Share via


Walkthrough: Extending the CRT to add customer preference data for Retail clients

Important

This content is archived and is not being updated. For the latest documentation, see Microsoft Dynamics 365 product documentation. For the latest release plans, see Dynamics 365 and Microsoft Power Platform release plans.

Applies To: Microsoft Dynamics AX 2012 R3

To add the RetailCustPreferences table to the Commerce Runtime (CRT), you can make the modifications in the CRT yourself or you can add code to and re-run CommerceRuntimeScripts.sql. This topic describes the modifications and includes the entire text of CommerceRuntimeScripts.sql.

Walkthrough

Prerequisites

Modify the CRT

Set up and run a subjob to synchronize values for the new data field to the online channel database

Update the SQL Server stored procedure code

Resources

Online Store

Retail Modern Point of Sale

Prerequisites

These walkthroughs illustrate adding a field to a retail channel that enables customers to opt in to receive special offers by email. In this scenario, the retailer wants to indicate whether customers wish to receive email about special offers, either in an online store or in a modern POS client. The walkthroughs should be completed in the following order:

  1. Walkthrough: Adding a table for customer preferences to the AX 2012 database

  2. Walkthrough: Extending the CRT to add customer preference data for Retail clients

  3. Walkthrough: Extending retail data distribution infrastructure for customer preferences

  4. Walkthrough: Adding customer preferences to the Retail online sample store (online store only)

Modify the CRT

In the CRT, each entity is represented by a key-value pair. The key has the name of the column name in the table or view. The value is the value of the field for that column in the view. When you create the new fields in the CustomersView, the new key-value pair is included in the property bag. For more information see Customize the Data in a Commerce Entity.

Next, you will modify the stored procedure associated with the CustomersView view. This enables writing the data back to Microsoft Dynamics AX.

Dn720790.collapse_all(en-us,AX.60).gifCreate the new table in the channel database for the CRT to use

  1. Open Microsoft SQL Server Management Studio.

  2. In Object Explorer, expand the database node for and then expand the Tables node.

  3. Scroll down to the RetailCustPreferences table. Right-click the table, point to Script table as, then point to CREATE to, and then click New Query Editor Window.

  4. Go to the top line of the generated script and change the USE statement to the name of the channel database (aka the CRT database). The default name for this database after you install Microsoft Dynamics AX 2012 R3 is AxRetailSP. If that is the name of your channel database, the following example illustrates the USE statement.

    USE [AxRetailSP]

  5. Remove the PARTITION field.

  6. Change all instances of dbo to ax for the field names.

  7. Click Execute or press F5 to run the script.

Dn720790.collapse_all(en-us,AX.60).gifModify the CustomersView view in the channel database

You must add the EmailOptIn field to the CustomersView view in the channel database to make the new field available in the Retail online sample store.

  1. Open Microsoft SQL Server Management Studio. You must be logged on to the computer with the account that has permissions to modify the Retail databases.

  2. In Object Explorer, expand the database node for your channel database. The default name for this database after you install Microsoft Dynamics AX 2012 R3 is AxRetailSP.

  3. Expand the Views node and right-click dbo.Customersview.

  4. Click Script View as, ALTER to, New Query Editor Window.

  5. Add the following lines to the query to include the EmailOptIn field in the CustomersView.

    (SELECT    TOP (1) EMAILOPTIN
          FROM          dbo.RetailCustPreferences
          WHERE      (ACCOUNTNUM = dbo.CUSTTABLE.ACCOUNTNUM)) AS EmailOptIn, 
    
  6. Save your changes and re-run the query.

Set up and run a subjob to synchronize values for the new data field to the online channel database

You run jobs to synchronize data from AX 2012 to the CRT. For more information, see Configure jobs and subjobs in Retail Scheduler.

In the AX 2012 Distribution schedule form, create a subjob under the Customer job for RetailCustPreferences. Fun the jobs that synchronize initial data in AX 2012 to the distribution location. For more information see Configure table distribution settings for Retail data and Configure and schedule retail data distribution.

Update the SQL Server stored procedure code

This section contains the entire contents of CommerceRuntimeScripts.sql. There are four places where code has been inserted. Search for SDKSAMPLE_CUSTOMERPREFERENCES to find them.

Dn720790.collapse_all(en-us,AX.60).gifCode

-- SAMPLE CODE NOTICE
--
-- THIS SAMPLE CODE IS MADE AVAILABLE AS IS.  MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF
-- RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY.  THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER.  NO TECHNICAL
-- SUPPORT IS PROVIDED.  YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO.
-- Create the database schemas
IF NOT EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = 'ax')
BEGIN
  PRINT 'Creating AX database schema ..'
  EXECUTE('CREATE SCHEMA ax');
END;

IF NOT EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = 'crt')
BEGIN
  PRINT 'Creating CRT database schema ..'
  EXECUTE('CREATE SCHEMA crt');
END;

-- Creating role UsersRole
PRINT N'Creating role UsersRole';

GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'UsersRole' AND type = 'R')
BEGIN
    CREATE ROLE [UsersRole] AUTHORIZATION [dbo]
END
IF (@@ERROR != 0)
    PRINT N'FAILED to create role UsersRole.'

GO
PRINT N'Finished creating role UsersRole'
GO


-- Creating role PublishersRole
PRINT N'Creating role PublishersRole';

GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'PublishersRole' AND type = 'R')
BEGIN
    CREATE ROLE [PublishersRole] AUTHORIZATION [dbo]
END
IF (@@ERROR != 0)
    PRINT N'FAILED to create role PublishersRole.'

GO
PRINT N'Finished creating role PublishersRole'
GO


-- Creating role DataSyncUsersRole
PRINT N'Creating role DataSyncUsersRole';

GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'DataSyncUsersRole' AND type = 'R')
BEGIN
    CREATE ROLE [DataSyncUsersRole] AUTHORIZATION [dbo]
END
IF (@@ERROR != 0)
    PRINT N'FAILED to create role DataSyncUsersRole.'

GO
PRINT N'Finished creating role DataSyncUsersRole'
GO


-- Creating role db_executor
PRINT N'Creating role db_executor';

GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'db_executor' AND type = 'R')
BEGIN
    CREATE ROLE [db_executor] AUTHORIZATION [dbo]
END
IF (@@ERROR != 0)
    PRINT N'FAILED to create role db_executor.'

GO
PRINT N'Finished creating role db_executor'
GO

GRANT EXECUTE TO [db_executor]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ACCOUNTANT_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ACCOUNTANT_BR](
[RECID] [bigint] NOT NULL,
[CNPJNUM_BR] [nvarchar](20) NOT NULL,
[CPFNUM_BR] [nvarchar](20) NOT NULL,
[CRCNUM_BR] [nvarchar](20) NOT NULL,
[NAME] [nvarchar](100) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1701316395_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1701316395_1138566887] UNIQUE NONCLUSTERED 
(
[CPFNUM_BR] ASC,
[CRCNUM_BR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANT_BR_CNPJNUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANT_BR] ADD  CONSTRAINT [DF_ACCOUNTANT_BR_CNPJNUM_BR]  DEFAULT ('') FOR [CNPJNUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANT_BR_CPFNUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANT_BR] ADD  CONSTRAINT [DF_ACCOUNTANT_BR_CPFNUM_BR]  DEFAULT ('') FOR [CPFNUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANT_BR_CRCNUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANT_BR] ADD  CONSTRAINT [DF_ACCOUNTANT_BR_CRCNUM_BR]  DEFAULT ('') FOR [CRCNUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANT_BR_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANT_BR] ADD  CONSTRAINT [DF_ACCOUNTANT_BR_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ACCOUNTANT_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ACCOUNTANTLOGISTICSLOCATION_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ACCOUNTANTLOGISTICSLOCATION_BR](
[RECID] [bigint] NOT NULL,
[ACCOUNTANT] [bigint] NOT NULL,
[ISDEFAULT] [int] NOT NULL,
[ISPOSTALADDRESS] [int] NOT NULL,
[ISPRIMARY] [int] NOT NULL,
[ISPRIVATE] [int] NOT NULL,
[LOCATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1306553661_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1306553661_1643352582] UNIQUE NONCLUSTERED 
(
[ACCOUNTANT] ASC,
[LOCATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATION_BR_ACCOUNTANT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATION_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATION_BR_ACCOUNTANT]  DEFAULT ((0)) FOR [ACCOUNTANT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISDEFAULT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATION_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISDEFAULT]  DEFAULT ((0)) FOR [ISDEFAULT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISPOSTALADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATION_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISPOSTALADDRESS]  DEFAULT ((0)) FOR [ISPOSTALADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISPRIMARY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATION_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISPRIMARY]  DEFAULT ((0)) FOR [ISPRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISPRIVATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATION_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATION_BR_ISPRIVATE]  DEFAULT ((0)) FOR [ISPRIVATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATION_BR_LOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATION_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATION_BR_LOCATION]  DEFAULT ((0)) FOR [LOCATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ACCOUNTANTLOGISTICSLOCATION_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR](
[RECID] [bigint] NOT NULL,
[ACCOUNTANTLOGISTICSLOCATION] [bigint] NOT NULL,
[LOCATIONROLE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1576658753_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1576658753_-2080191547] UNIQUE NONCLUSTERED 
(
[LOCATIONROLE] ASC,
[ACCOUNTANTLOGISTICSLOCATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATIONROLE_BR_ACCOUNTANTLOGISTICSLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATIONROLE_BR_ACCOUNTANTLOGISTICSLOCATION]  DEFAULT ((0)) FOR [ACCOUNTANTLOGISTICSLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ACCOUNTANTLOGISTICSLOCATIONROLE_BR_LOCATIONROLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR] ADD  CONSTRAINT [DF_ACCOUNTANTLOGISTICSLOCATIONROLE_BR_LOCATIONROLE]  DEFAULT ((0)) FOR [LOCATIONROLE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[BRAZILPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[BRAZILPARAMETERS](
[RECID] [bigint] NOT NULL,
[APPROXTAXVALUESOURCE] [nvarchar](60) NOT NULL,
[KEY] [int] NOT NULL,
[LINKEDFISCALDOCUMENTMODEL02COFINS] [nvarchar](10) NOT NULL,
[LINKEDFISCALDOCUMENTMODEL02ICMS] [nvarchar](10) NOT NULL,
[LINKEDFISCALDOCUMENTMODEL02PIS] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1632568128_-1273337705] PRIMARY KEY CLUSTERED 
(
[KEY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_BRAZILPARAMETERS_APPROXTAXVALUESOURCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[BRAZILPARAMETERS] ADD  CONSTRAINT [DF_BRAZILPARAMETERS_APPROXTAXVALUESOURCE]  DEFAULT ('') FOR [APPROXTAXVALUESOURCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_BRAZILPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[BRAZILPARAMETERS] ADD  CONSTRAINT [DF_BRAZILPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_BRAZILPARAMETERS_LINKEDFISCALDOCUMENTMODEL02COFINS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[BRAZILPARAMETERS] ADD  CONSTRAINT [DF_BRAZILPARAMETERS_LINKEDFISCALDOCUMENTMODEL02COFINS]  DEFAULT ('') FOR [LINKEDFISCALDOCUMENTMODEL02COFINS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_BRAZILPARAMETERS_LINKEDFISCALDOCUMENTMODEL02ICMS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[BRAZILPARAMETERS] ADD  CONSTRAINT [DF_BRAZILPARAMETERS_LINKEDFISCALDOCUMENTMODEL02ICMS]  DEFAULT ('') FOR [LINKEDFISCALDOCUMENTMODEL02ICMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_BRAZILPARAMETERS_LINKEDFISCALDOCUMENTMODEL02PIS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[BRAZILPARAMETERS] ADD  CONSTRAINT [DF_BRAZILPARAMETERS_LINKEDFISCALDOCUMENTMODEL02PIS]  DEFAULT ('') FOR [LINKEDFISCALDOCUMENTMODEL02PIS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[BRAZILPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[COMPANYINFO]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[COMPANYINFO](
[RECID] [bigint] NOT NULL,
[DATAAREA] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-885798727_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-885798727_-1273337705] UNIQUE NONCLUSTERED 
(
[DATAAREA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_COMPANYINFO_DATAAREA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[COMPANYINFO] ADD  CONSTRAINT [DF_COMPANYINFO_DATAAREA]  DEFAULT ('') FOR [DATAAREA]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[COMPANYINFO] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[CURRENCY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[CURRENCY](
[RECID] [bigint] NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[CURRENCYCODEISO] [nvarchar](3) NOT NULL,
[ROUNDOFFPRICE] [numeric](32, 16) NOT NULL,
[ROUNDOFFPURCH] [numeric](32, 16) NOT NULL,
[ROUNDOFFSALES] [numeric](32, 16) NOT NULL,
[ROUNDOFFTYPEPRICE] [int] NOT NULL,
[ROUNDOFFTYPEPURCH] [int] NOT NULL,
[ROUNDOFFTYPESALES] [int] NOT NULL,
[SYMBOL] [nvarchar](5) NOT NULL,
[TXT] [nvarchar](60) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1650711867_1955152843] PRIMARY KEY CLUSTERED 
(
[CURRENCYCODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_CURRENCYCODEISO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_CURRENCYCODEISO]  DEFAULT ('') FOR [CURRENCYCODEISO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_ROUNDOFFPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_ROUNDOFFPRICE]  DEFAULT ((0)) FOR [ROUNDOFFPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_ROUNDOFFPURCH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_ROUNDOFFPURCH]  DEFAULT ((0)) FOR [ROUNDOFFPURCH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_ROUNDOFFSALES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_ROUNDOFFSALES]  DEFAULT ((0)) FOR [ROUNDOFFSALES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_ROUNDOFFTYPEPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_ROUNDOFFTYPEPRICE]  DEFAULT ((0)) FOR [ROUNDOFFTYPEPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_ROUNDOFFTYPEPURCH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_ROUNDOFFTYPEPURCH]  DEFAULT ((0)) FOR [ROUNDOFFTYPEPURCH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_ROUNDOFFTYPESALES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_ROUNDOFFTYPESALES]  DEFAULT ((0)) FOR [ROUNDOFFTYPESALES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_SYMBOL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_SYMBOL]  DEFAULT ('') FOR [SYMBOL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CURRENCY_TXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CURRENCY] ADD  CONSTRAINT [DF_CURRENCY_TXT]  DEFAULT ('') FOR [TXT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[CURRENCY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[CUSTGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[CUSTGROUP](
[RECID] [bigint] NOT NULL,
[CUSTGROUP] [nvarchar](10) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1620308668_1086213528] PRIMARY KEY CLUSTERED 
(
[CUSTGROUP] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTGROUP_CUSTGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTGROUP] ADD  CONSTRAINT [DF_CUSTGROUP_CUSTGROUP]  DEFAULT ('') FOR [CUSTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTGROUP_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTGROUP] ADD  CONSTRAINT [DF_CUSTGROUP_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[CUSTGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[CUSTPACKINGSLIPJOUR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[CUSTPACKINGSLIPJOUR](
[RECID] [bigint] NOT NULL,
[PACKINGSLIPID] [nvarchar](20) NOT NULL,
[SALESID] [nvarchar](20) NOT NULL,
[SHIPCARRIERID] [nvarchar](10) NOT NULL,
[SOURCEDOCUMENTHEADER] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_868055170_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_868055170_1531416702] UNIQUE NONCLUSTERED 
(
[SOURCEDOCUMENTHEADER] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPJOUR_PACKINGSLIPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPJOUR] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPJOUR_PACKINGSLIPID]  DEFAULT ('') FOR [PACKINGSLIPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPJOUR_SALESID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPJOUR] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPJOUR_SALESID]  DEFAULT ('') FOR [SALESID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPJOUR_SHIPCARRIERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPJOUR] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPJOUR_SHIPCARRIERID]  DEFAULT ('') FOR [SHIPCARRIERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPJOUR_SOURCEDOCUMENTHEADER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPJOUR] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPJOUR_SOURCEDOCUMENTHEADER]  DEFAULT ((0)) FOR [SOURCEDOCUMENTHEADER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPJOUR_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPJOUR] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPJOUR_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[CUSTPACKINGSLIPJOUR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[CUSTPACKINGSLIPTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[CUSTPACKINGSLIPTRANS](
[RECID] [bigint] NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[ORDERED] [numeric](32, 16) NOT NULL,
[PACKINGSLIPID] [nvarchar](20) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[REMAIN] [numeric](32, 16) NOT NULL,
[SALESID] [nvarchar](20) NOT NULL,
[SOURCEDOCUMENTLINE] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_535734996_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_535734996_527453709] UNIQUE NONCLUSTERED 
(
[SOURCEDOCUMENTLINE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_ORDERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_ORDERED]  DEFAULT ((0)) FOR [ORDERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_PACKINGSLIPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_PACKINGSLIPID]  DEFAULT ('') FOR [PACKINGSLIPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_REMAIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_REMAIN]  DEFAULT ((0)) FOR [REMAIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_SALESID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_SALESID]  DEFAULT ('') FOR [SALESID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_SOURCEDOCUMENTLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_SOURCEDOCUMENTLINE]  DEFAULT ((0)) FOR [SOURCEDOCUMENTLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTPACKINGSLIPTRANS_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTPACKINGSLIPTRANS] ADD  CONSTRAINT [DF_CUSTPACKINGSLIPTRANS_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[CUSTPACKINGSLIPTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[CUSTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[CUSTTABLE](
[RECID] [bigint] NOT NULL,
[ACCOUNTNUM] [nvarchar](20) NOT NULL,
[ACCOUNTSTATEMENT] [int] NOT NULL,
[BANKACCOUNT] [nvarchar](10) NOT NULL,
[BANKCENTRALBANKPURPOSECODE] [nvarchar](10) NOT NULL,
[BANKCENTRALBANKPURPOSETEXT] [nvarchar](140) NOT NULL,
[BLOCKED] [int] NOT NULL,
[CASHDISC] [nvarchar](10) NOT NULL,
[CLEARINGPERIOD] [nvarchar](10) NOT NULL,
[CNPJCPFNUM_BR] [nvarchar](20) NOT NULL,
[COMMISSIONGROUP] [nvarchar](10) NOT NULL,
[CONTACTPERSONID] [nvarchar](20) NOT NULL,
[CREDITMAX] [numeric](32, 16) NOT NULL,
[CREDITRATING] [nvarchar](10) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[CUSTGROUP] [nvarchar](10) NOT NULL,
[CUSTITEMGROUPID] [nvarchar](10) NOT NULL,
[DESTINATIONCODEID] [nvarchar](10) NOT NULL,
[DLVMODE] [nvarchar](10) NOT NULL,
[DLVTERM] [nvarchar](10) NOT NULL,
[ENDDISC] [nvarchar](10) NOT NULL,
[FORECASTDMPINCLUDE] [int] NOT NULL,
[FREIGHTZONE] [nvarchar](10) NOT NULL,
[IDENTIFICATIONNUMBER] [nvarchar](50) NOT NULL,
[IENUM_BR] [nvarchar](20) NOT NULL,
[INCLTAX] [int] NOT NULL,
[INVENTLOCATION] [nvarchar](10) NOT NULL,
[INVENTSITEID] [nvarchar](10) NOT NULL,
[INVOICEACCOUNT] [nvarchar](20) NOT NULL,
[INVOICEADDRESS] [int] NOT NULL,
[LINEDISC] [nvarchar](10) NOT NULL,
[LINEOFBUSINESSID] [nvarchar](10) NOT NULL,
[MANDATORYCREDITLIMIT] [int] NOT NULL,
[MARKUPGROUP] [nvarchar](10) NOT NULL,
[MULTILINEDISC] [nvarchar](10) NOT NULL,
[NUMBERSEQUENCEGROUP] [nvarchar](10) NOT NULL,
[ONETIMECUSTOMER] [int] NOT NULL,
[ORGID] [nvarchar](10) NOT NULL,
[OURACCOUNTNUM] [nvarchar](20) NOT NULL,
[PACKMATERIALFEELICENSENUM] [nvarchar](20) NOT NULL,
[PARTY] [bigint] NOT NULL,
[PAYMDAYID] [nvarchar](10) NOT NULL,
[PAYMMODE] [nvarchar](10) NOT NULL,
[PAYMSPEC] [nvarchar](10) NOT NULL,
[PAYMTERMID] [nvarchar](10) NOT NULL,
[PBACUSTGROUPID] [nvarchar](10) NOT NULL,
[PRICEGROUP] [nvarchar](10) NOT NULL,
[SALESGROUP] [nvarchar](10) NOT NULL,
[SALESPOOLID] [nvarchar](10) NOT NULL,
[STATISTICSGROUP] [nvarchar](10) NOT NULL,
[SUFRAMA_BR] [int] NOT NULL,
[SUFRAMANUMBER_BR] [nvarchar](10) NOT NULL,
[SUPPITEMGROUPID] [nvarchar](10) NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXLICENSENUM] [nvarchar](20) NOT NULL,
[USEPURCHREQUEST] [int] NOT NULL,
[VATNUM] [nvarchar](20) NOT NULL,
[VENDACCOUNT] [nvarchar](20) NOT NULL,
[WEBSALESORDERDISPLAY] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_880715539_-2094443312] PRIMARY KEY CLUSTERED 
(
[ACCOUNTNUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_880715539_237279918] UNIQUE NONCLUSTERED 
(
[PARTY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_ACCOUNTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_ACCOUNTNUM]  DEFAULT ('') FOR [ACCOUNTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_ACCOUNTSTATEMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_ACCOUNTSTATEMENT]  DEFAULT ((0)) FOR [ACCOUNTSTATEMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_BANKACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_BANKACCOUNT]  DEFAULT ('') FOR [BANKACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_BANKCENTRALBANKPURPOSECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_BANKCENTRALBANKPURPOSECODE]  DEFAULT ('') FOR [BANKCENTRALBANKPURPOSECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_BANKCENTRALBANKPURPOSETEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_BANKCENTRALBANKPURPOSETEXT]  DEFAULT ('') FOR [BANKCENTRALBANKPURPOSETEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_BLOCKED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_BLOCKED]  DEFAULT ((0)) FOR [BLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CASHDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CASHDISC]  DEFAULT ('') FOR [CASHDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CLEARINGPERIOD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CLEARINGPERIOD]  DEFAULT ('') FOR [CLEARINGPERIOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CNPJCPFNUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CNPJCPFNUM_BR]  DEFAULT ('') FOR [CNPJCPFNUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_COMMISSIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_COMMISSIONGROUP]  DEFAULT ('') FOR [COMMISSIONGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CONTACTPERSONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CONTACTPERSONID]  DEFAULT ('') FOR [CONTACTPERSONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CREDITMAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CREDITMAX]  DEFAULT ((0)) FOR [CREDITMAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CREDITRATING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CREDITRATING]  DEFAULT ('') FOR [CREDITRATING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CUSTGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CUSTGROUP]  DEFAULT ('') FOR [CUSTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CUSTITEMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CUSTITEMGROUPID]  DEFAULT ('') FOR [CUSTITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_DESTINATIONCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_DESTINATIONCODEID]  DEFAULT ('') FOR [DESTINATIONCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_DLVMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_DLVMODE]  DEFAULT ('') FOR [DLVMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_DLVTERM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_DLVTERM]  DEFAULT ('') FOR [DLVTERM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_ENDDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_ENDDISC]  DEFAULT ('') FOR [ENDDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_FORECASTDMPINCLUDE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_FORECASTDMPINCLUDE]  DEFAULT ((0)) FOR [FORECASTDMPINCLUDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_FREIGHTZONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_FREIGHTZONE]  DEFAULT ('') FOR [FREIGHTZONE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_IDENTIFICATIONNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_IDENTIFICATIONNUMBER]  DEFAULT ('') FOR [IDENTIFICATIONNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_IENUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_IENUM_BR]  DEFAULT ('') FOR [IENUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_INCLTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_INCLTAX]  DEFAULT ((0)) FOR [INCLTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_INVENTLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_INVENTLOCATION]  DEFAULT ('') FOR [INVENTLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_INVENTSITEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_INVENTSITEID]  DEFAULT ('') FOR [INVENTSITEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_INVOICEACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_INVOICEACCOUNT]  DEFAULT ('') FOR [INVOICEACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_INVOICEADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_INVOICEADDRESS]  DEFAULT ((0)) FOR [INVOICEADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_LINEDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_LINEDISC]  DEFAULT ('') FOR [LINEDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_LINEOFBUSINESSID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_LINEOFBUSINESSID]  DEFAULT ('') FOR [LINEOFBUSINESSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_MANDATORYCREDITLIMIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_MANDATORYCREDITLIMIT]  DEFAULT ((0)) FOR [MANDATORYCREDITLIMIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_MARKUPGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_MARKUPGROUP]  DEFAULT ('') FOR [MARKUPGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_MULTILINEDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_MULTILINEDISC]  DEFAULT ('') FOR [MULTILINEDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_NUMBERSEQUENCEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_NUMBERSEQUENCEGROUP]  DEFAULT ('') FOR [NUMBERSEQUENCEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_ONETIMECUSTOMER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_ONETIMECUSTOMER]  DEFAULT ((0)) FOR [ONETIMECUSTOMER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_ORGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_ORGID]  DEFAULT ('') FOR [ORGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_OURACCOUNTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_OURACCOUNTNUM]  DEFAULT ('') FOR [OURACCOUNTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PACKMATERIALFEELICENSENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PACKMATERIALFEELICENSENUM]  DEFAULT ('') FOR [PACKMATERIALFEELICENSENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PARTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PARTY]  DEFAULT ((0)) FOR [PARTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PAYMDAYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PAYMDAYID]  DEFAULT ('') FOR [PAYMDAYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PAYMMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PAYMMODE]  DEFAULT ('') FOR [PAYMMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PAYMSPEC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PAYMSPEC]  DEFAULT ('') FOR [PAYMSPEC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PAYMTERMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PAYMTERMID]  DEFAULT ('') FOR [PAYMTERMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PBACUSTGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PBACUSTGROUPID]  DEFAULT ('') FOR [PBACUSTGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_PRICEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_PRICEGROUP]  DEFAULT ('') FOR [PRICEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_SALESGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_SALESGROUP]  DEFAULT ('') FOR [SALESGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_SALESPOOLID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_SALESPOOLID]  DEFAULT ('') FOR [SALESPOOLID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_STATISTICSGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_STATISTICSGROUP]  DEFAULT ('') FOR [STATISTICSGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_SUFRAMA_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_SUFRAMA_BR]  DEFAULT ((0)) FOR [SUFRAMA_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_SUFRAMANUMBER_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_SUFRAMANUMBER_BR]  DEFAULT ('') FOR [SUFRAMANUMBER_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_SUPPITEMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_SUPPITEMGROUPID]  DEFAULT ('') FOR [SUPPITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_TAXLICENSENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_TAXLICENSENUM]  DEFAULT ('') FOR [TAXLICENSENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_USEPURCHREQUEST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_USEPURCHREQUEST]  DEFAULT ((0)) FOR [USEPURCHREQUEST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_VATNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_VATNUM]  DEFAULT ('') FOR [VATNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_VENDACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_VENDACCOUNT]  DEFAULT ('') FOR [VENDACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_WEBSALESORDERDISPLAY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_WEBSALESORDERDISPLAY]  DEFAULT ((0)) FOR [WEBSALESORDERDISPLAY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_CUSTTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[CUSTTABLE] ADD  CONSTRAINT [DF_CUSTTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[CUSTTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[DIRADDRESSBOOK]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[DIRADDRESSBOOK](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[NAME] [nvarchar](10) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2048506466_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_2048506466_910918470] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRADDRESSBOOK_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRADDRESSBOOK] ADD  CONSTRAINT [DF_DIRADDRESSBOOK_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRADDRESSBOOK_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRADDRESSBOOK] ADD  CONSTRAINT [DF_DIRADDRESSBOOK_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRADDRESSBOOK_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRADDRESSBOOK] ADD  CONSTRAINT [DF_DIRADDRESSBOOK_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRADDRESSBOOK_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRADDRESSBOOK] ADD  CONSTRAINT [DF_DIRADDRESSBOOK_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[DIRADDRESSBOOK] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[DIRADDRESSBOOKPARTY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[DIRADDRESSBOOKPARTY](
[RECID] [bigint] NOT NULL,
[ADDRESSBOOK] [bigint] NOT NULL,
[PARTY] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_996533606_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_996533606_589292146] UNIQUE NONCLUSTERED 
(
[PARTY] ASC,
[ADDRESSBOOK] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRADDRESSBOOKPARTY_ADDRESSBOOK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRADDRESSBOOKPARTY] ADD  CONSTRAINT [DF_DIRADDRESSBOOKPARTY_ADDRESSBOOK]  DEFAULT ((0)) FOR [ADDRESSBOOK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRADDRESSBOOKPARTY_PARTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRADDRESSBOOKPARTY] ADD  CONSTRAINT [DF_DIRADDRESSBOOKPARTY_PARTY]  DEFAULT ((0)) FOR [PARTY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[DIRADDRESSBOOKPARTY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[DIRPARTYLOCATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[DIRPARTYLOCATION](
[RECID] [bigint] NOT NULL,
[ATTENTIONTOADDRESSLINE] [nvarchar](255) NOT NULL,
[ISLOCATIONOWNER] [int] NOT NULL,
[ISPOSTALADDRESS] [int] NOT NULL,
[ISPRIMARY] [int] NOT NULL,
[ISPRIVATE] [int] NOT NULL,
[LOCATION] [bigint] NOT NULL,
[PARTY] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1696019432_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1696019432_-1627387636] UNIQUE NONCLUSTERED 
(
[PARTY] ASC,
[LOCATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATION_ATTENTIONTOADDRESSLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATION] ADD  CONSTRAINT [DF_DIRPARTYLOCATION_ATTENTIONTOADDRESSLINE]  DEFAULT ('') FOR [ATTENTIONTOADDRESSLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATION_ISLOCATIONOWNER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATION] ADD  CONSTRAINT [DF_DIRPARTYLOCATION_ISLOCATIONOWNER]  DEFAULT ((0)) FOR [ISLOCATIONOWNER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATION_ISPOSTALADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATION] ADD  CONSTRAINT [DF_DIRPARTYLOCATION_ISPOSTALADDRESS]  DEFAULT ((0)) FOR [ISPOSTALADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATION_ISPRIMARY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATION] ADD  CONSTRAINT [DF_DIRPARTYLOCATION_ISPRIMARY]  DEFAULT ((0)) FOR [ISPRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATION_ISPRIVATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATION] ADD  CONSTRAINT [DF_DIRPARTYLOCATION_ISPRIVATE]  DEFAULT ((0)) FOR [ISPRIVATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATION_LOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATION] ADD  CONSTRAINT [DF_DIRPARTYLOCATION_LOCATION]  DEFAULT ((0)) FOR [LOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATION_PARTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATION] ADD  CONSTRAINT [DF_DIRPARTYLOCATION_PARTY]  DEFAULT ((0)) FOR [PARTY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[DIRPARTYLOCATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[DIRPARTYLOCATIONROLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[DIRPARTYLOCATIONROLE](
[RECID] [bigint] NOT NULL,
[LOCATIONROLE] [bigint] NOT NULL,
[PARTYLOCATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_586983440_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_586983440_-1706136147] UNIQUE NONCLUSTERED 
(
[PARTYLOCATION] ASC,
[LOCATIONROLE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATIONROLE_LOCATIONROLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATIONROLE] ADD  CONSTRAINT [DF_DIRPARTYLOCATIONROLE_LOCATIONROLE]  DEFAULT ((0)) FOR [LOCATIONROLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYLOCATIONROLE_PARTYLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYLOCATIONROLE] ADD  CONSTRAINT [DF_DIRPARTYLOCATIONROLE_PARTYLOCATION]  DEFAULT ((0)) FOR [PARTYLOCATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[DIRPARTYLOCATIONROLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[DIRPARTYTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[DIRPARTYTABLE](
[RECID] [bigint] NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[KNOWNAS] [nvarchar](100) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[NAME] [nvarchar](100) NOT NULL,
[NAMEALIAS] [nvarchar](20) NOT NULL,
[PARTYNUMBER] [nvarchar](40) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-747565321_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-747565321_315771746] UNIQUE NONCLUSTERED 
(
[PARTYNUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_KNOWNAS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_KNOWNAS]  DEFAULT ('') FOR [KNOWNAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_NAMEALIAS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_NAMEALIAS]  DEFAULT ('') FOR [NAMEALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_PARTYNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_PARTYNUMBER]  DEFAULT ('') FOR [PARTYNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPARTYTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPARTYTABLE] ADD  CONSTRAINT [DF_DIRPARTYTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[DIRPARTYTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[DIRPERSONNAME]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[DIRPERSONNAME](
[RECID] [bigint] NOT NULL,
[FIRSTNAME] [nvarchar](25) NOT NULL,
[LASTNAME] [nvarchar](25) NOT NULL,
[MIDDLENAME] [nvarchar](25) NOT NULL,
[PERSON] [bigint] NOT NULL,
[VALIDFROM] [datetime] NOT NULL,
[VALIDFROMTZID] [int] NOT NULL,
[VALIDTO] [datetime] NOT NULL,
[VALIDTOTZID] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_600258457_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_600258457_-1645802954] UNIQUE NONCLUSTERED 
(
[PERSON] ASC,
[VALIDFROM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_FIRSTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_FIRSTNAME]  DEFAULT ('') FOR [FIRSTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_LASTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_LASTNAME]  DEFAULT ('') FOR [LASTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_MIDDLENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_MIDDLENAME]  DEFAULT ('') FOR [MIDDLENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_PERSON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_PERSON]  DEFAULT ((0)) FOR [PERSON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_VALIDFROM]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_VALIDFROMTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_VALIDFROMTZID]  DEFAULT ((37001)) FOR [VALIDFROMTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_VALIDTO]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DIRPERSONNAME_VALIDTOTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DIRPERSONNAME] ADD  CONSTRAINT [DF_DIRPERSONNAME_VALIDTOTZID]  DEFAULT ((37001)) FOR [VALIDTOTZID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[DIRPERSONNAME] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[DLVMODE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[DLVMODE](
[RECID] [bigint] NOT NULL,
[CODE] [nvarchar](10) NOT NULL,
[MARKUPGROUP] [nvarchar](10) NOT NULL,
[SHIPCARRIERACCOUNTCODE] [nvarchar](20) NOT NULL,
[SHIPCARRIERDLVTYPE] [int] NOT NULL,
[SHIPCARRIERID] [nvarchar](10) NOT NULL,
[SHIPCARRIERNAME] [nvarchar](20) NOT NULL,
[TXT] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1052277315_776425418] PRIMARY KEY CLUSTERED 
(
[CODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DLVMODE_CODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DLVMODE] ADD  CONSTRAINT [DF_DLVMODE_CODE]  DEFAULT ('') FOR [CODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DLVMODE_MARKUPGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DLVMODE] ADD  CONSTRAINT [DF_DLVMODE_MARKUPGROUP]  DEFAULT ('') FOR [MARKUPGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DLVMODE_SHIPCARRIERACCOUNTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DLVMODE] ADD  CONSTRAINT [DF_DLVMODE_SHIPCARRIERACCOUNTCODE]  DEFAULT ('') FOR [SHIPCARRIERACCOUNTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DLVMODE_SHIPCARRIERDLVTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DLVMODE] ADD  CONSTRAINT [DF_DLVMODE_SHIPCARRIERDLVTYPE]  DEFAULT ((0)) FOR [SHIPCARRIERDLVTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DLVMODE_SHIPCARRIERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DLVMODE] ADD  CONSTRAINT [DF_DLVMODE_SHIPCARRIERID]  DEFAULT ('') FOR [SHIPCARRIERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DLVMODE_SHIPCARRIERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DLVMODE] ADD  CONSTRAINT [DF_DLVMODE_SHIPCARRIERNAME]  DEFAULT ('') FOR [SHIPCARRIERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_DLVMODE_TXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[DLVMODE] ADD  CONSTRAINT [DF_DLVMODE_TXT]  DEFAULT ('') FOR [TXT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[DLVMODE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESATTRIBUTE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESATTRIBUTE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTEMODIFIER] [int] NOT NULL,
[ATTRIBUTETYPE] [bigint] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1988291431_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTE_ATTRIBUTEMODIFIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTE] ADD  CONSTRAINT [DF_ECORESATTRIBUTE_ATTRIBUTEMODIFIER]  DEFAULT ((0)) FOR [ATTRIBUTEMODIFIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTE_ATTRIBUTETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTE] ADD  CONSTRAINT [DF_ECORESATTRIBUTE_ATTRIBUTETYPE]  DEFAULT ((0)) FOR [ATTRIBUTETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTE] ADD  CONSTRAINT [DF_ECORESATTRIBUTE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESATTRIBUTE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESATTRIBUTEDEFAULTVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESATTRIBUTEDEFAULTVALUE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[VALUE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-306725327_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEDEFAULTVALUE_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEDEFAULTVALUE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEDEFAULTVALUE_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEDEFAULTVALUE_VALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEDEFAULTVALUE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEDEFAULTVALUE_VALUE]  DEFAULT ((0)) FOR [VALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESATTRIBUTEDEFAULTVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESATTRIBUTEGROUPATTRIBUTE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESATTRIBUTEGROUPATTRIBUTE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[ATTRIBUTEGROUP] [bigint] NOT NULL,
[DEFAULTVALUE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_461708616_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_461708616_-255559742] UNIQUE NONCLUSTERED 
(
[ATTRIBUTEGROUP] ASC,
[ATTRIBUTE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEGROUPATTRIBUTE_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEGROUPATTRIBUTE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEGROUPATTRIBUTE_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEGROUPATTRIBUTE_ATTRIBUTEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEGROUPATTRIBUTE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEGROUPATTRIBUTE_ATTRIBUTEGROUP]  DEFAULT ((0)) FOR [ATTRIBUTEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEGROUPATTRIBUTE_DEFAULTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEGROUPATTRIBUTE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEGROUPATTRIBUTE_DEFAULTVALUE]  DEFAULT ((0)) FOR [DEFAULTVALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESATTRIBUTEGROUPATTRIBUTE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESATTRIBUTETRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESATTRIBUTETRANSLATION](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[FRIENDLYNAME] [nvarchar](120) NOT NULL,
[HELPTEXT] [nvarchar](255) NOT NULL,
[LANGUAGE] [nvarchar](7) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1990869088_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1990869088_2081875952] UNIQUE NONCLUSTERED 
(
[ATTRIBUTE] ASC,
[LANGUAGE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETRANSLATION_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETRANSLATION] ADD  CONSTRAINT [DF_ECORESATTRIBUTETRANSLATION_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETRANSLATION] ADD  CONSTRAINT [DF_ECORESATTRIBUTETRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETRANSLATION_FRIENDLYNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETRANSLATION] ADD  CONSTRAINT [DF_ECORESATTRIBUTETRANSLATION_FRIENDLYNAME]  DEFAULT ('') FOR [FRIENDLYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETRANSLATION_HELPTEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETRANSLATION] ADD  CONSTRAINT [DF_ECORESATTRIBUTETRANSLATION_HELPTEXT]  DEFAULT ('') FOR [HELPTEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETRANSLATION_LANGUAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETRANSLATION] ADD  CONSTRAINT [DF_ECORESATTRIBUTETRANSLATION_LANGUAGE]  DEFAULT ('') FOR [LANGUAGE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESATTRIBUTETRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESATTRIBUTETYPE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESATTRIBUTETYPE](
[RECID] [bigint] NOT NULL,
[DATATYPE] [int] NOT NULL,
[ISENUMERATION] [int] NOT NULL,
[ISHIDDEN] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1716185735_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1716185735_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETYPE_DATATYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETYPE] ADD  CONSTRAINT [DF_ECORESATTRIBUTETYPE_DATATYPE]  DEFAULT ((0)) FOR [DATATYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETYPE_ISENUMERATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETYPE] ADD  CONSTRAINT [DF_ECORESATTRIBUTETYPE_ISENUMERATION]  DEFAULT ((0)) FOR [ISENUMERATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETYPE_ISHIDDEN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETYPE] ADD  CONSTRAINT [DF_ECORESATTRIBUTETYPE_ISHIDDEN]  DEFAULT ((0)) FOR [ISHIDDEN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTETYPE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTETYPE] ADD  CONSTRAINT [DF_ECORESATTRIBUTETYPE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESATTRIBUTETYPE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESATTRIBUTEVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESATTRIBUTEVALUE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[INSTANCEVALUE] [bigint] NOT NULL,
[VALUE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2006788166_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEVALUE_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEVALUE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEVALUE_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEVALUE_INSTANCEVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEVALUE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEVALUE_INSTANCEVALUE]  DEFAULT ((0)) FOR [INSTANCEVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESATTRIBUTEVALUE_VALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESATTRIBUTEVALUE] ADD  CONSTRAINT [DF_ECORESATTRIBUTEVALUE_VALUE]  DEFAULT ((0)) FOR [VALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESATTRIBUTEVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESBOOLEANVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESBOOLEANVALUE](
[RECID] [bigint] NOT NULL,
[BOOLEANVALUE] [int] NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1443038458_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESBOOLEANVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCATEGORY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCATEGORY](
[RECID] [bigint] NOT NULL,
[CATEGORYHIERARCHY] [bigint] NOT NULL,
[CHANGESTATUS] [int] NOT NULL,
[CODE] [nvarchar](20) NOT NULL,
[DEFAULTPROJECTGLOBALCATEGORY] [bigint] NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[ISACTIVE] [int] NOT NULL,
[ISCATEGORYATTRIBUTESINHERITED] [int] NOT NULL,
[ISTANGIBLE] [int] NOT NULL,
[LEVEL] [bigint] NOT NULL,
[NAME] [nvarchar](254) NOT NULL,
[NESTEDSETLEFT] [bigint] NOT NULL,
[NESTEDSETRIGHT] [bigint] NOT NULL,
[PARENTCATEGORY] [bigint] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1608894095_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1608894095_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC,
[CATEGORYHIERARCHY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_CATEGORYHIERARCHY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_CATEGORYHIERARCHY]  DEFAULT ((0)) FOR [CATEGORYHIERARCHY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_CHANGESTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_CHANGESTATUS]  DEFAULT ((0)) FOR [CHANGESTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_CODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_CODE]  DEFAULT ('') FOR [CODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_DEFAULTPROJECTGLOBALCATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_DEFAULTPROJECTGLOBALCATEGORY]  DEFAULT ((0)) FOR [DEFAULTPROJECTGLOBALCATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_ISACTIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_ISACTIVE]  DEFAULT ((0)) FOR [ISACTIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_ISCATEGORYATTRIBUTESINHERITED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_ISCATEGORYATTRIBUTESINHERITED]  DEFAULT ((0)) FOR [ISCATEGORYATTRIBUTESINHERITED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_ISTANGIBLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_ISTANGIBLE]  DEFAULT ((0)) FOR [ISTANGIBLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_LEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_LEVEL]  DEFAULT ((0)) FOR [LEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_NESTEDSETLEFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_NESTEDSETLEFT]  DEFAULT ((0)) FOR [NESTEDSETLEFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_NESTEDSETRIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_NESTEDSETRIGHT]  DEFAULT ((0)) FOR [NESTEDSETRIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_PARENTCATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_PARENTCATEGORY]  DEFAULT ((0)) FOR [PARENTCATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORY_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORY] ADD  CONSTRAINT [DF_ECORESCATEGORY_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCATEGORY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCATEGORYATTRIBUTEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCATEGORYATTRIBUTEGROUP](
[RECID] [bigint] NOT NULL,
[ATTRIBUTEGROUP] [bigint] NOT NULL,
[ATTRIBUTEGROUPTYPE] [int] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[MODIFIER] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1480101260_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1480101260_-1614480561] UNIQUE NONCLUSTERED 
(
[ATTRIBUTEGROUP] ASC,
[CATEGORY] ASC,
[MODIFIER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTEGROUP_ATTRIBUTEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTEGROUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTEGROUP_ATTRIBUTEGROUP]  DEFAULT ((0)) FOR [ATTRIBUTEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTEGROUP_ATTRIBUTEGROUPTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTEGROUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTEGROUP_ATTRIBUTEGROUPTYPE]  DEFAULT ((0)) FOR [ATTRIBUTEGROUPTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTEGROUP_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTEGROUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTEGROUP_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTEGROUP_MODIFIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTEGROUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTEGROUP_MODIFIER]  DEFAULT ((0)) FOR [MODIFIER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCATEGORYATTRIBUTEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCATEGORYATTRIBUTELOOKUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCATEGORYATTRIBUTELOOKUP](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[ATTRIBUTEGROUPATTRIBUTE] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[CATEGORYATTRIBUTE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1521133457_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1521133457_-2122509987] UNIQUE NONCLUSTERED 
(
[CATEGORY] ASC,
[ATTRIBUTE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTELOOKUP_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTELOOKUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTELOOKUP_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTELOOKUP_ATTRIBUTEGROUPATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTELOOKUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTELOOKUP_ATTRIBUTEGROUPATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTEGROUPATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTELOOKUP_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTELOOKUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTELOOKUP_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYATTRIBUTELOOKUP_CATEGORYATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYATTRIBUTELOOKUP] ADD  CONSTRAINT [DF_ECORESCATEGORYATTRIBUTELOOKUP_CATEGORYATTRIBUTE]  DEFAULT ((0)) FOR [CATEGORYATTRIBUTE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCATEGORYATTRIBUTELOOKUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCATEGORYHIERARCHY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCATEGORYHIERARCHY](
[RECID] [bigint] NOT NULL,
[HIERARCHYMODIFIER] [int] NOT NULL,
[NAME] [nvarchar](128) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-979199422_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-979199422_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYHIERARCHY_HIERARCHYMODIFIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYHIERARCHY] ADD  CONSTRAINT [DF_ECORESCATEGORYHIERARCHY_HIERARCHYMODIFIER]  DEFAULT ((0)) FOR [HIERARCHYMODIFIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYHIERARCHY_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYHIERARCHY] ADD  CONSTRAINT [DF_ECORESCATEGORYHIERARCHY_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCATEGORYHIERARCHY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCATEGORYHIERARCHYROLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCATEGORYHIERARCHYROLE](
[RECID] [bigint] NOT NULL,
[CATEGORYHIERARCHY] [bigint] NOT NULL,
[NAMEDCATEGORYHIERARCHYROLE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_686403814_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_686403814_-1937137019] UNIQUE NONCLUSTERED 
(
[NAMEDCATEGORYHIERARCHYROLE] ASC,
[CATEGORYHIERARCHY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYHIERARCHYROLE_CATEGORYHIERARCHY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYHIERARCHYROLE] ADD  CONSTRAINT [DF_ECORESCATEGORYHIERARCHYROLE_CATEGORYHIERARCHY]  DEFAULT ((0)) FOR [CATEGORYHIERARCHY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYHIERARCHYROLE_NAMEDCATEGORYHIERARCHYROLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYHIERARCHYROLE] ADD  CONSTRAINT [DF_ECORESCATEGORYHIERARCHYROLE_NAMEDCATEGORYHIERARCHYROLE]  DEFAULT ((0)) FOR [NAMEDCATEGORYHIERARCHYROLE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCATEGORYHIERARCHYROLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCATEGORYTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCATEGORYTRANSLATION](
[RECID] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](1000) NOT NULL,
[FRIENDLYNAME] [nvarchar](254) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[SEARCHTEXT] [nvarchar](254) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1435627490_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1435627490_-888948581] UNIQUE NONCLUSTERED 
(
[CATEGORY] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYTRANSLATION_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_ECORESCATEGORYTRANSLATION_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYTRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_ECORESCATEGORYTRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYTRANSLATION_FRIENDLYNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_ECORESCATEGORYTRANSLATION_FRIENDLYNAME]  DEFAULT ('') FOR [FRIENDLYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYTRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_ECORESCATEGORYTRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCATEGORYTRANSLATION_SEARCHTEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_ECORESCATEGORYTRANSLATION_SEARCHTEXT]  DEFAULT ('') FOR [SEARCHTEXT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCATEGORYTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCOLOR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCOLOR](
[RECID] [bigint] NOT NULL,
[NAME] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1935030618_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1935030618_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCOLOR_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCOLOR] ADD  CONSTRAINT [DF_ECORESCOLOR_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCOLOR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCONFIGURATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCONFIGURATION](
[RECID] [bigint] NOT NULL,
[NAME] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1043434429_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1043434429_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCONFIGURATION_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCONFIGURATION] ADD  CONSTRAINT [DF_ECORESCONFIGURATION_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCONFIGURATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESCURRENCYVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESCURRENCYVALUE](
[RECID] [bigint] NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[CURRENCYVALUE] [numeric](32, 16) NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1964246449_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESCURRENCYVALUE_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESCURRENCYVALUE] ADD  CONSTRAINT [DF_ECORESCURRENCYVALUE_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESCURRENCYVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESDATETIMEVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESDATETIMEVALUE](
[RECID] [bigint] NOT NULL,
[DATETIMEVALUE] [datetime] NULL,
[DATETIMEVALUETZID] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-809579165_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESDATETIMEVALUE_DATETIMEVALUETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESDATETIMEVALUE] ADD  CONSTRAINT [DF_ECORESDATETIMEVALUE_DATETIMEVALUETZID]  DEFAULT ((37001)) FOR [DATETIMEVALUETZID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESDATETIMEVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESDISTINCTPRODUCTVARIANT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESDISTINCTPRODUCTVARIANT](
[RECID] [bigint] NOT NULL,
[PRODUCTMASTER] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1270744131_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESDISTINCTPRODUCTVARIANT_PRODUCTMASTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESDISTINCTPRODUCTVARIANT] ADD  CONSTRAINT [DF_ECORESDISTINCTPRODUCTVARIANT_PRODUCTMASTER]  DEFAULT ((0)) FOR [PRODUCTMASTER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESDISTINCTPRODUCTVARIANT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESFLOATVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESFLOATVALUE](
[RECID] [bigint] NOT NULL,
[FLOATUNITOFMEASURE] [bigint] NULL,
[FLOATVALUE] [numeric](32, 16) NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_656793196_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESFLOATVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESINSTANCEVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESINSTANCEVALUE](
[RECID] [bigint] NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_544155415_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESINSTANCEVALUE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESINSTANCEVALUE] ADD  CONSTRAINT [DF_ECORESINSTANCEVALUE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESINSTANCEVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESINTVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESINTVALUE](
[RECID] [bigint] NOT NULL,
[INTUNITOFMEASURE] [bigint] NULL,
[INTVALUE] [int] NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_351683345_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESINTVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCT](
[RECID] [bigint] NOT NULL,
[DISPLAYPRODUCTNUMBER] [nvarchar](70) NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[PRODUCTTYPE] [int] NOT NULL,
[SEARCHNAME] [nvarchar](20) NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-441108210_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-441108210_532903983] UNIQUE NONCLUSTERED 
(
[DISPLAYPRODUCTNUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCT_DISPLAYPRODUCTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCT] ADD  CONSTRAINT [DF_ECORESPRODUCT_DISPLAYPRODUCTNUMBER]  DEFAULT ('') FOR [DISPLAYPRODUCTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCT_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCT] ADD  CONSTRAINT [DF_ECORESPRODUCT_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCT_PRODUCTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCT] ADD  CONSTRAINT [DF_ECORESPRODUCT_PRODUCTTYPE]  DEFAULT ((0)) FOR [PRODUCTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCT_SEARCHNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCT] ADD  CONSTRAINT [DF_ECORESPRODUCT_SEARCHNAME]  DEFAULT ('') FOR [SEARCHNAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTCATEGORY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTCATEGORY](
[RECID] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[CATEGORYHIERARCHY] [bigint] NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_474291702_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_474291702_345072579] UNIQUE NONCLUSTERED 
(
[PRODUCT] ASC,
[CATEGORY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTCATEGORY_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTCATEGORY] ADD  CONSTRAINT [DF_ECORESPRODUCTCATEGORY_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTCATEGORY_CATEGORYHIERARCHY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTCATEGORY] ADD  CONSTRAINT [DF_ECORESPRODUCTCATEGORY_CATEGORYHIERARCHY]  DEFAULT ((0)) FOR [CATEGORYHIERARCHY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTCATEGORY_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTCATEGORY] ADD  CONSTRAINT [DF_ECORESPRODUCTCATEGORY_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTCATEGORY_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTCATEGORY] ADD  CONSTRAINT [DF_ECORESPRODUCTCATEGORY_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTCATEGORY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTIMAGE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTIMAGE](
[RECID] [bigint] NOT NULL,
[DEFAULTIMAGE] [int] NOT NULL,
[MEDIUMSIZE] [varbinary](max) NULL,
[REFRECORD] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_138521337_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTIMAGE_DEFAULTIMAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTIMAGE] ADD  CONSTRAINT [DF_ECORESPRODUCTIMAGE_DEFAULTIMAGE]  DEFAULT ((0)) FOR [DEFAULTIMAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTIMAGE_REFRECORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTIMAGE] ADD  CONSTRAINT [DF_ECORESPRODUCTIMAGE_REFRECORD]  DEFAULT ((0)) FOR [REFRECORD]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTIMAGE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTINSTANCEVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTINSTANCEVALUE](
[RECID] [bigint] NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1181257446_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1181257446_-474954108] UNIQUE NONCLUSTERED 
(
[PRODUCT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTINSTANCEVALUE_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTINSTANCEVALUE] ADD  CONSTRAINT [DF_ECORESPRODUCTINSTANCEVALUE_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTINSTANCEVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTMASTERCOLOR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTMASTERCOLOR](
[RECID] [bigint] NOT NULL,
[COLOR] [bigint] NOT NULL,
[COLORPRODUCTDIMENSIONATTRIBUTE] [bigint] NOT NULL,
[COLORPRODUCTMASTER] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-245487881_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-245487881_1679221303] UNIQUE NONCLUSTERED 
(
[COLORPRODUCTMASTER] ASC,
[COLORPRODUCTDIMENSIONATTRIBUTE] ASC,
[COLOR] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERCOLOR_COLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERCOLOR] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERCOLOR_COLOR]  DEFAULT ((0)) FOR [COLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERCOLOR_COLORPRODUCTDIMENSIONATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERCOLOR] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERCOLOR_COLORPRODUCTDIMENSIONATTRIBUTE]  DEFAULT ((0)) FOR [COLORPRODUCTDIMENSIONATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERCOLOR_COLORPRODUCTMASTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERCOLOR] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERCOLOR_COLORPRODUCTMASTER]  DEFAULT ((0)) FOR [COLORPRODUCTMASTER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTMASTERCOLOR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTMASTERCONFIGURATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTMASTERCONFIGURATION](
[RECID] [bigint] NOT NULL,
[CONFIGPRODUCTDIMENSIONATTRIBUTE] [bigint] NOT NULL,
[CONFIGPRODUCTMASTER] [bigint] NOT NULL,
[CONFIGURATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2132147850_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_2132147850_-1900482308] UNIQUE NONCLUSTERED 
(
[CONFIGPRODUCTMASTER] ASC,
[CONFIGPRODUCTDIMENSIONATTRIBUTE] ASC,
[CONFIGURATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERCONFIGURATION_CONFIGPRODUCTDIMENSIONATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERCONFIGURATION] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERCONFIGURATION_CONFIGPRODUCTDIMENSIONATTRIBUTE]  DEFAULT ((0)) FOR [CONFIGPRODUCTDIMENSIONATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERCONFIGURATION_CONFIGPRODUCTMASTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERCONFIGURATION] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERCONFIGURATION_CONFIGPRODUCTMASTER]  DEFAULT ((0)) FOR [CONFIGPRODUCTMASTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERCONFIGURATION_CONFIGURATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERCONFIGURATION] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERCONFIGURATION_CONFIGURATION]  DEFAULT ((0)) FOR [CONFIGURATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTMASTERCONFIGURATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTMASTERDIMENSIONVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTMASTERDIMENSIONVALUE](
[RECID] [bigint] NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[RETAILDISPLAYORDER] [numeric](32, 16) NOT NULL,
[RETAILWEIGHT] [int] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-890205203_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERDIMENSIONVALUE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERDIMENSIONVALUE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERDIMENSIONVALUE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERDIMENSIONVALUE_RETAILDISPLAYORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERDIMENSIONVALUE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERDIMENSIONVALUE_RETAILDISPLAYORDER]  DEFAULT ((0)) FOR [RETAILDISPLAYORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERDIMENSIONVALUE_RETAILWEIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERDIMENSIONVALUE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERDIMENSIONVALUE_RETAILWEIGHT]  DEFAULT ((0)) FOR [RETAILWEIGHT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTMASTERDIMENSIONVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTMASTERDIMVALUETRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTMASTERDIMVALUETRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](1000) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PRODUCTMASTERDIMENSIONVALUE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1147335506_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1147335506_-973044609] UNIQUE NONCLUSTERED 
(
[PRODUCTMASTERDIMENSIONVALUE] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERDIMVALUETRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERDIMVALUETRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERDIMVALUETRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_PRODUCTMASTERDIMENSIONVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERDIMVALUETRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERDIMVALUETRANSLATION_PRODUCTMASTERDIMENSIONVALUE]  DEFAULT ((0)) FOR [PRODUCTMASTERDIMENSIONVALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTMASTERDIMVALUETRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTMASTERSIZE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTMASTERSIZE](
[RECID] [bigint] NOT NULL,
[SIZE] [bigint] NOT NULL,
[SIZEPRODUCTDIMENSIONATTRIBUTE] [bigint] NOT NULL,
[SIZEPRODUCTMASTER] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1630785697_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1630785697_410463323] UNIQUE NONCLUSTERED 
(
[SIZEPRODUCTMASTER] ASC,
[SIZEPRODUCTDIMENSIONATTRIBUTE] ASC,
[SIZE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERSIZE_SIZE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERSIZE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERSIZE_SIZE]  DEFAULT ((0)) FOR [SIZE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERSIZE_SIZEPRODUCTDIMENSIONATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERSIZE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERSIZE_SIZEPRODUCTDIMENSIONATTRIBUTE]  DEFAULT ((0)) FOR [SIZEPRODUCTDIMENSIONATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERSIZE_SIZEPRODUCTMASTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERSIZE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERSIZE_SIZEPRODUCTMASTER]  DEFAULT ((0)) FOR [SIZEPRODUCTMASTER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTMASTERSIZE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTMASTERSTYLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTMASTERSTYLE](
[RECID] [bigint] NOT NULL,
[STYLE] [bigint] NOT NULL,
[STYLEPRODUCTDIMENSIONATTRIBUTE] [bigint] NOT NULL,
[STYLEPRODUCTMASTER] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1455273879_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1455273879_-671292583] UNIQUE NONCLUSTERED 
(
[STYLEPRODUCTMASTER] ASC,
[STYLEPRODUCTDIMENSIONATTRIBUTE] ASC,
[STYLE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERSTYLE_STYLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERSTYLE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERSTYLE_STYLE]  DEFAULT ((0)) FOR [STYLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERSTYLE_STYLEPRODUCTDIMENSIONATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERSTYLE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERSTYLE_STYLEPRODUCTDIMENSIONATTRIBUTE]  DEFAULT ((0)) FOR [STYLEPRODUCTDIMENSIONATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTMASTERSTYLE_STYLEPRODUCTMASTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTMASTERSTYLE] ADD  CONSTRAINT [DF_ECORESPRODUCTMASTERSTYLE_STYLEPRODUCTMASTER]  DEFAULT ((0)) FOR [STYLEPRODUCTMASTER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTMASTERSTYLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTRELATIONTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTRELATIONTABLE](
[RECID] [bigint] NOT NULL,
[PRODUCT1] [bigint] NOT NULL,
[PRODUCT2] [bigint] NOT NULL,
[PRODUCTRELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_705077454_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_705077454_-382657853] UNIQUE NONCLUSTERED 
(
[PRODUCT1] ASC,
[PRODUCTRELATIONTYPE] ASC,
[PRODUCT2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTRELATIONTABLE_PRODUCT1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTRELATIONTABLE] ADD  CONSTRAINT [DF_ECORESPRODUCTRELATIONTABLE_PRODUCT1]  DEFAULT ((0)) FOR [PRODUCT1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTRELATIONTABLE_PRODUCT2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTRELATIONTABLE] ADD  CONSTRAINT [DF_ECORESPRODUCTRELATIONTABLE_PRODUCT2]  DEFAULT ((0)) FOR [PRODUCT2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTRELATIONTABLE_PRODUCTRELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTRELATIONTABLE] ADD  CONSTRAINT [DF_ECORESPRODUCTRELATIONTABLE_PRODUCTRELATIONTYPE]  DEFAULT ((0)) FOR [PRODUCTRELATIONTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTRELATIONTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTRELATIONTYPE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTRELATIONTYPE](
[RECID] [bigint] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1362932938_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1362932938_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTRELATIONTYPE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTRELATIONTYPE] ADD  CONSTRAINT [DF_ECORESPRODUCTRELATIONTYPE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTRELATIONTYPE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTTRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](1000) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1618573415_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1618573415_168464721] UNIQUE NONCLUSTERED 
(
[RECID] ASC,
[PRODUCT] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1618573415_-1991811118] UNIQUE NONCLUSTERED 
(
[PRODUCT] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTTRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTTRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTTRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTTRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTTRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTTRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTTRANSLATION_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTTRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTTRANSLATION_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTTRANSLATION_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTTRANSLATION] ADD  CONSTRAINT [DF_ECORESPRODUCTTRANSLATION_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTVARIANTCOLOR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTVARIANTCOLOR](
[RECID] [bigint] NOT NULL,
[COLOR] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_90086398_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTVARIANTCOLOR_COLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTVARIANTCOLOR] ADD  CONSTRAINT [DF_ECORESPRODUCTVARIANTCOLOR_COLOR]  DEFAULT ((0)) FOR [COLOR]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTVARIANTCOLOR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTVARIANTCONFIGURATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTVARIANTCONFIGURATION](
[RECID] [bigint] NOT NULL,
[CONFIGURATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-54286215_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTVARIANTCONFIGURATION_CONFIGURATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTVARIANTCONFIGURATION] ADD  CONSTRAINT [DF_ECORESPRODUCTVARIANTCONFIGURATION_CONFIGURATION]  DEFAULT ((0)) FOR [CONFIGURATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTVARIANTCONFIGURATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTVARIANTDIMENSIONVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTVARIANTDIMENSIONVALUE](
[RECID] [bigint] NOT NULL,
[DISTINCTPRODUCTVARIANT] [bigint] NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[PRODUCTDIMENSIONATTRIBUTE] [bigint] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-69226718_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-69226718_-1266844630] UNIQUE NONCLUSTERED 
(
[DISTINCTPRODUCTVARIANT] ASC,
[PRODUCTDIMENSIONATTRIBUTE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTVARIANTDIMENSIONVALUE_DISTINCTPRODUCTVARIANT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTVARIANTDIMENSIONVALUE] ADD  CONSTRAINT [DF_ECORESPRODUCTVARIANTDIMENSIONVALUE_DISTINCTPRODUCTVARIANT]  DEFAULT ((0)) FOR [DISTINCTPRODUCTVARIANT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTVARIANTDIMENSIONVALUE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTVARIANTDIMENSIONVALUE] ADD  CONSTRAINT [DF_ECORESPRODUCTVARIANTDIMENSIONVALUE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTVARIANTDIMENSIONVALUE_PRODUCTDIMENSIONATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTVARIANTDIMENSIONVALUE] ADD  CONSTRAINT [DF_ECORESPRODUCTVARIANTDIMENSIONVALUE_PRODUCTDIMENSIONATTRIBUTE]  DEFAULT ((0)) FOR [PRODUCTDIMENSIONATTRIBUTE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTVARIANTDIMENSIONVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTVARIANTSIZE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTVARIANTSIZE](
[RECID] [bigint] NOT NULL,
[SIZE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_181768102_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTVARIANTSIZE_SIZE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTVARIANTSIZE] ADD  CONSTRAINT [DF_ECORESPRODUCTVARIANTSIZE_SIZE]  DEFAULT ((0)) FOR [SIZE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTVARIANTSIZE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESPRODUCTVARIANTSTYLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESPRODUCTVARIANTSTYLE](
[RECID] [bigint] NOT NULL,
[STYLE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1931830212_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESPRODUCTVARIANTSTYLE_STYLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESPRODUCTVARIANTSTYLE] ADD  CONSTRAINT [DF_ECORESPRODUCTVARIANTSTYLE_STYLE]  DEFAULT ((0)) FOR [STYLE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESPRODUCTVARIANTSTYLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESREFERENCEVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESREFERENCEVALUE](
[RECID] [bigint] NOT NULL,
[REFFIELDID] [int] NULL,
[REFRECID] [bigint] NULL,
[REFTABLEID] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_509484233_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESREFERENCEVALUE_REFTABLEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESREFERENCEVALUE] ADD  CONSTRAINT [DF_ECORESREFERENCEVALUE_REFTABLEID]  DEFAULT ((0)) FOR [REFTABLEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESREFERENCEVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESSIZE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESSIZE](
[RECID] [bigint] NOT NULL,
[NAME] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_357393082_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_357393082_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESSIZE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESSIZE] ADD  CONSTRAINT [DF_ECORESSIZE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESSIZE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESSTYLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESSTYLE](
[RECID] [bigint] NOT NULL,
[NAME] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_967371264_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_967371264_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESSTYLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESSTYLE] ADD  CONSTRAINT [DF_ECORESSTYLE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESSTYLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESTEXTVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESTEXTVALUE](
[RECID] [bigint] NOT NULL,
[TEXTVALUE] [nvarchar](1999) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1324545795_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTEXTVALUE_TEXTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTEXTVALUE] ADD  CONSTRAINT [DF_ECORESTEXTVALUE_TEXTVALUE]  DEFAULT ('') FOR [TEXTVALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESTEXTVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESTEXTVALUETRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESTEXTVALUETRANSLATION](
[RECID] [bigint] NOT NULL,
[LANGUAGE] [nvarchar](7) NOT NULL,
[TEXTVALUE] [nvarchar](1999) NOT NULL,
[TEXTVALUETABLE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1489278364_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1489278364_1876204403] UNIQUE NONCLUSTERED 
(
[TEXTVALUETABLE] ASC,
[LANGUAGE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTEXTVALUETRANSLATION_LANGUAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTEXTVALUETRANSLATION] ADD  CONSTRAINT [DF_ECORESTEXTVALUETRANSLATION_LANGUAGE]  DEFAULT ('') FOR [LANGUAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTEXTVALUETRANSLATION_TEXTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTEXTVALUETRANSLATION] ADD  CONSTRAINT [DF_ECORESTEXTVALUETRANSLATION_TEXTVALUE]  DEFAULT ('') FOR [TEXTVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTEXTVALUETRANSLATION_TEXTVALUETABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTEXTVALUETRANSLATION] ADD  CONSTRAINT [DF_ECORESTEXTVALUETRANSLATION_TEXTVALUETABLE]  DEFAULT ((0)) FOR [TEXTVALUETABLE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESTEXTVALUETRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP](
[RECID] [bigint] NOT NULL,
[DIMENSIONFIELDID] [int] NOT NULL,
[ISACTIVE] [int] NOT NULL,
[ISALLOWBLANKISSUEENABLED] [int] NOT NULL,
[ISSALESPROCESSACTIVATED] [int] NOT NULL,
[TRACKINGDIMENSIONGROUP] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1701906886_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1701906886_1841106920] UNIQUE NONCLUSTERED 
(
[TRACKINGDIMENSIONGROUP] ASC,
[DIMENSIONFIELDID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_DIMENSIONFIELDID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_DIMENSIONFIELDID]  DEFAULT ((0)) FOR [DIMENSIONFIELDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_ISACTIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_ISACTIVE]  DEFAULT ((0)) FOR [ISACTIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_ISALLOWBLANKISSUEENABLED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_ISALLOWBLANKISSUEENABLED]  DEFAULT ((0)) FOR [ISALLOWBLANKISSUEENABLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_ISSALESPROCESSACTIVATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_ISSALESPROCESSACTIVATED]  DEFAULT ((0)) FOR [ISSALESPROCESSACTIVATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_TRACKINGDIMENSIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPFLDSETUP_TRACKINGDIMENSIONGROUP]  DEFAULT ((0)) FOR [TRACKINGDIMENSIONGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESTRACKINGDIMENSIONGROUPITEM]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPITEM](
[RECID] [bigint] NOT NULL,
[ITEMDATAAREAID] [nvarchar](4) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[TRACKINGDIMENSIONGROUP] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-174369730_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-174369730_1322497665] UNIQUE NONCLUSTERED 
(
[ITEMID] ASC,
[ITEMDATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPITEM_ITEMDATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPITEM] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPITEM_ITEMDATAAREAID]  DEFAULT ('') FOR [ITEMDATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPITEM_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPITEM] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPITEM_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPITEM_TRACKINGDIMENSIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPITEM] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPITEM_TRACKINGDIMENSIONGROUP]  DEFAULT ((0)) FOR [TRACKINGDIMENSIONGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESTRACKINGDIMENSIONGROUPITEM] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESTRACKINGDIMENSIONGROUPPRODUCT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPPRODUCT](
[RECID] [bigint] NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[TRACKINGDIMENSIONGROUP] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1127445604_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1127445604_1005329023] UNIQUE NONCLUSTERED 
(
[PRODUCT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPPRODUCT_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPPRODUCT] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPPRODUCT_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESTRACKINGDIMENSIONGROUPPRODUCT_TRACKINGDIMENSIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESTRACKINGDIMENSIONGROUPPRODUCT] ADD  CONSTRAINT [DF_ECORESTRACKINGDIMENSIONGROUPPRODUCT_TRACKINGDIMENSIONGROUP]  DEFAULT ((0)) FOR [TRACKINGDIMENSIONGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESTRACKINGDIMENSIONGROUPPRODUCT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[ECORESVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[ECORESVALUE](
[RECID] [bigint] NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_698346388_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_ECORESVALUE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[ECORESVALUE] ADD  CONSTRAINT [DF_ECORESVALUE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[ECORESVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[EXCEPTIONCODETABLE_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[EXCEPTIONCODETABLE_BR](
[RECID] [bigint] NOT NULL,
[APPROXTAXVALUEIMPORTED] [numeric](32, 16) NOT NULL,
[APPROXTAXVALUENATIONAL] [numeric](32, 16) NOT NULL,
[EXCEPTIONCODE] [nvarchar](10) NOT NULL,
[TAXFISCALCLASSIFICATIONID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_671712487_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_671712487_-482247933] UNIQUE NONCLUSTERED 
(
[TAXFISCALCLASSIFICATIONID] ASC,
[EXCEPTIONCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCEPTIONCODETABLE_BR_APPROXTAXVALUEIMPORTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCEPTIONCODETABLE_BR] ADD  CONSTRAINT [DF_EXCEPTIONCODETABLE_BR_APPROXTAXVALUEIMPORTED]  DEFAULT ((0)) FOR [APPROXTAXVALUEIMPORTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCEPTIONCODETABLE_BR_APPROXTAXVALUENATIONAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCEPTIONCODETABLE_BR] ADD  CONSTRAINT [DF_EXCEPTIONCODETABLE_BR_APPROXTAXVALUENATIONAL]  DEFAULT ((0)) FOR [APPROXTAXVALUENATIONAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCEPTIONCODETABLE_BR_EXCEPTIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCEPTIONCODETABLE_BR] ADD  CONSTRAINT [DF_EXCEPTIONCODETABLE_BR_EXCEPTIONCODE]  DEFAULT ('') FOR [EXCEPTIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCEPTIONCODETABLE_BR_TAXFISCALCLASSIFICATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCEPTIONCODETABLE_BR] ADD  CONSTRAINT [DF_EXCEPTIONCODETABLE_BR_TAXFISCALCLASSIFICATIONID]  DEFAULT ('') FOR [TAXFISCALCLASSIFICATIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[EXCEPTIONCODETABLE_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[EXCHANGERATE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[EXCHANGERATE](
[RECID] [bigint] NOT NULL,
[EXCHANGERATE] [numeric](32, 16) NOT NULL,
[EXCHANGERATECURRENCYPAIR] [bigint] NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_555506149_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_555506149_-858666067] UNIQUE NONCLUSTERED 
(
[EXCHANGERATECURRENCYPAIR] ASC,
[VALIDFROM] ASC,
[VALIDTO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATE_EXCHANGERATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATE] ADD  CONSTRAINT [DF_EXCHANGERATE_EXCHANGERATE]  DEFAULT ((0)) FOR [EXCHANGERATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATE_EXCHANGERATECURRENCYPAIR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATE] ADD  CONSTRAINT [DF_EXCHANGERATE_EXCHANGERATECURRENCYPAIR]  DEFAULT ((0)) FOR [EXCHANGERATECURRENCYPAIR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATE_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATE] ADD  CONSTRAINT [DF_EXCHANGERATE_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATE_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATE] ADD  CONSTRAINT [DF_EXCHANGERATE_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATE] ADD  CONSTRAINT [DF_EXCHANGERATE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[EXCHANGERATE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[EXCHANGERATECURRENCYPAIR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[EXCHANGERATECURRENCYPAIR](
[RECID] [bigint] NOT NULL,
[EXCHANGERATEDISPLAYFACTOR] [int] NOT NULL,
[EXCHANGERATETYPE] [bigint] NOT NULL,
[FROMCURRENCYCODE] [nvarchar](3) NOT NULL,
[TOCURRENCYCODE] [nvarchar](3) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1152046774_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1152046774_-946998140] UNIQUE NONCLUSTERED 
(
[FROMCURRENCYCODE] ASC,
[TOCURRENCYCODE] ASC,
[EXCHANGERATETYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATECURRENCYPAIR_EXCHANGERATEDISPLAYFACTOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATECURRENCYPAIR] ADD  CONSTRAINT [DF_EXCHANGERATECURRENCYPAIR_EXCHANGERATEDISPLAYFACTOR]  DEFAULT ((0)) FOR [EXCHANGERATEDISPLAYFACTOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATECURRENCYPAIR_EXCHANGERATETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATECURRENCYPAIR] ADD  CONSTRAINT [DF_EXCHANGERATECURRENCYPAIR_EXCHANGERATETYPE]  DEFAULT ((0)) FOR [EXCHANGERATETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATECURRENCYPAIR_FROMCURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATECURRENCYPAIR] ADD  CONSTRAINT [DF_EXCHANGERATECURRENCYPAIR_FROMCURRENCYCODE]  DEFAULT ('') FOR [FROMCURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATECURRENCYPAIR_TOCURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATECURRENCYPAIR] ADD  CONSTRAINT [DF_EXCHANGERATECURRENCYPAIR_TOCURRENCYCODE]  DEFAULT ('') FOR [TOCURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATECURRENCYPAIR_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATECURRENCYPAIR] ADD  CONSTRAINT [DF_EXCHANGERATECURRENCYPAIR_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[EXCHANGERATECURRENCYPAIR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[EXCHANGERATETYPE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[EXCHANGERATETYPE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[NAME] [nvarchar](20) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-193334427_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-193334427_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATETYPE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATETYPE] ADD  CONSTRAINT [DF_EXCHANGERATETYPE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_EXCHANGERATETYPE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[EXCHANGERATETYPE] ADD  CONSTRAINT [DF_EXCHANGERATETYPE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[EXCHANGERATETYPE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[FISCALESTABLISHMENT_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[FISCALESTABLISHMENT_BR](
[RECID] [bigint] NOT NULL,
[ACCOUNTANT_BR] [bigint] NOT NULL,
[CCMNUM_BR] [nvarchar](20) NOT NULL,
[CNPJCPFNUM_BR] [nvarchar](20) NOT NULL,
[DIRPARTYLOCATION] [bigint] NOT NULL,
[FISCALESTABLISHMENTID] [nvarchar](10) NOT NULL,
[IENUM_BR] [nvarchar](20) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1629009360_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1629009360_1165620475] UNIQUE NONCLUSTERED 
(
[FISCALESTABLISHMENTID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1629009360_1402367493] UNIQUE NONCLUSTERED 
(
[DIRPARTYLOCATION] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENT_BR_ACCOUNTANT_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENT_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENT_BR_ACCOUNTANT_BR]  DEFAULT ((0)) FOR [ACCOUNTANT_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENT_BR_CCMNUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENT_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENT_BR_CCMNUM_BR]  DEFAULT ('') FOR [CCMNUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENT_BR_CNPJCPFNUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENT_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENT_BR_CNPJCPFNUM_BR]  DEFAULT ('') FOR [CNPJCPFNUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENT_BR_DIRPARTYLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENT_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENT_BR_DIRPARTYLOCATION]  DEFAULT ((0)) FOR [DIRPARTYLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENT_BR_FISCALESTABLISHMENTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENT_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENT_BR_FISCALESTABLISHMENTID]  DEFAULT ('') FOR [FISCALESTABLISHMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENT_BR_IENUM_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENT_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENT_BR_IENUM_BR]  DEFAULT ('') FOR [IENUM_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENT_BR_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENT_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENT_BR_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[FISCALESTABLISHMENT_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[FISCALESTABLISHMENTINVENTSITE_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[FISCALESTABLISHMENTINVENTSITE_BR](
[RECID] [bigint] NOT NULL,
[FISCALESTABLISHMENT_BR] [bigint] NOT NULL,
[INVENTSITE] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1215761809_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1215761809_-1854860068] UNIQUE NONCLUSTERED 
(
[INVENTSITE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENTINVENTSITE_BR_FISCALESTABLISHMENT_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENTINVENTSITE_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENTINVENTSITE_BR_FISCALESTABLISHMENT_BR]  DEFAULT ((0)) FOR [FISCALESTABLISHMENT_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FISCALESTABLISHMENTINVENTSITE_BR_INVENTSITE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FISCALESTABLISHMENTINVENTSITE_BR] ADD  CONSTRAINT [DF_FISCALESTABLISHMENTINVENTSITE_BR_INVENTSITE]  DEFAULT ('') FOR [INVENTSITE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[FISCALESTABLISHMENTINVENTSITE_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[FORMULADESIGNER_IN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[FORMULADESIGNER_IN](
[RECID] [bigint] NOT NULL,
[CALCEXP] [nvarchar](1000) NOT NULL,
[CALCEXP1] [nvarchar](1000) NOT NULL,
[ID] [int] NOT NULL,
[PRICEINCLTAX] [int] NOT NULL,
[TAXABLEBASIS] [int] NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-751993433_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-751993433_-2114646326] UNIQUE NONCLUSTERED 
(
[TAXITEMGROUP] ASC,
[TAXCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FORMULADESIGNER_IN_CALCEXP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FORMULADESIGNER_IN] ADD  CONSTRAINT [DF_FORMULADESIGNER_IN_CALCEXP]  DEFAULT ('') FOR [CALCEXP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FORMULADESIGNER_IN_CALCEXP1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FORMULADESIGNER_IN] ADD  CONSTRAINT [DF_FORMULADESIGNER_IN_CALCEXP1]  DEFAULT ('') FOR [CALCEXP1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FORMULADESIGNER_IN_ID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FORMULADESIGNER_IN] ADD  CONSTRAINT [DF_FORMULADESIGNER_IN_ID]  DEFAULT ((0)) FOR [ID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FORMULADESIGNER_IN_PRICEINCLTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FORMULADESIGNER_IN] ADD  CONSTRAINT [DF_FORMULADESIGNER_IN_PRICEINCLTAX]  DEFAULT ((0)) FOR [PRICEINCLTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FORMULADESIGNER_IN_TAXABLEBASIS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FORMULADESIGNER_IN] ADD  CONSTRAINT [DF_FORMULADESIGNER_IN_TAXABLEBASIS]  DEFAULT ((0)) FOR [TAXABLEBASIS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FORMULADESIGNER_IN_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FORMULADESIGNER_IN] ADD  CONSTRAINT [DF_FORMULADESIGNER_IN_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_FORMULADESIGNER_IN_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[FORMULADESIGNER_IN] ADD  CONSTRAINT [DF_FORMULADESIGNER_IN_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[FORMULADESIGNER_IN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[HCMJOB]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[HCMJOB](
[RECID] [bigint] NOT NULL,
[JOBID] [nvarchar](25) NOT NULL,
[MAXIMUMPOSITIONS] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1678374987_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1678374987_-689341552] UNIQUE NONCLUSTERED 
(
[JOBID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMJOB_JOBID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMJOB] ADD  CONSTRAINT [DF_HCMJOB_JOBID]  DEFAULT ('') FOR [JOBID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMJOB_MAXIMUMPOSITIONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMJOB] ADD  CONSTRAINT [DF_HCMJOB_MAXIMUMPOSITIONS]  DEFAULT ((0)) FOR [MAXIMUMPOSITIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMJOB_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMJOB] ADD  CONSTRAINT [DF_HCMJOB_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMJOB_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMJOB] ADD  CONSTRAINT [DF_HCMJOB_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[HCMJOB] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[HCMPOSITION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[HCMPOSITION](
[RECID] [bigint] NOT NULL,
[POSITIONID] [nvarchar](25) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_592131255_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_592131255_-1568444020] UNIQUE NONCLUSTERED 
(
[POSITIONID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITION_POSITIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITION] ADD  CONSTRAINT [DF_HCMPOSITION_POSITIONID]  DEFAULT ('') FOR [POSITIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITION_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITION] ADD  CONSTRAINT [DF_HCMPOSITION_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITION_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITION] ADD  CONSTRAINT [DF_HCMPOSITION_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[HCMPOSITION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[HCMPOSITIONDETAIL]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[HCMPOSITIONDETAIL](
[RECID] [bigint] NOT NULL,
[COMPLOCATION] [bigint] NOT NULL,
[DEPARTMENT] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[FULLTIMEEQUIVALENCY] [numeric](32, 16) NOT NULL,
[JOB] [bigint] NOT NULL,
[POSITION] [bigint] NOT NULL,
[POSITIONTYPE] [bigint] NOT NULL,
[TITLE] [bigint] NOT NULL,
[VALIDFROM] [datetime] NOT NULL,
[VALIDFROMTZID] [int] NOT NULL,
[VALIDTO] [datetime] NOT NULL,
[VALIDTOTZID] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1550564396_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1550564396_-1568444020] UNIQUE NONCLUSTERED 
(
[POSITION] ASC,
[VALIDFROM] ASC,
[VALIDTO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_COMPLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_COMPLOCATION]  DEFAULT ((0)) FOR [COMPLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_DEPARTMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_DEPARTMENT]  DEFAULT ((0)) FOR [DEPARTMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_FULLTIMEEQUIVALENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_FULLTIMEEQUIVALENCY]  DEFAULT ((0)) FOR [FULLTIMEEQUIVALENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_JOB]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_JOB]  DEFAULT ((0)) FOR [JOB]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_POSITION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_POSITION]  DEFAULT ((0)) FOR [POSITION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_POSITIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_POSITIONTYPE]  DEFAULT ((0)) FOR [POSITIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_TITLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_TITLE]  DEFAULT ((0)) FOR [TITLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_VALIDFROM]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_VALIDFROMTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_VALIDFROMTZID]  DEFAULT ((37001)) FOR [VALIDFROMTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_VALIDTO]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_VALIDTOTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_VALIDTOTZID]  DEFAULT ((37001)) FOR [VALIDTOTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONDETAIL_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONDETAIL] ADD  CONSTRAINT [DF_HCMPOSITIONDETAIL_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[HCMPOSITIONDETAIL] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[HCMPOSITIONWORKERASSIGNMENT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT](
[RECID] [bigint] NOT NULL,
[ASSIGNMENTREASONCODE] [bigint] NOT NULL,
[POSITION] [bigint] NOT NULL,
[VALIDFROM] [datetime] NOT NULL,
[VALIDFROMTZID] [int] NOT NULL,
[VALIDTO] [datetime] NOT NULL,
[VALIDTOTZID] [int] NOT NULL,
[WORKER] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1725185210_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1725185210_-1568444020] UNIQUE NONCLUSTERED 
(
[POSITION] ASC,
[VALIDFROM] ASC,
[VALIDTO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_ASSIGNMENTREASONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_ASSIGNMENTREASONCODE]  DEFAULT ((0)) FOR [ASSIGNMENTREASONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_POSITION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_POSITION]  DEFAULT ((0)) FOR [POSITION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_VALIDFROM]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_VALIDFROMTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_VALIDFROMTZID]  DEFAULT ((37001)) FOR [VALIDFROMTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_VALIDTO]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_VALIDTOTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_VALIDTOTZID]  DEFAULT ((37001)) FOR [VALIDTOTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_WORKER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_WORKER]  DEFAULT ((0)) FOR [WORKER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMPOSITIONWORKERASSIGNMENT_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMPOSITIONWORKERASSIGNMENT] ADD  CONSTRAINT [DF_HCMPOSITIONWORKERASSIGNMENT_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[HCMPOSITIONWORKERASSIGNMENT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[HCMWORKER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[HCMWORKER](
[RECID] [bigint] NOT NULL,
[PERSON] [bigint] NOT NULL,
[PERSONNELNUMBER] [nvarchar](25) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_876116916_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_876116916_-738480416] UNIQUE NONCLUSTERED 
(
[PERSON] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_876116916_-738480417] UNIQUE NONCLUSTERED 
(
[PERSONNELNUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMWORKER_PERSON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMWORKER] ADD  CONSTRAINT [DF_HCMWORKER_PERSON]  DEFAULT ((0)) FOR [PERSON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMWORKER_PERSONNELNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMWORKER] ADD  CONSTRAINT [DF_HCMWORKER_PERSONNELNUMBER]  DEFAULT ('') FOR [PERSONNELNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMWORKER_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMWORKER] ADD  CONSTRAINT [DF_HCMWORKER_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_HCMWORKER_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[HCMWORKER] ADD  CONSTRAINT [DF_HCMWORKER_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[HCMWORKER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTDIM]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTDIM](
[RECID] [bigint] NOT NULL,
[CONFIGID] [nvarchar](10) NOT NULL,
[INVENTBATCHID] [nvarchar](20) NOT NULL,
[INVENTCOLORID] [nvarchar](10) NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[INVENTGTDID_RU] [nvarchar](30) NOT NULL,
[INVENTLOCATIONID] [nvarchar](10) NOT NULL,
[INVENTOWNERID_RU] [nvarchar](20) NOT NULL,
[INVENTPROFILEID_RU] [nvarchar](10) NOT NULL,
[INVENTSERIALID] [nvarchar](20) NOT NULL,
[INVENTSITEID] [nvarchar](10) NOT NULL,
[INVENTSIZEID] [nvarchar](10) NOT NULL,
[INVENTSTYLEID] [nvarchar](10) NOT NULL,
[SHA1HASH] [varbinary](28) NULL,
[WMSLOCATIONID] [nvarchar](10) NOT NULL,
[WMSPALLETID] [nvarchar](18) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-65082180_-588450352] PRIMARY KEY CLUSTERED 
(
[INVENTDIMID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-65082180_-851492679] UNIQUE NONCLUSTERED 
(
[CONFIGID] ASC,
[INVENTSIZEID] ASC,
[INVENTCOLORID] ASC,
[INVENTSTYLEID] ASC,
[INVENTSITEID] ASC,
[INVENTLOCATIONID] ASC,
[INVENTBATCHID] ASC,
[WMSLOCATIONID] ASC,
[WMSPALLETID] ASC,
[INVENTSERIALID] ASC,
[INVENTGTDID_RU] ASC,
[INVENTPROFILEID_RU] ASC,
[INVENTOWNERID_RU] ASC,
[SHA1HASH] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_CONFIGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_CONFIGID]  DEFAULT ('') FOR [CONFIGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTBATCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTBATCHID]  DEFAULT ('') FOR [INVENTBATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTCOLORID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTCOLORID]  DEFAULT ('') FOR [INVENTCOLORID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTGTDID_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTGTDID_RU]  DEFAULT ('') FOR [INVENTGTDID_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTLOCATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTLOCATIONID]  DEFAULT ('') FOR [INVENTLOCATIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTOWNERID_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTOWNERID_RU]  DEFAULT ('') FOR [INVENTOWNERID_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTPROFILEID_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTPROFILEID_RU]  DEFAULT ('') FOR [INVENTPROFILEID_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTSERIALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTSERIALID]  DEFAULT ('') FOR [INVENTSERIALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTSITEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTSITEID]  DEFAULT ('') FOR [INVENTSITEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTSIZEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTSIZEID]  DEFAULT ('') FOR [INVENTSIZEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_INVENTSTYLEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_INVENTSTYLEID]  DEFAULT ('') FOR [INVENTSTYLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_WMSLOCATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_WMSLOCATIONID]  DEFAULT ('') FOR [WMSLOCATIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIM_WMSPALLETID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIM] ADD  CONSTRAINT [DF_INVENTDIM_WMSPALLETID]  DEFAULT ('') FOR [WMSPALLETID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTDIM] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTDIMCOMBINATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTDIMCOMBINATION](
[RECID] [bigint] NOT NULL,
[DISTINCTPRODUCTVARIANT] [bigint] NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[RETAILVARIANTID] [nvarchar](10) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-804010625_1429128816] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[INVENTDIMID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-804010625_-474954108] UNIQUE NONCLUSTERED 
(
[DISTINCTPRODUCTVARIANT] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIMCOMBINATION_DISTINCTPRODUCTVARIANT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIMCOMBINATION] ADD  CONSTRAINT [DF_INVENTDIMCOMBINATION_DISTINCTPRODUCTVARIANT]  DEFAULT ((0)) FOR [DISTINCTPRODUCTVARIANT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIMCOMBINATION_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIMCOMBINATION] ADD  CONSTRAINT [DF_INVENTDIMCOMBINATION_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIMCOMBINATION_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIMCOMBINATION] ADD  CONSTRAINT [DF_INVENTDIMCOMBINATION_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIMCOMBINATION_RETAILVARIANTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIMCOMBINATION] ADD  CONSTRAINT [DF_INVENTDIMCOMBINATION_RETAILVARIANTID]  DEFAULT ('') FOR [RETAILVARIANTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTDIMCOMBINATION_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTDIMCOMBINATION] ADD  CONSTRAINT [DF_INVENTDIMCOMBINATION_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTDIMCOMBINATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTITEMBARCODE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTITEMBARCODE](
[RECID] [bigint] NOT NULL,
[BARCODESETUPID] [nvarchar](10) NOT NULL,
[BLOCKED] [int] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[ITEMBARCODE] [nvarchar](80) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[RETAILSHOWFORITEM] [int] NOT NULL,
[RETAILVARIANTID] [nvarchar](10) NOT NULL,
[UNITID] [nvarchar](10) NOT NULL,
[USEFORINPUT] [int] NOT NULL,
[USEFORPRINTING] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_500758235_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_BARCODESETUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_BARCODESETUPID]  DEFAULT ('') FOR [BARCODESETUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_BLOCKED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_BLOCKED]  DEFAULT ((0)) FOR [BLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_ITEMBARCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_ITEMBARCODE]  DEFAULT ('') FOR [ITEMBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_RETAILSHOWFORITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_RETAILSHOWFORITEM]  DEFAULT ((0)) FOR [RETAILSHOWFORITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_RETAILVARIANTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_RETAILVARIANTID]  DEFAULT ('') FOR [RETAILVARIANTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_UNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_UNITID]  DEFAULT ('') FOR [UNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_USEFORINPUT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_USEFORINPUT]  DEFAULT ((0)) FOR [USEFORINPUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMBARCODE_USEFORPRINTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMBARCODE] ADD  CONSTRAINT [DF_INVENTITEMBARCODE_USEFORPRINTING]  DEFAULT ((0)) FOR [USEFORPRINTING]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTITEMBARCODE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTITEMGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTITEMGROUP](
[RECID] [bigint] NOT NULL,
[ITEMGROUPID] [nvarchar](10) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1805098484_2044944007] PRIMARY KEY CLUSTERED 
(
[ITEMGROUPID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGROUP_ITEMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGROUP] ADD  CONSTRAINT [DF_INVENTITEMGROUP_ITEMGROUPID]  DEFAULT ('') FOR [ITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGROUP_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGROUP] ADD  CONSTRAINT [DF_INVENTITEMGROUP_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTITEMGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTITEMGROUPITEM]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTITEMGROUPITEM](
[RECID] [bigint] NOT NULL,
[ITEMDATAAREAID] [nvarchar](4) NOT NULL,
[ITEMGROUPDATAAREAID] [nvarchar](4) NOT NULL,
[ITEMGROUPID] [nvarchar](10) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-313455423_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-313455423_1429128816] UNIQUE NONCLUSTERED 
(
[ITEMID] ASC,
[ITEMDATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGROUPITEM_ITEMDATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGROUPITEM] ADD  CONSTRAINT [DF_INVENTITEMGROUPITEM_ITEMDATAAREAID]  DEFAULT ('') FOR [ITEMDATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGROUPITEM_ITEMGROUPDATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGROUPITEM] ADD  CONSTRAINT [DF_INVENTITEMGROUPITEM_ITEMGROUPDATAAREAID]  DEFAULT ('') FOR [ITEMGROUPDATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGROUPITEM_ITEMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGROUPITEM] ADD  CONSTRAINT [DF_INVENTITEMGROUPITEM_ITEMGROUPID]  DEFAULT ('') FOR [ITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGROUPITEM_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGROUPITEM] ADD  CONSTRAINT [DF_INVENTITEMGROUPITEM_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTITEMGROUPITEM] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTITEMGTIN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTITEMGTIN](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[GLOBALTRADEITEMNUMBER] [nvarchar](14) NOT NULL,
[GTINSETUP] [int] NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[UNITID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1261397331_1429128816] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[INVENTDIMID] ASC,
[UNITID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1261397331_-948205258] UNIQUE NONCLUSTERED 
(
[GLOBALTRADEITEMNUMBER] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGTIN_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGTIN] ADD  CONSTRAINT [DF_INVENTITEMGTIN_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGTIN_GLOBALTRADEITEMNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGTIN] ADD  CONSTRAINT [DF_INVENTITEMGTIN_GLOBALTRADEITEMNUMBER]  DEFAULT ('') FOR [GLOBALTRADEITEMNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGTIN_GTINSETUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGTIN] ADD  CONSTRAINT [DF_INVENTITEMGTIN_GTINSETUP]  DEFAULT ((0)) FOR [GTINSETUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGTIN_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGTIN] ADD  CONSTRAINT [DF_INVENTITEMGTIN_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGTIN_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGTIN] ADD  CONSTRAINT [DF_INVENTITEMGTIN_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMGTIN_UNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMGTIN] ADD  CONSTRAINT [DF_INVENTITEMGTIN_UNITID]  DEFAULT ('') FOR [UNITID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTITEMGTIN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTITEMSALESSETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTITEMSALESSETUP](
[RECID] [bigint] NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[INVENTDIMIDDEFAULT] [nvarchar](20) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[MANDATORYINVENTLOCATION] [int] NOT NULL,
[MANDATORYINVENTSITE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1618439284_1798859704] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[INVENTDIMID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMSALESSETUP_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMSALESSETUP] ADD  CONSTRAINT [DF_INVENTITEMSALESSETUP_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMSALESSETUP_INVENTDIMIDDEFAULT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMSALESSETUP] ADD  CONSTRAINT [DF_INVENTITEMSALESSETUP_INVENTDIMIDDEFAULT]  DEFAULT ('') FOR [INVENTDIMIDDEFAULT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMSALESSETUP_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMSALESSETUP] ADD  CONSTRAINT [DF_INVENTITEMSALESSETUP_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMSALESSETUP_MANDATORYINVENTLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMSALESSETUP] ADD  CONSTRAINT [DF_INVENTITEMSALESSETUP_MANDATORYINVENTLOCATION]  DEFAULT ((0)) FOR [MANDATORYINVENTLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTITEMSALESSETUP_MANDATORYINVENTSITE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTITEMSALESSETUP] ADD  CONSTRAINT [DF_INVENTITEMSALESSETUP_MANDATORYINVENTSITE]  DEFAULT ((0)) FOR [MANDATORYINVENTSITE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTITEMSALESSETUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTLOCATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTLOCATION](
[RECID] [bigint] NOT NULL,
[INVENTLOCATIONID] [nvarchar](10) NOT NULL,
[INVENTLOCATIONTYPE] [int] NOT NULL,
[INVENTSITEID] [nvarchar](10) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_448739807_1141804996] PRIMARY KEY CLUSTERED 
(
[INVENTLOCATIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATION_INVENTLOCATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATION_INVENTLOCATIONID]  DEFAULT ('') FOR [INVENTLOCATIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATION_INVENTLOCATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATION_INVENTLOCATIONTYPE]  DEFAULT ((0)) FOR [INVENTLOCATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATION_INVENTSITEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATION_INVENTSITEID]  DEFAULT ('') FOR [INVENTSITEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATION_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATION_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTLOCATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTLOCATIONLOGISTICSLOCATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTLOCATIONLOGISTICSLOCATION](
[RECID] [bigint] NOT NULL,
[INVENTLOCATION] [bigint] NOT NULL,
[ISPOSTALADDRESS] [int] NOT NULL,
[ISPRIMARY] [int] NOT NULL,
[LOCATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1407999417_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1407999417_553911634] UNIQUE NONCLUSTERED 
(
[INVENTLOCATION] ASC,
[LOCATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATIONLOGISTICSLOCATION_INVENTLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATIONLOGISTICSLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATIONLOGISTICSLOCATION_INVENTLOCATION]  DEFAULT ((0)) FOR [INVENTLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATIONLOGISTICSLOCATION_ISPOSTALADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATIONLOGISTICSLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATIONLOGISTICSLOCATION_ISPOSTALADDRESS]  DEFAULT ((0)) FOR [ISPOSTALADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATIONLOGISTICSLOCATION_ISPRIMARY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATIONLOGISTICSLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATIONLOGISTICSLOCATION_ISPRIMARY]  DEFAULT ((0)) FOR [ISPRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTLOCATIONLOGISTICSLOCATION_LOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTLOCATIONLOGISTICSLOCATION] ADD  CONSTRAINT [DF_INVENTLOCATIONLOGISTICSLOCATION_LOCATION]  DEFAULT ((0)) FOR [LOCATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTLOCATIONLOGISTICSLOCATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTSERIAL]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTSERIAL](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](max) NULL,
[INVENTSERIALID] [nvarchar](20) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[PRODDATE] [date] NOT NULL,
[RFIDTAGID] [nvarchar](24) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_43867350_-846934704] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[INVENTSERIALID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTSERIAL_INVENTSERIALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTSERIAL] ADD  CONSTRAINT [DF_INVENTSERIAL_INVENTSERIALID]  DEFAULT ('') FOR [INVENTSERIALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTSERIAL_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTSERIAL] ADD  CONSTRAINT [DF_INVENTSERIAL_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTSERIAL_PRODDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTSERIAL] ADD  CONSTRAINT [DF_INVENTSERIAL_PRODDATE]  DEFAULT ('1900-01-01') FOR [PRODDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTSERIAL_RFIDTAGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTSERIAL] ADD  CONSTRAINT [DF_INVENTSERIAL_RFIDTAGID]  DEFAULT ('') FOR [RFIDTAGID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTSERIAL] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTTABLE](
[RECID] [bigint] NOT NULL,
[ABCCONTRIBUTIONMARGIN] [int] NOT NULL,
[ABCREVENUE] [int] NOT NULL,
[ABCTIEUP] [int] NOT NULL,
[ABCVALUE] [int] NOT NULL,
[ALTITEMID] [nvarchar](20) NOT NULL,
[APPROXTAXVALUE_BR] [numeric](32, 16) NOT NULL,
[BATCHNUMGROUPID] [nvarchar](10) NOT NULL,
[COSTMODEL] [int] NOT NULL,
[DENSITY] [numeric](32, 16) NOT NULL,
[DEPTH] [numeric](32, 16) NOT NULL,
[EXCEPTIONCODE_BR] [nvarchar](10) NOT NULL,
[GROSSDEPTH] [numeric](32, 16) NOT NULL,
[GROSSHEIGHT] [numeric](32, 16) NOT NULL,
[GROSSWIDTH] [numeric](32, 16) NOT NULL,
[HEIGHT] [numeric](32, 16) NOT NULL,
[INVENTPRODUCTTYPE_BR] [nvarchar](10) NOT NULL,
[ITEMBUYERGROUPID] [nvarchar](10) NOT NULL,
[ITEMDIMCOSTPRICE] [int] NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[ITEMTYPE] [int] NOT NULL,
[NAMEALIAS] [nvarchar](20) NOT NULL,
[NETWEIGHT] [numeric](32, 16) NOT NULL,
[PBAINVENTITEMGROUPID] [nvarchar](10) NOT NULL,
[PBAITEMCONFIGURABLE] [int] NOT NULL,
[PRIMARYVENDORID] [nvarchar](20) NOT NULL,
[PRODGROUPID] [nvarchar](10) NOT NULL,
[PRODPOOLID] [nvarchar](10) NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[PROJCATEGORYID] [nvarchar](30) NOT NULL,
[PROPERTYID] [nvarchar](10) NOT NULL,
[PURCHMODEL] [int] NOT NULL,
[REQGROUPID] [nvarchar](10) NOT NULL,
[SALESCONTRIBUTIONRATIO] [numeric](32, 16) NOT NULL,
[SALESMODEL] [int] NOT NULL,
[SALESPERCENTMARKUP] [numeric](32, 16) NOT NULL,
[SALESPRICEMODELBASIC] [int] NOT NULL,
[SERIALNUMGROUPID] [nvarchar](10) NOT NULL,
[SORTCODE] [int] NOT NULL,
[TARAWEIGHT] [numeric](32, 16) NOT NULL,
[TAXATIONORIGIN_BR] [int] NOT NULL,
[TAXFISCALCLASSIFICATION_BR] [nvarchar](10) NOT NULL,
[TAXSERVICECODE_BR] [nvarchar](10) NOT NULL,
[UNITVOLUME] [numeric](32, 16) NOT NULL,
[USEALTITEMID] [int] NOT NULL,
[WIDTH] [numeric](32, 16) NOT NULL,
[WMSPICKINGQTYTIME] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-137955366_1429128816] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-137955366_-474954108] UNIQUE NONCLUSTERED 
(
[PRODUCT] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ABCCONTRIBUTIONMARGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ABCCONTRIBUTIONMARGIN]  DEFAULT ((0)) FOR [ABCCONTRIBUTIONMARGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ABCREVENUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ABCREVENUE]  DEFAULT ((0)) FOR [ABCREVENUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ABCTIEUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ABCTIEUP]  DEFAULT ((0)) FOR [ABCTIEUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ABCVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ABCVALUE]  DEFAULT ((0)) FOR [ABCVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ALTITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ALTITEMID]  DEFAULT ('') FOR [ALTITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_APPROXTAXVALUE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_APPROXTAXVALUE_BR]  DEFAULT ((0)) FOR [APPROXTAXVALUE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_BATCHNUMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_BATCHNUMGROUPID]  DEFAULT ('') FOR [BATCHNUMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_COSTMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_COSTMODEL]  DEFAULT ((0)) FOR [COSTMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_DENSITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_DENSITY]  DEFAULT ((0)) FOR [DENSITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_DEPTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_DEPTH]  DEFAULT ((0)) FOR [DEPTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_EXCEPTIONCODE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_EXCEPTIONCODE_BR]  DEFAULT ('') FOR [EXCEPTIONCODE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_GROSSDEPTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_GROSSDEPTH]  DEFAULT ((0)) FOR [GROSSDEPTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_GROSSHEIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_GROSSHEIGHT]  DEFAULT ((0)) FOR [GROSSHEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_GROSSWIDTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_GROSSWIDTH]  DEFAULT ((0)) FOR [GROSSWIDTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_HEIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_HEIGHT]  DEFAULT ((0)) FOR [HEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_INVENTPRODUCTTYPE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_INVENTPRODUCTTYPE_BR]  DEFAULT ('') FOR [INVENTPRODUCTTYPE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ITEMBUYERGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ITEMBUYERGROUPID]  DEFAULT ('') FOR [ITEMBUYERGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ITEMDIMCOSTPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ITEMDIMCOSTPRICE]  DEFAULT ((0)) FOR [ITEMDIMCOSTPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_ITEMTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_ITEMTYPE]  DEFAULT ((0)) FOR [ITEMTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_NAMEALIAS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_NAMEALIAS]  DEFAULT ('') FOR [NAMEALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_NETWEIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_NETWEIGHT]  DEFAULT ((0)) FOR [NETWEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PBAINVENTITEMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PBAINVENTITEMGROUPID]  DEFAULT ('') FOR [PBAINVENTITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PBAITEMCONFIGURABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PBAITEMCONFIGURABLE]  DEFAULT ((0)) FOR [PBAITEMCONFIGURABLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PRIMARYVENDORID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PRIMARYVENDORID]  DEFAULT ('') FOR [PRIMARYVENDORID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PRODGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PRODGROUPID]  DEFAULT ('') FOR [PRODGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PRODPOOLID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PRODPOOLID]  DEFAULT ('') FOR [PRODPOOLID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PROJCATEGORYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PROJCATEGORYID]  DEFAULT ('') FOR [PROJCATEGORYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PROPERTYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PROPERTYID]  DEFAULT ('') FOR [PROPERTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_PURCHMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_PURCHMODEL]  DEFAULT ((0)) FOR [PURCHMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_REQGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_REQGROUPID]  DEFAULT ('') FOR [REQGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_SALESCONTRIBUTIONRATIO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_SALESCONTRIBUTIONRATIO]  DEFAULT ((0)) FOR [SALESCONTRIBUTIONRATIO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_SALESMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_SALESMODEL]  DEFAULT ((0)) FOR [SALESMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_SALESPERCENTMARKUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_SALESPERCENTMARKUP]  DEFAULT ((0)) FOR [SALESPERCENTMARKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_SALESPRICEMODELBASIC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_SALESPRICEMODELBASIC]  DEFAULT ((0)) FOR [SALESPRICEMODELBASIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_SERIALNUMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_SERIALNUMGROUPID]  DEFAULT ('') FOR [SERIALNUMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_SORTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_SORTCODE]  DEFAULT ((0)) FOR [SORTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_TARAWEIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_TARAWEIGHT]  DEFAULT ((0)) FOR [TARAWEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_TAXATIONORIGIN_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_TAXATIONORIGIN_BR]  DEFAULT ((0)) FOR [TAXATIONORIGIN_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_TAXFISCALCLASSIFICATION_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_TAXFISCALCLASSIFICATION_BR]  DEFAULT ('') FOR [TAXFISCALCLASSIFICATION_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_TAXSERVICECODE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_TAXSERVICECODE_BR]  DEFAULT ('') FOR [TAXSERVICECODE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_UNITVOLUME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_UNITVOLUME]  DEFAULT ((0)) FOR [UNITVOLUME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_USEALTITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_USEALTITEMID]  DEFAULT ((0)) FOR [USEALTITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_WIDTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_WIDTH]  DEFAULT ((0)) FOR [WIDTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLE_WMSPICKINGQTYTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLE] ADD  CONSTRAINT [DF_INVENTTABLE_WMSPICKINGQTYTIME]  DEFAULT ((0)) FOR [WMSPICKINGQTYTIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[INVENTTABLEMODULE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[INVENTTABLEMODULE](
[RECID] [bigint] NOT NULL,
[ALLOCATEMARKUP] [int] NOT NULL,
[ENDDISC] [int] NOT NULL,
[INTERCOMPANYBLOCKED] [int] NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[LINEDISC] [nvarchar](10) NOT NULL,
[MARKUP] [numeric](32, 16) NOT NULL,
[MARKUPGROUPID] [nvarchar](10) NOT NULL,
[MAXIMUMRETAILPRICE_IN] [numeric](32, 16) NOT NULL,
[MODULETYPE] [int] NOT NULL,
[MULTILINEDISC] [nvarchar](10) NOT NULL,
[OVERDELIVERYPCT] [numeric](32, 16) NOT NULL,
[PRICE] [numeric](32, 16) NOT NULL,
[PRICEDATE] [date] NOT NULL,
[PRICEQTY] [numeric](32, 16) NOT NULL,
[PRICEUNIT] [numeric](32, 16) NOT NULL,
[SUPPITEMGROUPID] [nvarchar](10) NOT NULL,
[TAXITEMGROUPID] [nvarchar](10) NOT NULL,
[UNDERDELIVERYPCT] [numeric](32, 16) NOT NULL,
[UNITID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1890880046_1242579072] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[MODULETYPE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_ALLOCATEMARKUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_ALLOCATEMARKUP]  DEFAULT ((0)) FOR [ALLOCATEMARKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_ENDDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_ENDDISC]  DEFAULT ((0)) FOR [ENDDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_INTERCOMPANYBLOCKED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_INTERCOMPANYBLOCKED]  DEFAULT ((0)) FOR [INTERCOMPANYBLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_LINEDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_LINEDISC]  DEFAULT ('') FOR [LINEDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_MARKUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_MARKUP]  DEFAULT ((0)) FOR [MARKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_MARKUPGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_MARKUPGROUPID]  DEFAULT ('') FOR [MARKUPGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_MAXIMUMRETAILPRICE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_MAXIMUMRETAILPRICE_IN]  DEFAULT ((0)) FOR [MAXIMUMRETAILPRICE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_MODULETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_MODULETYPE]  DEFAULT ((0)) FOR [MODULETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_MULTILINEDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_MULTILINEDISC]  DEFAULT ('') FOR [MULTILINEDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_OVERDELIVERYPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_OVERDELIVERYPCT]  DEFAULT ((0)) FOR [OVERDELIVERYPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_PRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_PRICE]  DEFAULT ((0)) FOR [PRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_PRICEDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_PRICEDATE]  DEFAULT ('1900-01-01') FOR [PRICEDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_PRICEQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_PRICEQTY]  DEFAULT ((0)) FOR [PRICEQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_PRICEUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_PRICEUNIT]  DEFAULT ((0)) FOR [PRICEUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_SUPPITEMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_SUPPITEMGROUPID]  DEFAULT ('') FOR [SUPPITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_TAXITEMGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_TAXITEMGROUPID]  DEFAULT ('') FOR [TAXITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_UNDERDELIVERYPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_UNDERDELIVERYPCT]  DEFAULT ((0)) FOR [UNDERDELIVERYPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_INVENTTABLEMODULE_UNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[INVENTTABLEMODULE] ADD  CONSTRAINT [DF_INVENTTABLEMODULE_UNITID]  DEFAULT ('') FOR [UNITID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[INVENTTABLEMODULE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[JMGIPCACTIVITY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[JMGIPCACTIVITY](
[RECID] [bigint] NOT NULL,
[ACTIVITY] [nvarchar](10) NOT NULL,
[BREAKDROP] [int] NOT NULL,
[CATEGORY] [nvarchar](10) NOT NULL,
[JOBID] [nvarchar](20) NOT NULL,
[SIGNIN] [int] NOT NULL,
[SIGNINOUT] [int] NOT NULL,
[TYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-765664409_828124743] PRIMARY KEY CLUSTERED 
(
[ACTIVITY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-765664409_1805009001] UNIQUE NONCLUSTERED 
(
[CATEGORY] ASC,
[ACTIVITY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-765664409_-937149049] UNIQUE NONCLUSTERED 
(
[JOBID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_JMGIPCACTIVITY_ACTIVITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[JMGIPCACTIVITY] ADD  CONSTRAINT [DF_JMGIPCACTIVITY_ACTIVITY]  DEFAULT ('') FOR [ACTIVITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_JMGIPCACTIVITY_BREAKDROP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[JMGIPCACTIVITY] ADD  CONSTRAINT [DF_JMGIPCACTIVITY_BREAKDROP]  DEFAULT ((0)) FOR [BREAKDROP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_JMGIPCACTIVITY_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[JMGIPCACTIVITY] ADD  CONSTRAINT [DF_JMGIPCACTIVITY_CATEGORY]  DEFAULT ('') FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_JMGIPCACTIVITY_JOBID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[JMGIPCACTIVITY] ADD  CONSTRAINT [DF_JMGIPCACTIVITY_JOBID]  DEFAULT ('') FOR [JOBID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_JMGIPCACTIVITY_SIGNIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[JMGIPCACTIVITY] ADD  CONSTRAINT [DF_JMGIPCACTIVITY_SIGNIN]  DEFAULT ((0)) FOR [SIGNIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_JMGIPCACTIVITY_SIGNINOUT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[JMGIPCACTIVITY] ADD  CONSTRAINT [DF_JMGIPCACTIVITY_SIGNINOUT]  DEFAULT ((0)) FOR [SIGNINOUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_JMGIPCACTIVITY_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[JMGIPCACTIVITY] ADD  CONSTRAINT [DF_JMGIPCACTIVITY_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[JMGIPCACTIVITY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LANGUAGETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LANGUAGETABLE](
[RECID] [bigint] NOT NULL,
[LABELFILE] [int] NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[USERDEFINEDLANGUAGE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1680185576_-1273337705] PRIMARY KEY CLUSTERED 
(
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LANGUAGETABLE_LABELFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LANGUAGETABLE] ADD  CONSTRAINT [DF_LANGUAGETABLE_LABELFILE]  DEFAULT ((0)) FOR [LABELFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LANGUAGETABLE_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LANGUAGETABLE] ADD  CONSTRAINT [DF_LANGUAGETABLE_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LANGUAGETABLE_USERDEFINEDLANGUAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LANGUAGETABLE] ADD  CONSTRAINT [DF_LANGUAGETABLE_USERDEFINEDLANGUAGE]  DEFAULT ((0)) FOR [USERDEFINEDLANGUAGE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LANGUAGETABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LEDGER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LEDGER](
[RECID] [bigint] NOT NULL,
[ACCOUNTINGCURRENCY] [nvarchar](3) NOT NULL,
[BUDGETEXCHANGERATETYPE] [bigint] NOT NULL,
[CHARTOFACCOUNTS] [bigint] NOT NULL,
[DEFAULTEXCHANGERATETYPE] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[FISCALCALENDAR] [bigint] NOT NULL,
[ISBUDGETCONTROLENABLED] [int] NOT NULL,
[NAME] [nvarchar](20) NOT NULL,
[PRIMARYFORLEGALENTITY] [bigint] NOT NULL,
[REPORTINGCURRENCY] [nvarchar](3) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-103131727_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-103131727_-1565480838] UNIQUE NONCLUSTERED 
(
[PRIMARYFORLEGALENTITY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-103131727_-1966747349] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_ACCOUNTINGCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_ACCOUNTINGCURRENCY]  DEFAULT ('') FOR [ACCOUNTINGCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_BUDGETEXCHANGERATETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_BUDGETEXCHANGERATETYPE]  DEFAULT ((0)) FOR [BUDGETEXCHANGERATETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_CHARTOFACCOUNTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_CHARTOFACCOUNTS]  DEFAULT ((0)) FOR [CHARTOFACCOUNTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_DEFAULTEXCHANGERATETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_DEFAULTEXCHANGERATETYPE]  DEFAULT ((0)) FOR [DEFAULTEXCHANGERATETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_FISCALCALENDAR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_FISCALCALENDAR]  DEFAULT ((0)) FOR [FISCALCALENDAR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_ISBUDGETCONTROLENABLED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_ISBUDGETCONTROLENABLED]  DEFAULT ((0)) FOR [ISBUDGETCONTROLENABLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_PRIMARYFORLEGALENTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_PRIMARYFORLEGALENTITY]  DEFAULT ((0)) FOR [PRIMARYFORLEGALENTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LEDGER_REPORTINGCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LEDGER] ADD  CONSTRAINT [DF_LEDGER_REPORTINGCURRENCY]  DEFAULT ('') FOR [REPORTINGCURRENCY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LEDGER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSCOUNTRYREGION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION](
[RECID] [bigint] NOT NULL,
[ADDRESSUSEZIPPLUS4] [int] NOT NULL,
[ADDRFORMAT] [nvarchar](10) NOT NULL,
[BACENCODE_BR] [nvarchar](4) NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[ISIMMUTABLE] [int] NOT NULL,
[ISOCODE] [nchar](2) NOT NULL,
[TIMEZONE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_128014817_-305463479] PRIMARY KEY CLUSTERED 
(
[COUNTRYREGIONID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_ADDRESSUSEZIPPLUS4]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_ADDRESSUSEZIPPLUS4]  DEFAULT ((0)) FOR [ADDRESSUSEZIPPLUS4]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_ADDRFORMAT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_ADDRFORMAT]  DEFAULT ('') FOR [ADDRFORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_BACENCODE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_BACENCODE_BR]  DEFAULT ('') FOR [BACENCODE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_ISIMMUTABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_ISIMMUTABLE]  DEFAULT ((0)) FOR [ISIMMUTABLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_ISOCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_ISOCODE]  DEFAULT ('') FOR [ISOCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGION_TIMEZONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGION_TIMEZONE]  DEFAULT ((0)) FOR [TIMEZONE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSCOUNTRYREGION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION](
[RECID] [bigint] NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[LONGNAME] [nvarchar](255) NOT NULL,
[SHORTNAME] [nvarchar](255) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_96499510_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_96499510_-1112445765] UNIQUE NONCLUSTERED 
(
[COUNTRYREGIONID] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_LONGNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_LONGNAME]  DEFAULT ('') FOR [LONGNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_SHORTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION_SHORTNAME]  DEFAULT ('') FOR [SHORTNAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSCOUNTY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSCOUNTY](
[RECID] [bigint] NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[COUNTYCODE_SP] [nchar](2) NOT NULL,
[COUNTYID] [nvarchar](10) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[STATEID] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1242622437_-816487246] PRIMARY KEY CLUSTERED 
(
[COUNTRYREGIONID] ASC,
[STATEID] ASC,
[COUNTYID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTY_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTY_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTY_COUNTYCODE_SP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTY_COUNTYCODE_SP]  DEFAULT ('') FOR [COUNTYCODE_SP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTY_COUNTYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTY_COUNTYID]  DEFAULT ('') FOR [COUNTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTY_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTY_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSCOUNTY_STATEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSCOUNTY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSCOUNTY_STATEID]  DEFAULT ('') FOR [STATEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSCOUNTY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSDISTRICT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSDISTRICT](
[RECID] [bigint] NOT NULL,
[CITY] [bigint] NOT NULL,
[COUNTRYREGIONID_RU] [nvarchar](10) NOT NULL,
[COUNTYID_RU] [nvarchar](10) NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PROPERTIES_RU] [bigint] NOT NULL,
[STATEID_RU] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1765824537_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1765824537_246310896] UNIQUE NONCLUSTERED 
(
[NAME] ASC,
[CITY] ASC,
[COUNTRYREGIONID_RU] ASC,
[STATEID_RU] ASC,
[COUNTYID_RU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSDISTRICT_CITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSDISTRICT] ADD  CONSTRAINT [DF_LOGISTICSADDRESSDISTRICT_CITY]  DEFAULT ((0)) FOR [CITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSDISTRICT_COUNTRYREGIONID_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSDISTRICT] ADD  CONSTRAINT [DF_LOGISTICSADDRESSDISTRICT_COUNTRYREGIONID_RU]  DEFAULT ('') FOR [COUNTRYREGIONID_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSDISTRICT_COUNTYID_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSDISTRICT] ADD  CONSTRAINT [DF_LOGISTICSADDRESSDISTRICT_COUNTYID_RU]  DEFAULT ('') FOR [COUNTYID_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSDISTRICT_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSDISTRICT] ADD  CONSTRAINT [DF_LOGISTICSADDRESSDISTRICT_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSDISTRICT_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSDISTRICT] ADD  CONSTRAINT [DF_LOGISTICSADDRESSDISTRICT_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSDISTRICT_PROPERTIES_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSDISTRICT] ADD  CONSTRAINT [DF_LOGISTICSADDRESSDISTRICT_PROPERTIES_RU]  DEFAULT ((0)) FOR [PROPERTIES_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSDISTRICT_STATEID_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSDISTRICT] ADD  CONSTRAINT [DF_LOGISTICSADDRESSDISTRICT_STATEID_RU]  DEFAULT ('') FOR [STATEID_RU]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSDISTRICT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSFORMATHEADING]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSFORMATHEADING](
[RECID] [bigint] NOT NULL,
[ADDRFORMAT] [nvarchar](10) NOT NULL,
[NAME] [nvarchar](100) NOT NULL,
[UPDATETOADDRESS] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_940083590_1389798729] PRIMARY KEY CLUSTERED 
(
[ADDRFORMAT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATHEADING_ADDRFORMAT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATHEADING] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATHEADING_ADDRFORMAT]  DEFAULT ('') FOR [ADDRFORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATHEADING_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATHEADING] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATHEADING_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATHEADING_UPDATETOADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATHEADING] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATHEADING_UPDATETOADDRESS]  DEFAULT ((0)) FOR [UPDATETOADDRESS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSFORMATHEADING] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSFORMATLINES]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSFORMATLINES](
[RECID] [bigint] NOT NULL,
[ADDRFORMAT] [nvarchar](10) NOT NULL,
[DATAENTRYONLY] [int] NOT NULL,
[ELEMENT] [int] NOT NULL,
[INACTIVE] [int] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[SEPARATOR] [nvarchar](10) NOT NULL,
[SEPARATORCRLF] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-900029417_819092615] PRIMARY KEY CLUSTERED 
(
[ADDRFORMAT] ASC,
[LINENUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-900029417_1662335864] UNIQUE NONCLUSTERED 
(
[ADDRFORMAT] ASC,
[ELEMENT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATLINES_ADDRFORMAT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATLINES] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATLINES_ADDRFORMAT]  DEFAULT ('') FOR [ADDRFORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATLINES_DATAENTRYONLY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATLINES] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATLINES_DATAENTRYONLY]  DEFAULT ((0)) FOR [DATAENTRYONLY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATLINES_ELEMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATLINES] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATLINES_ELEMENT]  DEFAULT ((0)) FOR [ELEMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATLINES_INACTIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATLINES] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATLINES_INACTIVE]  DEFAULT ((0)) FOR [INACTIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATLINES_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATLINES] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATLINES_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATLINES_SEPARATOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATLINES] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATLINES_SEPARATOR]  DEFAULT ('') FOR [SEPARATOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSFORMATLINES_SEPARATORCRLF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSFORMATLINES] ADD  CONSTRAINT [DF_LOGISTICSADDRESSFORMATLINES_SEPARATORCRLF]  DEFAULT ((0)) FOR [SEPARATORCRLF]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSFORMATLINES] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSSCITY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSSCITY](
[RECID] [bigint] NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[COUNTYID] [nvarchar](10) NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[IBGECODE_BR] [nvarchar](7) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[STATEID] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1023594959_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSCITY_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSCITY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSCITY_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSCITY_COUNTYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSCITY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSCITY_COUNTYID]  DEFAULT ('') FOR [COUNTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSCITY_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSCITY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSCITY_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSCITY_IBGECODE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSCITY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSCITY_IBGECODE_BR]  DEFAULT ('') FOR [IBGECODE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSCITY_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSCITY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSCITY_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSCITY_STATEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSCITY] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSCITY_STATEID]  DEFAULT ('') FOR [STATEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSSCITY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSSTATE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSSTATE](
[RECID] [bigint] NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[INTRASTATCODE] [nvarchar](10) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[STATEID] [nvarchar](10) NOT NULL,
[TIMEZONE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-727715432_-971710904] PRIMARY KEY CLUSTERED 
(
[COUNTRYREGIONID] ASC,
[STATEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSTATE_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSTATE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSTATE_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSTATE_INTRASTATCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSTATE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSTATE_INTRASTATCODE]  DEFAULT ('') FOR [INTRASTATCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSTATE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSTATE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSTATE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSTATE_STATEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSTATE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSTATE_STATEID]  DEFAULT ('') FOR [STATEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSSTATE_TIMEZONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSSTATE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSSTATE_TIMEZONE]  DEFAULT ((0)) FOR [TIMEZONE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSSTATE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSADDRESSZIPCODE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSADDRESSZIPCODE](
[RECID] [bigint] NOT NULL,
[CITY] [nvarchar](60) NOT NULL,
[CITYALIAS] [nvarchar](30) NOT NULL,
[CITYRECID] [bigint] NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[COUNTY] [nvarchar](10) NOT NULL,
[DISTRICT] [bigint] NOT NULL,
[DISTRICTNAME] [nvarchar](60) NOT NULL,
[EVENODD] [int] NOT NULL,
[FROMNUM] [int] NOT NULL,
[STATE] [nvarchar](10) NOT NULL,
[STREETNAME] [nvarchar](60) NOT NULL,
[TIMEZONE] [int] NOT NULL,
[TONUM] [int] NOT NULL,
[ZIPCODE] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_966996751_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_CITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_CITY]  DEFAULT ('') FOR [CITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_CITYALIAS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_CITYALIAS]  DEFAULT ('') FOR [CITYALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_CITYRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_CITYRECID]  DEFAULT ((0)) FOR [CITYRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_COUNTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_COUNTY]  DEFAULT ('') FOR [COUNTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_DISTRICT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_DISTRICT]  DEFAULT ((0)) FOR [DISTRICT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_DISTRICTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_DISTRICTNAME]  DEFAULT ('') FOR [DISTRICTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_EVENODD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_EVENODD]  DEFAULT ((0)) FOR [EVENODD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_FROMNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_FROMNUM]  DEFAULT ((0)) FOR [FROMNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_STATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_STATE]  DEFAULT ('') FOR [STATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_STREETNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_STREETNAME]  DEFAULT ('') FOR [STREETNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_TIMEZONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_TIMEZONE]  DEFAULT ((0)) FOR [TIMEZONE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_TONUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_TONUM]  DEFAULT ((0)) FOR [TONUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSADDRESSZIPCODE_ZIPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSADDRESSZIPCODE] ADD  CONSTRAINT [DF_LOGISTICSADDRESSZIPCODE_ZIPCODE]  DEFAULT ('') FOR [ZIPCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSADDRESSZIPCODE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSELECTRONICADDRESS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSELECTRONICADDRESS](
[RECID] [bigint] NOT NULL,
[COUNTRYREGIONCODE] [nvarchar](5) NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[ISINSTANTMESSAGE] [int] NOT NULL,
[ISMOBILEPHONE] [int] NOT NULL,
[ISPRIMARY] [int] NOT NULL,
[ISPRIVATE] [int] NOT NULL,
[LOCATION] [bigint] NOT NULL,
[LOCATOR] [nvarchar](255) NOT NULL,
[LOCATOREXTENSION] [nvarchar](10) NOT NULL,
[TYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1137359931_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_COUNTRYREGIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_COUNTRYREGIONCODE]  DEFAULT ('') FOR [COUNTRYREGIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_ISINSTANTMESSAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_ISINSTANTMESSAGE]  DEFAULT ((0)) FOR [ISINSTANTMESSAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_ISMOBILEPHONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_ISMOBILEPHONE]  DEFAULT ((0)) FOR [ISMOBILEPHONE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_ISPRIMARY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_ISPRIMARY]  DEFAULT ((0)) FOR [ISPRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_ISPRIVATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_ISPRIVATE]  DEFAULT ((0)) FOR [ISPRIVATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_LOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_LOCATION]  DEFAULT ((0)) FOR [LOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_LOCATOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_LOCATOR]  DEFAULT ('') FOR [LOCATOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_LOCATOREXTENSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_LOCATOREXTENSION]  DEFAULT ('') FOR [LOCATOREXTENSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSELECTRONICADDRESS_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSELECTRONICADDRESS] ADD  CONSTRAINT [DF_LOGISTICSELECTRONICADDRESS_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSELECTRONICADDRESS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSLOCATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSLOCATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[DUNSNUMBERRECID] [bigint] NOT NULL,
[ISPOSTALADDRESS] [int] NOT NULL,
[LOCATIONID] [nvarchar](30) NOT NULL,
[PARENTLOCATION] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1358324402_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1358324402_760607746] UNIQUE NONCLUSTERED 
(
[LOCATIONID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATION_DUNSNUMBERRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATION_DUNSNUMBERRECID]  DEFAULT ((0)) FOR [DUNSNUMBERRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATION_ISPOSTALADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATION_ISPOSTALADDRESS]  DEFAULT ((0)) FOR [ISPOSTALADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATION_LOCATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATION_LOCATIONID]  DEFAULT ('') FOR [LOCATIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATION_PARENTLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATION_PARENTLOCATION]  DEFAULT ((0)) FOR [PARENTLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATION_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATION_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATION_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATION_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSLOCATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSLOCATIONEXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSLOCATIONEXT](
[RECID] [bigint] NOT NULL,
[LOCATION] [bigint] NOT NULL,
[SALESCALENDARID] [nvarchar](10) NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-45831765_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-45831765_167473448] UNIQUE NONCLUSTERED 
(
[LOCATION] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONEXT_LOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONEXT] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONEXT_LOCATION]  DEFAULT ((0)) FOR [LOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONEXT_SALESCALENDARID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONEXT] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONEXT_SALESCALENDARID]  DEFAULT ('') FOR [SALESCALENDARID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONEXT_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONEXT] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONEXT_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSLOCATIONEXT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSLOCATIONROLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSLOCATIONROLE](
[RECID] [bigint] NOT NULL,
[ISCONTACTINFO] [int] NOT NULL,
[ISPOSTALADDRESS] [int] NOT NULL,
[NAME] [nvarchar](40) NOT NULL,
[TYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_517951034_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_517951034_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONROLE_ISCONTACTINFO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONROLE] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONROLE_ISCONTACTINFO]  DEFAULT ((0)) FOR [ISCONTACTINFO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONROLE_ISPOSTALADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONROLE] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONROLE_ISPOSTALADDRESS]  DEFAULT ((0)) FOR [ISPOSTALADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONROLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONROLE] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONROLE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONROLE_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONROLE] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONROLE_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSLOCATIONROLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSLOCATIONROLETRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSLOCATIONROLETRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[LOCATIONROLE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_32160965_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_32160965_619597902] UNIQUE NONCLUSTERED 
(
[LOCATIONROLE] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONROLETRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONROLETRANSLATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONROLETRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONROLETRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONROLETRANSLATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONROLETRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSLOCATIONROLETRANSLATION_LOCATIONROLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSLOCATIONROLETRANSLATION] ADD  CONSTRAINT [DF_LOGISTICSLOCATIONROLETRANSLATION_LOCATIONROLE]  DEFAULT ((0)) FOR [LOCATIONROLE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSLOCATIONROLETRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[LOGISTICSPOSTALADDRESS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[LOGISTICSPOSTALADDRESS](
[RECID] [bigint] NOT NULL,
[ADDRESS] [nvarchar](250) NOT NULL,
[BUILDINGCOMPLIMENT] [nvarchar](60) NOT NULL,
[CITY] [nvarchar](60) NOT NULL,
[CITYRECID] [bigint] NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[COUNTY] [nvarchar](10) NOT NULL,
[DISTRICT] [bigint] NOT NULL,
[DISTRICTNAME] [nvarchar](60) NOT NULL,
[ISPRIVATE] [int] NOT NULL,
[LATITUDE] [numeric](32, 16) NOT NULL,
[LOCATION] [bigint] NOT NULL,
[LONGITUDE] [numeric](32, 16) NOT NULL,
[POSTBOX] [nvarchar](20) NOT NULL,
[STATE] [nvarchar](10) NOT NULL,
[STREET] [nvarchar](250) NOT NULL,
[STREETNUMBER] [nvarchar](20) NOT NULL,
[TIMEZONE] [int] NOT NULL,
[VALIDFROM] [datetime] NOT NULL,
[VALIDFROMTZID] [int] NOT NULL,
[VALIDTO] [datetime] NOT NULL,
[VALIDTOTZID] [int] NOT NULL,
[ZIPCODE] [nvarchar](10) NOT NULL,
[ZIPCODERECID] [bigint] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_621354382_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_621354382_2047046459] UNIQUE NONCLUSTERED 
(
[LOCATION] ASC,
[VALIDFROM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_ADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_ADDRESS]  DEFAULT ('') FOR [ADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_BUILDINGCOMPLIMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_BUILDINGCOMPLIMENT]  DEFAULT ('') FOR [BUILDINGCOMPLIMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_CITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_CITY]  DEFAULT ('') FOR [CITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_CITYRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_CITYRECID]  DEFAULT ((0)) FOR [CITYRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_COUNTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_COUNTY]  DEFAULT ('') FOR [COUNTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_DISTRICT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_DISTRICT]  DEFAULT ((0)) FOR [DISTRICT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_DISTRICTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_DISTRICTNAME]  DEFAULT ('') FOR [DISTRICTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_ISPRIVATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_ISPRIVATE]  DEFAULT ((0)) FOR [ISPRIVATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_LATITUDE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_LATITUDE]  DEFAULT ((0)) FOR [LATITUDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_LOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_LOCATION]  DEFAULT ((0)) FOR [LOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_LONGITUDE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_LONGITUDE]  DEFAULT ((0)) FOR [LONGITUDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_POSTBOX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_POSTBOX]  DEFAULT ('') FOR [POSTBOX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_STATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_STATE]  DEFAULT ('') FOR [STATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_STREET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_STREET]  DEFAULT ('') FOR [STREET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_STREETNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_STREETNUMBER]  DEFAULT ('') FOR [STREETNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_TIMEZONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_TIMEZONE]  DEFAULT ((0)) FOR [TIMEZONE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_VALIDFROM]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_VALIDFROMTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_VALIDFROMTZID]  DEFAULT ((37001)) FOR [VALIDFROMTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_VALIDTO]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_VALIDTOTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_VALIDTOTZID]  DEFAULT ((37001)) FOR [VALIDTOTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_ZIPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_ZIPCODE]  DEFAULT ('') FOR [ZIPCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_ZIPCODERECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_ZIPCODERECID]  DEFAULT ((0)) FOR [ZIPCODERECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_LOGISTICSPOSTALADDRESS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[LOGISTICSPOSTALADDRESS] ADD  CONSTRAINT [DF_LOGISTICSPOSTALADDRESS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[LOGISTICSPOSTALADDRESS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[MARKUPAUTOLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[MARKUPAUTOLINE](
[RECID] [bigint] NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[CUSTOMSASSESSABLEVALUE_IN] [int] NOT NULL,
[FROMAMOUNT] [numeric](32, 16) NOT NULL,
[KEEP] [int] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[MARKUPCATEGORY] [int] NOT NULL,
[MARKUPCODE] [nvarchar](10) NOT NULL,
[MARKUPCURRENCYCODE] [nvarchar](3) NOT NULL,
[MODULECATEGORY] [int] NOT NULL,
[MODULETYPE] [int] NOT NULL,
[NOTIONALCHARGES_IN] [int] NOT NULL,
[NOTIONALPCT_IN] [numeric](32, 16) NOT NULL,
[TABLERECID] [bigint] NOT NULL,
[TABLETABLEID] [int] NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[TOAMOUNT] [numeric](32, 16) NOT NULL,
[TXT] [nvarchar](60) NOT NULL,
[VALUE] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1293693211_-1942181553] PRIMARY KEY CLUSTERED 
(
[TABLERECID] ASC,
[TABLETABLEID] ASC,
[LINENUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_CUSTOMSASSESSABLEVALUE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_CUSTOMSASSESSABLEVALUE_IN]  DEFAULT ((0)) FOR [CUSTOMSASSESSABLEVALUE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_FROMAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_FROMAMOUNT]  DEFAULT ((0)) FOR [FROMAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_KEEP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_KEEP]  DEFAULT ((0)) FOR [KEEP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_MARKUPCATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_MARKUPCATEGORY]  DEFAULT ((0)) FOR [MARKUPCATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_MARKUPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_MARKUPCODE]  DEFAULT ('') FOR [MARKUPCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_MARKUPCURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_MARKUPCURRENCYCODE]  DEFAULT ('') FOR [MARKUPCURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_MODULECATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_MODULECATEGORY]  DEFAULT ((0)) FOR [MODULECATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_MODULETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_MODULETYPE]  DEFAULT ((0)) FOR [MODULETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_NOTIONALCHARGES_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_NOTIONALCHARGES_IN]  DEFAULT ((0)) FOR [NOTIONALCHARGES_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_NOTIONALPCT_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_NOTIONALPCT_IN]  DEFAULT ((0)) FOR [NOTIONALPCT_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_TABLERECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_TABLERECID]  DEFAULT ((0)) FOR [TABLERECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_TABLETABLEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_TABLETABLEID]  DEFAULT ((0)) FOR [TABLETABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_TOAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_TOAMOUNT]  DEFAULT ((0)) FOR [TOAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_TXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_TXT]  DEFAULT ('') FOR [TXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOLINE_VALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOLINE] ADD  CONSTRAINT [DF_MARKUPAUTOLINE_VALUE]  DEFAULT ((0)) FOR [VALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[MARKUPAUTOLINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[MARKUPAUTOTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[MARKUPAUTOTABLE](
[RECID] [bigint] NOT NULL,
[ACCOUNTCODE] [int] NOT NULL,
[ACCOUNTRELATION] [nvarchar](20) NOT NULL,
[DLVMODECODE] [int] NOT NULL,
[DLVMODERELATION] [nvarchar](20) NOT NULL,
[ITEMCODE] [int] NOT NULL,
[ITEMRELATION] [nvarchar](20) NOT NULL,
[MARKUPRETURN] [int] NOT NULL,
[MODULECATEGORY] [int] NOT NULL,
[MODULETYPE] [int] NOT NULL,
[RETAILCONCESSIONFEE] [int] NOT NULL,
[RETURNRELATION] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_366724785_-1598920379] PRIMARY KEY CLUSTERED 
(
[MODULECATEGORY] ASC,
[MODULETYPE] ASC,
[ITEMCODE] ASC,
[ITEMRELATION] ASC,
[ACCOUNTCODE] ASC,
[ACCOUNTRELATION] ASC,
[MARKUPRETURN] ASC,
[RETURNRELATION] ASC,
[RETAILCONCESSIONFEE] ASC,
[DLVMODECODE] ASC,
[DLVMODERELATION] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_ACCOUNTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_ACCOUNTCODE]  DEFAULT ((0)) FOR [ACCOUNTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_ACCOUNTRELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_ACCOUNTRELATION]  DEFAULT ('') FOR [ACCOUNTRELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_DLVMODECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_DLVMODECODE]  DEFAULT ((0)) FOR [DLVMODECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_DLVMODERELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_DLVMODERELATION]  DEFAULT ('') FOR [DLVMODERELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_ITEMCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_ITEMCODE]  DEFAULT ((0)) FOR [ITEMCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_ITEMRELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_ITEMRELATION]  DEFAULT ('') FOR [ITEMRELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_MARKUPRETURN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_MARKUPRETURN]  DEFAULT ((0)) FOR [MARKUPRETURN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_MODULECATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_MODULECATEGORY]  DEFAULT ((0)) FOR [MODULECATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_MODULETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_MODULETYPE]  DEFAULT ((0)) FOR [MODULETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_RETAILCONCESSIONFEE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_RETAILCONCESSIONFEE]  DEFAULT ((0)) FOR [RETAILCONCESSIONFEE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPAUTOTABLE_RETURNRELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPAUTOTABLE] ADD  CONSTRAINT [DF_MARKUPAUTOTABLE_RETURNRELATION]  DEFAULT ('') FOR [RETURNRELATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[MARKUPAUTOTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[MARKUPTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[MARKUPTABLE](
[RECID] [bigint] NOT NULL,
[CUSTOMERLEDGERDIMENSION] [bigint] NOT NULL,
[CUSTPOSTING] [int] NOT NULL,
[CUSTTYPE] [int] NOT NULL,
[INTRASTAT_FI] [int] NOT NULL,
[ISLETTEROFCREDIT_SA] [int] NOT NULL,
[MARKUPCODE] [nvarchar](10) NOT NULL,
[MAXAMOUNT] [numeric](32, 16) NOT NULL,
[MODULETYPE] [int] NOT NULL,
[RETAILCONCESSIONFEE] [int] NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[TXT] [nvarchar](60) NOT NULL,
[USEINMATCHING] [int] NOT NULL,
[VENDORLEDGERDIMENSION] [bigint] NOT NULL,
[VENDPOSTING] [int] NOT NULL,
[VENDTYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1530831318_-1628860358] PRIMARY KEY CLUSTERED 
(
[MODULETYPE] ASC,
[MARKUPCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_CUSTOMERLEDGERDIMENSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_CUSTOMERLEDGERDIMENSION]  DEFAULT ((0)) FOR [CUSTOMERLEDGERDIMENSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_CUSTPOSTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_CUSTPOSTING]  DEFAULT ((0)) FOR [CUSTPOSTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_CUSTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_CUSTTYPE]  DEFAULT ((0)) FOR [CUSTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_INTRASTAT_FI]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_INTRASTAT_FI]  DEFAULT ((0)) FOR [INTRASTAT_FI]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_ISLETTEROFCREDIT_SA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_ISLETTEROFCREDIT_SA]  DEFAULT ((0)) FOR [ISLETTEROFCREDIT_SA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_MARKUPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_MARKUPCODE]  DEFAULT ('') FOR [MARKUPCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_MAXAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_MAXAMOUNT]  DEFAULT ((0)) FOR [MAXAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_MODULETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_MODULETYPE]  DEFAULT ((0)) FOR [MODULETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_RETAILCONCESSIONFEE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_RETAILCONCESSIONFEE]  DEFAULT ((0)) FOR [RETAILCONCESSIONFEE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_TXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_TXT]  DEFAULT ('') FOR [TXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_USEINMATCHING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_USEINMATCHING]  DEFAULT ((0)) FOR [USEINMATCHING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_VENDORLEDGERDIMENSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_VENDORLEDGERDIMENSION]  DEFAULT ((0)) FOR [VENDORLEDGERDIMENSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_VENDPOSTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_VENDPOSTING]  DEFAULT ((0)) FOR [VENDPOSTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_MARKUPTABLE_VENDTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[MARKUPTABLE] ADD  CONSTRAINT [DF_MARKUPTABLE_VENDTYPE]  DEFAULT ((0)) FOR [VENDTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[MARKUPTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH](
[RECID] [bigint] NOT NULL,
[ANCESTORORGANIZATION] [bigint] NOT NULL,
[DISTANCE] [int] NOT NULL,
[OMHIERARCHYTYPE] [bigint] NOT NULL,
[ORGANIZATION] [bigint] NOT NULL,
[VALIDFROM] [datetime] NOT NULL,
[VALIDFROMTZID] [int] NOT NULL,
[VALIDTO] [datetime] NOT NULL,
[VALIDTOTZID] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-76086348_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-76086348_-916295028] UNIQUE NONCLUSTERED 
(
[OMHIERARCHYTYPE] ASC,
[DISTANCE] ASC,
[ORGANIZATION] ASC,
[VALIDFROM] ASC,
[VALIDTO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_ANCESTORORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_ANCESTORORGANIZATION]  DEFAULT ((0)) FOR [ANCESTORORGANIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_DISTANCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_DISTANCE]  DEFAULT ((0)) FOR [DISTANCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_OMHIERARCHYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_OMHIERARCHYTYPE]  DEFAULT ((0)) FOR [OMHIERARCHYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_ORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_ORGANIZATION]  DEFAULT ((0)) FOR [ORGANIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDFROM]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDFROMTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDFROMTZID]  DEFAULT ((37001)) FOR [VALIDFROMTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDTO]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDTOTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] ADD  CONSTRAINT [DF_OMEXPLODEDORGANIZATIONSECURITYGRAPH_VALIDTOTZID]  DEFAULT ((37001)) FOR [VALIDTOTZID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[OMEXPLODEDORGANIZATIONSECURITYGRAPH] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[OMHIERARCHYPURPOSE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[OMHIERARCHYPURPOSE](
[RECID] [bigint] NOT NULL,
[HIERARCHYPURPOSE] [int] NOT NULL,
[HIERARCHYTYPE] [bigint] NOT NULL,
[ISDEFAULT] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_269376623_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_269376623_-1726555760] UNIQUE NONCLUSTERED 
(
[HIERARCHYPURPOSE] ASC,
[HIERARCHYTYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMHIERARCHYPURPOSE_HIERARCHYPURPOSE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMHIERARCHYPURPOSE] ADD  CONSTRAINT [DF_OMHIERARCHYPURPOSE_HIERARCHYPURPOSE]  DEFAULT ((0)) FOR [HIERARCHYPURPOSE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMHIERARCHYPURPOSE_HIERARCHYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMHIERARCHYPURPOSE] ADD  CONSTRAINT [DF_OMHIERARCHYPURPOSE_HIERARCHYTYPE]  DEFAULT ((0)) FOR [HIERARCHYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMHIERARCHYPURPOSE_ISDEFAULT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMHIERARCHYPURPOSE] ADD  CONSTRAINT [DF_OMHIERARCHYPURPOSE_ISDEFAULT]  DEFAULT ((0)) FOR [ISDEFAULT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[OMHIERARCHYPURPOSE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[OMINTERNALORGANIZATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[OMINTERNALORGANIZATION](
[RECID] [bigint] NOT NULL,
[ORGANIZATIONTYPE] [int] NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1760313484_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[OMINTERNALORGANIZATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[OMOPERATINGUNIT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[OMOPERATINGUNIT](
[RECID] [bigint] NOT NULL,
[HCMWORKER] [bigint] NULL,
[OMOPERATINGUNITNUMBER] [nvarchar](8) NOT NULL,
[OMOPERATINGUNITTYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-901362831_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-901362831_1785045346] UNIQUE NONCLUSTERED 
(
[OMOPERATINGUNITNUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMOPERATINGUNIT_OMOPERATINGUNITNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMOPERATINGUNIT] ADD  CONSTRAINT [DF_OMOPERATINGUNIT_OMOPERATINGUNITNUMBER]  DEFAULT ('') FOR [OMOPERATINGUNITNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_OMOPERATINGUNIT_OMOPERATINGUNITTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[OMOPERATINGUNIT] ADD  CONSTRAINT [DF_OMOPERATINGUNIT_OMOPERATINGUNITTYPE]  DEFAULT ((0)) FOR [OMOPERATINGUNITTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[OMOPERATINGUNIT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[PLFISCALTAXTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[PLFISCALTAXTABLE](
[RECID] [bigint] NOT NULL,
[FISCALPRINTERCODE] [nvarchar](20) NOT NULL,
[FISCALTAXCODE] [int] NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1142401777_-1211354216] PRIMARY KEY CLUSTERED 
(
[TAXCODE] ASC,
[FISCALPRINTERCODE] ASC,
[FISCALTAXCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PLFISCALTAXTABLE_FISCALPRINTERCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PLFISCALTAXTABLE] ADD  CONSTRAINT [DF_PLFISCALTAXTABLE_FISCALPRINTERCODE]  DEFAULT ('') FOR [FISCALPRINTERCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PLFISCALTAXTABLE_FISCALTAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PLFISCALTAXTABLE] ADD  CONSTRAINT [DF_PLFISCALTAXTABLE_FISCALTAXCODE]  DEFAULT ((0)) FOR [FISCALTAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PLFISCALTAXTABLE_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PLFISCALTAXTABLE] ADD  CONSTRAINT [DF_PLFISCALTAXTABLE_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[PLFISCALTAXTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[PRICEDISCGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[PRICEDISCGROUP](
[RECID] [bigint] NOT NULL,
[GROUPID] [nvarchar](10) NOT NULL,
[MODULE] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[TYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1621373531_2009434683] PRIMARY KEY CLUSTERED 
(
[MODULE] ASC,
[TYPE] ASC,
[GROUPID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCGROUP_GROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCGROUP] ADD  CONSTRAINT [DF_PRICEDISCGROUP_GROUPID]  DEFAULT ('') FOR [GROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCGROUP_MODULE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCGROUP] ADD  CONSTRAINT [DF_PRICEDISCGROUP_MODULE]  DEFAULT ((0)) FOR [MODULE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCGROUP_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCGROUP] ADD  CONSTRAINT [DF_PRICEDISCGROUP_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCGROUP_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCGROUP] ADD  CONSTRAINT [DF_PRICEDISCGROUP_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[PRICEDISCGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[PRICEDISCTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[PRICEDISCTABLE](
[RECID] [bigint] NOT NULL,
[ACCOUNTCODE] [int] NOT NULL,
[ACCOUNTRELATION] [nvarchar](20) NOT NULL,
[AGREEMENT] [nvarchar](10) NOT NULL,
[AGREEMENTHEADEREXT_RU] [bigint] NOT NULL,
[ALLOCATEMARKUP] [int] NOT NULL,
[AMOUNT] [numeric](32, 16) NOT NULL,
[CALENDARDAYS] [int] NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[DELIVERYTIME] [int] NOT NULL,
[FROMDATE] [date] NOT NULL,
[GENERICCURRENCY] [int] NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[ITEMCODE] [int] NOT NULL,
[ITEMRELATION] [nvarchar](20) NOT NULL,
[MARKUP] [numeric](32, 16) NOT NULL,
[MAXIMUMRETAILPRICE_IN] [numeric](32, 16) NOT NULL,
[MODULE] [int] NOT NULL,
[PERCENT1] [numeric](32, 16) NOT NULL,
[PERCENT2] [numeric](32, 16) NOT NULL,
[PRICEUNIT] [numeric](32, 16) NOT NULL,
[QUANTITYAMOUNTFROM] [numeric](32, 16) NOT NULL,
[QUANTITYAMOUNTTO] [numeric](32, 16) NOT NULL,
[RELATION] [int] NOT NULL,
[SEARCHAGAIN] [int] NOT NULL,
[TODATE] [date] NOT NULL,
[UNITID] [nvarchar](10) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_137462222_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_137462222_1904821809] UNIQUE NONCLUSTERED 
(
[RELATION] ASC,
[ITEMCODE] ASC,
[ITEMRELATION] ASC,
[ACCOUNTCODE] ASC,
[ACCOUNTRELATION] ASC,
[CURRENCY] ASC,
[INVENTDIMID] ASC,
[UNITID] ASC,
[QUANTITYAMOUNTFROM] ASC,
[RECID] ASC,
[FROMDATE] ASC,
[AGREEMENTHEADEREXT_RU] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_ACCOUNTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_ACCOUNTCODE]  DEFAULT ((0)) FOR [ACCOUNTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_ACCOUNTRELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_ACCOUNTRELATION]  DEFAULT ('') FOR [ACCOUNTRELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_AGREEMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_AGREEMENT]  DEFAULT ('') FOR [AGREEMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_AGREEMENTHEADEREXT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_AGREEMENTHEADEREXT_RU]  DEFAULT ((0)) FOR [AGREEMENTHEADEREXT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_ALLOCATEMARKUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_ALLOCATEMARKUP]  DEFAULT ((0)) FOR [ALLOCATEMARKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_AMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_AMOUNT]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_CALENDARDAYS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_CALENDARDAYS]  DEFAULT ((0)) FOR [CALENDARDAYS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_DELIVERYTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_DELIVERYTIME]  DEFAULT ((0)) FOR [DELIVERYTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_FROMDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_FROMDATE]  DEFAULT ('1900-01-01') FOR [FROMDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_GENERICCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_GENERICCURRENCY]  DEFAULT ((0)) FOR [GENERICCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_ITEMCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_ITEMCODE]  DEFAULT ((0)) FOR [ITEMCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_ITEMRELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_ITEMRELATION]  DEFAULT ('') FOR [ITEMRELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_MARKUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_MARKUP]  DEFAULT ((0)) FOR [MARKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_MAXIMUMRETAILPRICE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_MAXIMUMRETAILPRICE_IN]  DEFAULT ((0)) FOR [MAXIMUMRETAILPRICE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_MODULE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_MODULE]  DEFAULT ((0)) FOR [MODULE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_PERCENT1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_PERCENT1]  DEFAULT ((0)) FOR [PERCENT1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_PERCENT2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_PERCENT2]  DEFAULT ((0)) FOR [PERCENT2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_PRICEUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_PRICEUNIT]  DEFAULT ((0)) FOR [PRICEUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_QUANTITYAMOUNTFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_QUANTITYAMOUNTFROM]  DEFAULT ((0)) FOR [QUANTITYAMOUNTFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_QUANTITYAMOUNTTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_QUANTITYAMOUNTTO]  DEFAULT ((0)) FOR [QUANTITYAMOUNTTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_RELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_RELATION]  DEFAULT ((0)) FOR [RELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_SEARCHAGAIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_SEARCHAGAIN]  DEFAULT ((0)) FOR [SEARCHAGAIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_TODATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_TODATE]  DEFAULT ('1900-01-01') FOR [TODATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_UNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_UNITID]  DEFAULT ('') FOR [UNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEDISCTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEDISCTABLE] ADD  CONSTRAINT [DF_PRICEDISCTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[PRICEDISCTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[PRICEPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[PRICEPARAMETERS](
[RECID] [bigint] NOT NULL,
[KEY] [int] NOT NULL,
[PURCHENDACCOUNTALL] [int] NOT NULL,
[PURCHENDALLALL] [int] NOT NULL,
[PURCHENDGROUPALL] [int] NOT NULL,
[PURCHLINEACCOUNTALL] [int] NOT NULL,
[PURCHLINEACCOUNTGROUP] [int] NOT NULL,
[PURCHLINEACCOUNTITEM] [int] NOT NULL,
[PURCHLINEALLALL] [int] NOT NULL,
[PURCHLINEALLGROUP] [int] NOT NULL,
[PURCHLINEALLITEM] [int] NOT NULL,
[PURCHLINEGROUPALL] [int] NOT NULL,
[PURCHLINEGROUPGROUP] [int] NOT NULL,
[PURCHLINEGROUPITEM] [int] NOT NULL,
[PURCHMULTILNACCOUNTALL] [int] NOT NULL,
[PURCHMULTILNACCOUNTGROUP] [int] NOT NULL,
[PURCHMULTILNALLALL] [int] NOT NULL,
[PURCHMULTILNALLGROUP] [int] NOT NULL,
[PURCHMULTILNGROUPALL] [int] NOT NULL,
[PURCHMULTILNGROUPGROUP] [int] NOT NULL,
[PURCHPRICEACCOUNTITEM] [int] NOT NULL,
[PURCHPRICEALLITEM] [int] NOT NULL,
[PURCHPRICEGROUPITEM] [int] NOT NULL,
[SALESENDACCOUNTALL] [int] NOT NULL,
[SALESENDALLALL] [int] NOT NULL,
[SALESENDGROUPALL] [int] NOT NULL,
[SALESLINEACCOUNTALL] [int] NOT NULL,
[SALESLINEACCOUNTGROUP] [int] NOT NULL,
[SALESLINEACCOUNTITEM] [int] NOT NULL,
[SALESLINEALLALL] [int] NOT NULL,
[SALESLINEALLGROUP] [int] NOT NULL,
[SALESLINEALLITEM] [int] NOT NULL,
[SALESLINEGROUPALL] [int] NOT NULL,
[SALESLINEGROUPGROUP] [int] NOT NULL,
[SALESLINEGROUPITEM] [int] NOT NULL,
[SALESMULTILNACCOUNTALL] [int] NOT NULL,
[SALESMULTILNACCOUNTGROUP] [int] NOT NULL,
[SALESMULTILNALLALL] [int] NOT NULL,
[SALESMULTILNALLGROUP] [int] NOT NULL,
[SALESMULTILNGROUPALL] [int] NOT NULL,
[SALESMULTILNGROUPGROUP] [int] NOT NULL,
[SALESPRICEACCOUNTITEM] [int] NOT NULL,
[SALESPRICEALLITEM] [int] NOT NULL,
[SALESPRICEGROUPITEM] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_327828059_-1273337705] PRIMARY KEY CLUSTERED 
(
[KEY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHENDACCOUNTALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHENDACCOUNTALL]  DEFAULT ((0)) FOR [PURCHENDACCOUNTALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHENDALLALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHENDALLALL]  DEFAULT ((0)) FOR [PURCHENDALLALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHENDGROUPALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHENDGROUPALL]  DEFAULT ((0)) FOR [PURCHENDGROUPALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEACCOUNTALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEACCOUNTALL]  DEFAULT ((0)) FOR [PURCHLINEACCOUNTALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEACCOUNTGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEACCOUNTGROUP]  DEFAULT ((0)) FOR [PURCHLINEACCOUNTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEACCOUNTITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEACCOUNTITEM]  DEFAULT ((0)) FOR [PURCHLINEACCOUNTITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEALLALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEALLALL]  DEFAULT ((0)) FOR [PURCHLINEALLALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEALLGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEALLGROUP]  DEFAULT ((0)) FOR [PURCHLINEALLGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEALLITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEALLITEM]  DEFAULT ((0)) FOR [PURCHLINEALLITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEGROUPALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEGROUPALL]  DEFAULT ((0)) FOR [PURCHLINEGROUPALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEGROUPGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEGROUPGROUP]  DEFAULT ((0)) FOR [PURCHLINEGROUPGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHLINEGROUPITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHLINEGROUPITEM]  DEFAULT ((0)) FOR [PURCHLINEGROUPITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHMULTILNACCOUNTALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHMULTILNACCOUNTALL]  DEFAULT ((0)) FOR [PURCHMULTILNACCOUNTALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHMULTILNACCOUNTGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHMULTILNACCOUNTGROUP]  DEFAULT ((0)) FOR [PURCHMULTILNACCOUNTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHMULTILNALLALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHMULTILNALLALL]  DEFAULT ((0)) FOR [PURCHMULTILNALLALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHMULTILNALLGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHMULTILNALLGROUP]  DEFAULT ((0)) FOR [PURCHMULTILNALLGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHMULTILNGROUPALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHMULTILNGROUPALL]  DEFAULT ((0)) FOR [PURCHMULTILNGROUPALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHMULTILNGROUPGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHMULTILNGROUPGROUP]  DEFAULT ((0)) FOR [PURCHMULTILNGROUPGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHPRICEACCOUNTITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHPRICEACCOUNTITEM]  DEFAULT ((0)) FOR [PURCHPRICEACCOUNTITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHPRICEALLITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHPRICEALLITEM]  DEFAULT ((0)) FOR [PURCHPRICEALLITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_PURCHPRICEGROUPITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_PURCHPRICEGROUPITEM]  DEFAULT ((0)) FOR [PURCHPRICEGROUPITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESENDACCOUNTALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESENDACCOUNTALL]  DEFAULT ((0)) FOR [SALESENDACCOUNTALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESENDALLALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESENDALLALL]  DEFAULT ((0)) FOR [SALESENDALLALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESENDGROUPALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESENDGROUPALL]  DEFAULT ((0)) FOR [SALESENDGROUPALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEACCOUNTALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEACCOUNTALL]  DEFAULT ((0)) FOR [SALESLINEACCOUNTALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEACCOUNTGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEACCOUNTGROUP]  DEFAULT ((0)) FOR [SALESLINEACCOUNTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEACCOUNTITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEACCOUNTITEM]  DEFAULT ((0)) FOR [SALESLINEACCOUNTITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEALLALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEALLALL]  DEFAULT ((0)) FOR [SALESLINEALLALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEALLGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEALLGROUP]  DEFAULT ((0)) FOR [SALESLINEALLGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEALLITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEALLITEM]  DEFAULT ((0)) FOR [SALESLINEALLITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEGROUPALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEGROUPALL]  DEFAULT ((0)) FOR [SALESLINEGROUPALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEGROUPGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEGROUPGROUP]  DEFAULT ((0)) FOR [SALESLINEGROUPGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESLINEGROUPITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESLINEGROUPITEM]  DEFAULT ((0)) FOR [SALESLINEGROUPITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESMULTILNACCOUNTALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESMULTILNACCOUNTALL]  DEFAULT ((0)) FOR [SALESMULTILNACCOUNTALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESMULTILNACCOUNTGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESMULTILNACCOUNTGROUP]  DEFAULT ((0)) FOR [SALESMULTILNACCOUNTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESMULTILNALLALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESMULTILNALLALL]  DEFAULT ((0)) FOR [SALESMULTILNALLALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESMULTILNALLGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESMULTILNALLGROUP]  DEFAULT ((0)) FOR [SALESMULTILNALLGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESMULTILNGROUPALL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESMULTILNGROUPALL]  DEFAULT ((0)) FOR [SALESMULTILNGROUPALL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESMULTILNGROUPGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESMULTILNGROUPGROUP]  DEFAULT ((0)) FOR [SALESMULTILNGROUPGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESPRICEACCOUNTITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESPRICEACCOUNTITEM]  DEFAULT ((0)) FOR [SALESPRICEACCOUNTITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESPRICEALLITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESPRICEALLITEM]  DEFAULT ((0)) FOR [SALESPRICEALLITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_PRICEPARAMETERS_SALESPRICEGROUPITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[PRICEPARAMETERS] ADD  CONSTRAINT [DF_PRICEPARAMETERS_SALESPRICEGROUPITEM]  DEFAULT ((0)) FOR [SALESPRICEGROUPITEM]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[PRICEPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILAFFILIATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILAFFILIATION](
[RECID] [bigint] NOT NULL,
[AFFILIATIONTYPE] [int] NOT NULL,
[NAME] [nvarchar](64) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2069845833_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2069845833_-1405435399] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATION_AFFILIATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATION] ADD  CONSTRAINT [DF_RETAILAFFILIATION_AFFILIATIONTYPE]  DEFAULT ((0)) FOR [AFFILIATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATION_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATION] ADD  CONSTRAINT [DF_RETAILAFFILIATION_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILAFFILIATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILAFFILIATIONPRICEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILAFFILIATIONPRICEGROUP](
[RECID] [bigint] NOT NULL,
[PRICEDISCGROUP] [bigint] NOT NULL,
[RETAILAFFILIATION] [bigint] NOT NULL,
[RETAILLOYALTYTIER] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1865738683_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1865738683_869720144] UNIQUE NONCLUSTERED 
(
[RETAILAFFILIATION] ASC,
[PRICEDISCGROUP] ASC,
[RETAILLOYALTYTIER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATIONPRICEGROUP_PRICEDISCGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATIONPRICEGROUP] ADD  CONSTRAINT [DF_RETAILAFFILIATIONPRICEGROUP_PRICEDISCGROUP]  DEFAULT ((0)) FOR [PRICEDISCGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATIONPRICEGROUP_RETAILAFFILIATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATIONPRICEGROUP] ADD  CONSTRAINT [DF_RETAILAFFILIATIONPRICEGROUP_RETAILAFFILIATION]  DEFAULT ((0)) FOR [RETAILAFFILIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATIONPRICEGROUP_RETAILLOYALTYTIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATIONPRICEGROUP] ADD  CONSTRAINT [DF_RETAILAFFILIATIONPRICEGROUP_RETAILLOYALTYTIER]  DEFAULT ((0)) FOR [RETAILLOYALTYTIER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILAFFILIATIONPRICEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILAFFILIATIONTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILAFFILIATIONTRANSLATION](
[RECID] [bigint] NOT NULL,
[AFFILIATION] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1948685724_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1948685724_-1107894182] UNIQUE NONCLUSTERED 
(
[LANGUAGEID] ASC,
[AFFILIATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATIONTRANSLATION_AFFILIATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATIONTRANSLATION] ADD  CONSTRAINT [DF_RETAILAFFILIATIONTRANSLATION_AFFILIATION]  DEFAULT ((0)) FOR [AFFILIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATIONTRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATIONTRANSLATION] ADD  CONSTRAINT [DF_RETAILAFFILIATIONTRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILAFFILIATIONTRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILAFFILIATIONTRANSLATION] ADD  CONSTRAINT [DF_RETAILAFFILIATIONTRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILAFFILIATIONTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILASSORTMENTLOOKUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILASSORTMENTLOOKUP](
[RECID] [bigint] NOT NULL,
[ASSORTMENTID] [bigint] NOT NULL,
[LINETYPE] [int] NOT NULL,
[PRODUCTID] [bigint] NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL,
[VARIANTID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1305966847_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1305966847_-835757873] UNIQUE NONCLUSTERED 
(
[ASSORTMENTID] ASC,
[PRODUCTID] ASC,
[VARIANTID] ASC,
[LINETYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUP_ASSORTMENTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUP_ASSORTMENTID]  DEFAULT ((0)) FOR [ASSORTMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUP_LINETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUP_LINETYPE]  DEFAULT ((0)) FOR [LINETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUP_PRODUCTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUP_PRODUCTID]  DEFAULT ((0)) FOR [PRODUCTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUP_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUP_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUP_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUP_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUP_VARIANTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUP_VARIANTID]  DEFAULT ((0)) FOR [VARIANTID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILASSORTMENTLOOKUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILASSORTMENTLOOKUPCHANNELGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILASSORTMENTLOOKUPCHANNELGROUP](
[RECID] [bigint] NOT NULL,
[ASSORTMENTID] [bigint] NOT NULL,
[OMOPERATINGUNITID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-789342849_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-789342849_-1871154347] UNIQUE NONCLUSTERED 
(
[OMOPERATINGUNITID] ASC,
[ASSORTMENTID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUPCHANNELGROUP_ASSORTMENTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUPCHANNELGROUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUPCHANNELGROUP_ASSORTMENTID]  DEFAULT ((0)) FOR [ASSORTMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILASSORTMENTLOOKUPCHANNELGROUP_OMOPERATINGUNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILASSORTMENTLOOKUPCHANNELGROUP] ADD  CONSTRAINT [DF_RETAILASSORTMENTLOOKUPCHANNELGROUP_OMOPERATINGUNITID]  DEFAULT ((0)) FOR [OMOPERATINGUNITID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILASSORTMENTLOOKUPCHANNELGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILBARCODEMASKCHARACTER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILBARCODEMASKCHARACTER](
[RECID] [bigint] NOT NULL,
[CHARACTER] [nchar](1) NOT NULL,
[CHARACTERTYPE] [int] NOT NULL,
[COMMENT] [nvarchar](50) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-962323594_50008756] PRIMARY KEY CLUSTERED 
(
[CHARACTERTYPE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-962323594_259853196] UNIQUE NONCLUSTERED 
(
[CHARACTER] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKCHARACTER_CHARACTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKCHARACTER] ADD  CONSTRAINT [DF_RETAILBARCODEMASKCHARACTER_CHARACTER]  DEFAULT ('') FOR [CHARACTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKCHARACTER_CHARACTERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKCHARACTER] ADD  CONSTRAINT [DF_RETAILBARCODEMASKCHARACTER_CHARACTERTYPE]  DEFAULT ((0)) FOR [CHARACTERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKCHARACTER_COMMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKCHARACTER] ADD  CONSTRAINT [DF_RETAILBARCODEMASKCHARACTER_COMMENT]  DEFAULT ('') FOR [COMMENT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILBARCODEMASKCHARACTER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILBARCODEMASKSEGMENT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILBARCODEMASKSEGMENT](
[RECID] [bigint] NOT NULL,
[CHAR] [nchar](1) NOT NULL,
[DECIMALS] [int] NOT NULL,
[LENGTH] [numeric](32, 16) NOT NULL,
[MASKID] [nvarchar](10) NOT NULL,
[SEGMENTNUM] [int] NOT NULL,
[TYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1809797708_-615227758] PRIMARY KEY CLUSTERED 
(
[MASKID] ASC,
[SEGMENTNUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKSEGMENT_CHAR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKSEGMENT] ADD  CONSTRAINT [DF_RETAILBARCODEMASKSEGMENT_CHAR]  DEFAULT ('') FOR [CHAR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKSEGMENT_DECIMALS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKSEGMENT] ADD  CONSTRAINT [DF_RETAILBARCODEMASKSEGMENT_DECIMALS]  DEFAULT ((0)) FOR [DECIMALS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKSEGMENT_LENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKSEGMENT] ADD  CONSTRAINT [DF_RETAILBARCODEMASKSEGMENT_LENGTH]  DEFAULT ((0)) FOR [LENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKSEGMENT_MASKID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKSEGMENT] ADD  CONSTRAINT [DF_RETAILBARCODEMASKSEGMENT_MASKID]  DEFAULT ('') FOR [MASKID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKSEGMENT_SEGMENTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKSEGMENT] ADD  CONSTRAINT [DF_RETAILBARCODEMASKSEGMENT_SEGMENTNUM]  DEFAULT ((0)) FOR [SEGMENTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKSEGMENT_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKSEGMENT] ADD  CONSTRAINT [DF_RETAILBARCODEMASKSEGMENT_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILBARCODEMASKSEGMENT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILBARCODEMASKTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILBARCODEMASKTABLE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](50) NOT NULL,
[MASK] [nvarchar](80) NOT NULL,
[MASKID] [nvarchar](10) NOT NULL,
[PREFIX] [nvarchar](22) NOT NULL,
[SYMBOLOGY] [int] NOT NULL,
[TYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_614044725_-483433874] PRIMARY KEY CLUSTERED 
(
[MASKID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_614044725_1444299457] UNIQUE NONCLUSTERED 
(
[MASK] ASC,
[TYPE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKTABLE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKTABLE] ADD  CONSTRAINT [DF_RETAILBARCODEMASKTABLE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKTABLE_MASK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKTABLE] ADD  CONSTRAINT [DF_RETAILBARCODEMASKTABLE_MASK]  DEFAULT ('') FOR [MASK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKTABLE_MASKID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKTABLE] ADD  CONSTRAINT [DF_RETAILBARCODEMASKTABLE_MASKID]  DEFAULT ('') FOR [MASKID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKTABLE_PREFIX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKTABLE] ADD  CONSTRAINT [DF_RETAILBARCODEMASKTABLE_PREFIX]  DEFAULT ('') FOR [PREFIX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKTABLE_SYMBOLOGY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKTABLE] ADD  CONSTRAINT [DF_RETAILBARCODEMASKTABLE_SYMBOLOGY]  DEFAULT ((0)) FOR [SYMBOLOGY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBARCODEMASKTABLE_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBARCODEMASKTABLE] ADD  CONSTRAINT [DF_RETAILBARCODEMASKTABLE_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILBARCODEMASKTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILBUTTONGRID]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILBUTTONGRID](
[RECID] [bigint] NOT NULL,
[BUTTONGRIDID] [nvarchar](10) NOT NULL,
[DEFAULTCOLOR] [int] NOT NULL,
[DEFAULTFONTSIZE] [int] NOT NULL,
[DEFAULTFONTSTYLE] [int] NOT NULL,
[FONT] [nvarchar](32) NOT NULL,
[KEYBOARDUSED] [nvarchar](10) NOT NULL,
[NAME] [nvarchar](50) NOT NULL,
[SPACEBETWEENBUTTONS] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-984773215_189016630] PRIMARY KEY CLUSTERED 
(
[BUTTONGRIDID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_BUTTONGRIDID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_BUTTONGRIDID]  DEFAULT ('') FOR [BUTTONGRIDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_DEFAULTCOLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_DEFAULTCOLOR]  DEFAULT ((0)) FOR [DEFAULTCOLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_DEFAULTFONTSIZE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_DEFAULTFONTSIZE]  DEFAULT ((0)) FOR [DEFAULTFONTSIZE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_DEFAULTFONTSTYLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_DEFAULTFONTSTYLE]  DEFAULT ((0)) FOR [DEFAULTFONTSTYLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_FONT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_FONT]  DEFAULT ('') FOR [FONT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_KEYBOARDUSED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_KEYBOARDUSED]  DEFAULT ('') FOR [KEYBOARDUSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRID_SPACEBETWEENBUTTONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRID] ADD  CONSTRAINT [DF_RETAILBUTTONGRID_SPACEBETWEENBUTTONS]  DEFAULT ((0)) FOR [SPACEBETWEENBUTTONS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILBUTTONGRID] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILBUTTONGRIDBUTTONS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILBUTTONGRIDBUTTONS](
[RECID] [bigint] NOT NULL,
[ACTION] [int] NOT NULL,
[ACTIONPROPERTY] [nvarchar](1000) NOT NULL,
[BACKCOLOR] [int] NOT NULL,
[BACKCOLOR2] [int] NOT NULL,
[BORDERCOLOR] [int] NOT NULL,
[BUTTONGRIDID] [nvarchar](10) NOT NULL,
[COL] [int] NOT NULL,
[COLOUR] [int] NOT NULL,
[COLSPAN] [int] NOT NULL,
[DISPLAYTEXT] [nvarchar](50) NOT NULL,
[FONTCOLOR] [int] NOT NULL,
[FONTSIZE] [int] NOT NULL,
[FONTSTYLE] [int] NOT NULL,
[GRADIENTMODE] [int] NOT NULL,
[ID] [int] NOT NULL,
[IMAGEALIGNMENT] [int] NOT NULL,
[NEWIMAGEALIGNMENT] [int] NOT NULL,
[NEWTEXTALIGNMENT] [int] NOT NULL,
[PICTUREID] [int] NOT NULL,
[ROWNUM] [int] NOT NULL,
[ROWSPAN] [int] NOT NULL,
[USECUSTOMLOOKANDFEEL] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2770370_-1012477802] PRIMARY KEY CLUSTERED 
(
[ID] ASC,
[BUTTONGRIDID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_ACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_ACTION]  DEFAULT ((0)) FOR [ACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_ACTIONPROPERTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_ACTIONPROPERTY]  DEFAULT ('') FOR [ACTIONPROPERTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_BACKCOLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_BACKCOLOR]  DEFAULT ((0)) FOR [BACKCOLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_BACKCOLOR2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_BACKCOLOR2]  DEFAULT ((0)) FOR [BACKCOLOR2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_BORDERCOLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_BORDERCOLOR]  DEFAULT ((0)) FOR [BORDERCOLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_BUTTONGRIDID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_BUTTONGRIDID]  DEFAULT ('') FOR [BUTTONGRIDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_COL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_COL]  DEFAULT ((0)) FOR [COL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_COLOUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_COLOUR]  DEFAULT ((0)) FOR [COLOUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_COLSPAN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_COLSPAN]  DEFAULT ((0)) FOR [COLSPAN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_DISPLAYTEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_DISPLAYTEXT]  DEFAULT ('') FOR [DISPLAYTEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_FONTCOLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_FONTCOLOR]  DEFAULT ((0)) FOR [FONTCOLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_FONTSIZE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_FONTSIZE]  DEFAULT ((0)) FOR [FONTSIZE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_FONTSTYLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_FONTSTYLE]  DEFAULT ((0)) FOR [FONTSTYLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_GRADIENTMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_GRADIENTMODE]  DEFAULT ((0)) FOR [GRADIENTMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_ID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_ID]  DEFAULT ((0)) FOR [ID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_IMAGEALIGNMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_IMAGEALIGNMENT]  DEFAULT ((0)) FOR [IMAGEALIGNMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_NEWIMAGEALIGNMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_NEWIMAGEALIGNMENT]  DEFAULT ((0)) FOR [NEWIMAGEALIGNMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_NEWTEXTALIGNMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_NEWTEXTALIGNMENT]  DEFAULT ((0)) FOR [NEWTEXTALIGNMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_PICTUREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_PICTUREID]  DEFAULT ((0)) FOR [PICTUREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_ROWNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_ROWNUM]  DEFAULT ((0)) FOR [ROWNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_ROWSPAN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_ROWSPAN]  DEFAULT ((0)) FOR [ROWSPAN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILBUTTONGRIDBUTTONS_USECUSTOMLOOKANDFEEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILBUTTONGRIDBUTTONS] ADD  CONSTRAINT [DF_RETAILBUTTONGRIDBUTTONS_USECUSTOMLOOKANDFEEL]  DEFAULT ((0)) FOR [USECUSTOMLOOKANDFEEL]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILBUTTONGRIDBUTTONS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCATEGORYCONTAINMENTLOOKUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCATEGORYCONTAINMENTLOOKUP](
[RECID] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[CONTAINEDCATEGORY] [bigint] NOT NULL,
[ISDIRTY] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_729336743_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_729336743_496772623] UNIQUE NONCLUSTERED 
(
[CATEGORY] ASC,
[CONTAINEDCATEGORY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCATEGORYCONTAINMENTLOOKUP_CONTAINEDCATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILCATEGORYCONTAINMENTLOOKUP_CONTAINEDCATEGORY]  DEFAULT ((0)) FOR [CONTAINEDCATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCATEGORYCONTAINMENTLOOKUP_ISDIRTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] ADD  CONSTRAINT [DF_RETAILCATEGORYCONTAINMENTLOOKUP_ISDIRTY]  DEFAULT ((0)) FOR [ISDIRTY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCDXDATASTORECHANNEL]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCDXDATASTORECHANNEL](
[RECID] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[DATABASEPROFILE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_477722470_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_477722470_813932609] UNIQUE NONCLUSTERED 
(
[CHANNEL] ASC,
[DATABASEPROFILE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCDXDATASTORECHANNEL_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCDXDATASTORECHANNEL] ADD  CONSTRAINT [DF_RETAILCDXDATASTORECHANNEL_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCDXDATASTORECHANNEL_DATABASEPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCDXDATASTORECHANNEL] ADD  CONSTRAINT [DF_RETAILCDXDATASTORECHANNEL_DATABASEPROFILE]  DEFAULT ((0)) FOR [DATABASEPROFILE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCDXDATASTORECHANNEL] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELCURRENCY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELCURRENCY](
[RECID] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_114831543_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_114831543_1078512529] UNIQUE NONCLUSTERED 
(
[CHANNEL] ASC,
[CURRENCYCODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELCURRENCY_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELCURRENCY] ADD  CONSTRAINT [DF_RETAILCHANNELCURRENCY_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELCURRENCY_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELCURRENCY] ADD  CONSTRAINT [DF_RETAILCHANNELCURRENCY_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELCURRENCY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELPAYMENTCONNECTORLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELPAYMENTCONNECTORLINE](
[RECID] [bigint] NOT NULL,
[ONLINECHANNEL] [bigint] NOT NULL,
[PAYMENTCONNECTORNAME] [nvarchar](50) NOT NULL,
[PAYMENTCONNECTORPROPERTIES] [nvarchar](max) NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1982148519_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPAYMENTCONNECTORLINE_ONLINECHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPAYMENTCONNECTORLINE] ADD  CONSTRAINT [DF_RETAILCHANNELPAYMENTCONNECTORLINE_ONLINECHANNEL]  DEFAULT ((0)) FOR [ONLINECHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPAYMENTCONNECTORLINE_PAYMENTCONNECTORNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPAYMENTCONNECTORLINE] ADD  CONSTRAINT [DF_RETAILCHANNELPAYMENTCONNECTORLINE_PAYMENTCONNECTORNAME]  DEFAULT ('') FOR [PAYMENTCONNECTORNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPAYMENTCONNECTORLINE_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPAYMENTCONNECTORLINE] ADD  CONSTRAINT [DF_RETAILCHANNELPAYMENTCONNECTORLINE_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPAYMENTCONNECTORLINE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPAYMENTCONNECTORLINE] ADD  CONSTRAINT [DF_RETAILCHANNELPAYMENTCONNECTORLINE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELPAYMENTCONNECTORLINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELPRICEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELPRICEGROUP](
[RECID] [bigint] NOT NULL,
[PRICEGROUP] [bigint] NOT NULL,
[RETAILCHANNEL] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-639419124_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-639419124_-99939092] UNIQUE NONCLUSTERED 
(
[RETAILCHANNEL] ASC,
[PRICEGROUP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPRICEGROUP_PRICEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPRICEGROUP] ADD  CONSTRAINT [DF_RETAILCHANNELPRICEGROUP_PRICEGROUP]  DEFAULT ((0)) FOR [PRICEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPRICEGROUP_RETAILCHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPRICEGROUP] ADD  CONSTRAINT [DF_RETAILCHANNELPRICEGROUP_RETAILCHANNEL]  DEFAULT ((0)) FOR [RETAILCHANNEL]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELPRICEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELPROFILE](
[RECID] [bigint] NOT NULL,
[CHANNELPROFILETYPE] [int] NOT NULL,
[NAME] [nvarchar](50) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-384404477_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-384404477_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPROFILE_CHANNELPROFILETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPROFILE] ADD  CONSTRAINT [DF_RETAILCHANNELPROFILE_CHANNELPROFILETYPE]  DEFAULT ((0)) FOR [CHANNELPROFILETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPROFILE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPROFILE] ADD  CONSTRAINT [DF_RETAILCHANNELPROFILE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELPROFILEPROPERTY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELPROFILEPROPERTY](
[RECID] [bigint] NOT NULL,
[CHANNELPROFILE] [bigint] NOT NULL,
[KEY] [int] NOT NULL,
[VALUE] [nvarchar](1023) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-940211552_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPROFILEPROPERTY_CHANNELPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPROFILEPROPERTY] ADD  CONSTRAINT [DF_RETAILCHANNELPROFILEPROPERTY_CHANNELPROFILE]  DEFAULT ((0)) FOR [CHANNELPROFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPROFILEPROPERTY_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPROFILEPROPERTY] ADD  CONSTRAINT [DF_RETAILCHANNELPROFILEPROPERTY_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELPROFILEPROPERTY_VALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELPROFILEPROPERTY] ADD  CONSTRAINT [DF_RETAILCHANNELPROFILEPROPERTY_VALUE]  DEFAULT ('') FOR [VALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELPROFILEPROPERTY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELREPORT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELREPORT](
[RECID] [bigint] NOT NULL,
[REPORTDEFINITIONXML] [nvarchar](max) NULL,
[REPORTID] [nvarchar](100) NOT NULL,
[REPORTNAME] [nvarchar](400) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1169491562_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1169491562_-253282476] UNIQUE NONCLUSTERED 
(
[REPORTID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELREPORT_REPORTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELREPORT] ADD  CONSTRAINT [DF_RETAILCHANNELREPORT_REPORTID]  DEFAULT ('') FOR [REPORTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELREPORT_REPORTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELREPORT] ADD  CONSTRAINT [DF_RETAILCHANNELREPORT_REPORTNAME]  DEFAULT ('') FOR [REPORTNAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELREPORT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELTABLE](
[RECID] [bigint] NOT NULL,
[CHANNELTIMEZONEINFOID] [nvarchar](60) NOT NULL,
[CHANNELTYPE] [int] NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[DEFAULTCUSTACCOUNT] [nvarchar](20) NOT NULL,
[DEFAULTCUSTDATAAREAID] [nvarchar](4) NOT NULL,
[EVENTNOTIFICATIONPROFILEID] [nvarchar](20) NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[INVENTLOCATION] [nvarchar](10) NOT NULL,
[INVENTLOCATIONDATAAREAID] [nvarchar](4) NOT NULL,
[OMOPERATINGUNITID] [bigint] NOT NULL,
[PRICEINCLUDESSALESTAX] [int] NOT NULL,
[TRANSACTIONSERVICEPROFILE] [nvarchar](10) NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-922331912_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-922331912_-1636812754] UNIQUE NONCLUSTERED 
(
[OMOPERATINGUNITID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_CHANNELTIMEZONEINFOID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_CHANNELTIMEZONEINFOID]  DEFAULT ('') FOR [CHANNELTIMEZONEINFOID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_CHANNELTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_CHANNELTYPE]  DEFAULT ((0)) FOR [CHANNELTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_DEFAULTCUSTACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_DEFAULTCUSTACCOUNT]  DEFAULT ('') FOR [DEFAULTCUSTACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_DEFAULTCUSTDATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_DEFAULTCUSTDATAAREAID]  DEFAULT ('') FOR [DEFAULTCUSTDATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_EVENTNOTIFICATIONPROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_EVENTNOTIFICATIONPROFILEID]  DEFAULT ('') FOR [EVENTNOTIFICATIONPROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_INVENTLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_INVENTLOCATION]  DEFAULT ('') FOR [INVENTLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_INVENTLOCATIONDATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_INVENTLOCATIONDATAAREAID]  DEFAULT ('') FOR [INVENTLOCATIONDATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_OMOPERATINGUNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_OMOPERATINGUNITID]  DEFAULT ((0)) FOR [OMOPERATINGUNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_PRICEINCLUDESSALESTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_PRICEINCLUDESSALESTAX]  DEFAULT ((0)) FOR [PRICEINCLUDESSALESTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLE_TRANSACTIONSERVICEPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILCHANNELTABLE_TRANSACTIONSERVICEPROFILE]  DEFAULT ('') FOR [TRANSACTIONSERVICEPROFILE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCHANNELTABLEEXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCHANNELTABLEEXT](
[RECID] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CHANNELPROFILE] [bigint] NOT NULL,
[LIVECHANNELDATABASE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1313859313_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1313859313_69820500] UNIQUE NONCLUSTERED 
(
[CHANNEL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLEEXT_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLEEXT] ADD  CONSTRAINT [DF_RETAILCHANNELTABLEEXT_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLEEXT_CHANNELPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLEEXT] ADD  CONSTRAINT [DF_RETAILCHANNELTABLEEXT_CHANNELPROFILE]  DEFAULT ((0)) FOR [CHANNELPROFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCHANNELTABLEEXT_LIVECHANNELDATABASE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCHANNELTABLEEXT] ADD  CONSTRAINT [DF_RETAILCHANNELTABLEEXT_LIVECHANNELDATABASE]  DEFAULT ((0)) FOR [LIVECHANNELDATABASE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCHANNELTABLEEXT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCONFIGURATION_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCONFIGURATION_BR](
[RECID] [bigint] NOT NULL,
[PURPOSE] [int] NOT NULL,
[TYPE] [int] NOT NULL,
[VALUE] [nvarchar](20) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1461688190_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONFIGURATION_BR_PURPOSE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONFIGURATION_BR] ADD  CONSTRAINT [DF_RETAILCONFIGURATION_BR_PURPOSE]  DEFAULT ((0)) FOR [PURPOSE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONFIGURATION_BR_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONFIGURATION_BR] ADD  CONSTRAINT [DF_RETAILCONFIGURATION_BR_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONFIGURATION_BR_VALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONFIGURATION_BR] ADD  CONSTRAINT [DF_RETAILCONFIGURATION_BR_VALUE]  DEFAULT ('') FOR [VALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCONFIGURATION_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCONFIGURATIONSTORETABLE_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCONFIGURATIONSTORETABLE_BR](
[RECID] [bigint] NOT NULL,
[RETAILCONFIGURATION_BR] [bigint] NOT NULL,
[RETAILSTORETABLE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-180636695_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-180636695_586140477] UNIQUE NONCLUSTERED 
(
[RETAILCONFIGURATION_BR] ASC,
[RETAILSTORETABLE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONFIGURATIONSTORETABLE_BR_RETAILCONFIGURATION_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONFIGURATIONSTORETABLE_BR] ADD  CONSTRAINT [DF_RETAILCONFIGURATIONSTORETABLE_BR_RETAILCONFIGURATION_BR]  DEFAULT ((0)) FOR [RETAILCONFIGURATION_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONFIGURATIONSTORETABLE_BR_RETAILSTORETABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONFIGURATIONSTORETABLE_BR] ADD  CONSTRAINT [DF_RETAILCONFIGURATIONSTORETABLE_BR_RETAILSTORETABLE]  DEFAULT ((0)) FOR [RETAILSTORETABLE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCONFIGURATIONSTORETABLE_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCONNDATABASEPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCONNDATABASEPROFILE](
[RECID] [bigint] NOT NULL,
[DATABASE] [nvarchar](128) NOT NULL,
[NAME] [nvarchar](50) NOT NULL,
[SERVER] [nvarchar](256) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1554329957_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1554329957_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONNDATABASEPROFILE_DATABASE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONNDATABASEPROFILE] ADD  CONSTRAINT [DF_RETAILCONNDATABASEPROFILE_DATABASE]  DEFAULT ('') FOR [DATABASE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONNDATABASEPROFILE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONNDATABASEPROFILE] ADD  CONSTRAINT [DF_RETAILCONNDATABASEPROFILE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCONNDATABASEPROFILE_SERVER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCONNDATABASEPROFILE] ADD  CONSTRAINT [DF_RETAILCONNDATABASEPROFILE_SERVER]  DEFAULT ('') FOR [SERVER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCONNDATABASEPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCUSTAFFILIATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCUSTAFFILIATION](
[RECID] [bigint] NOT NULL,
[CUSTACCOUNTNUM] [nvarchar](20) NOT NULL,
[RETAILAFFILIATIONID] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1682217268_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1682217268_1544434852] UNIQUE NONCLUSTERED 
(
[CUSTACCOUNTNUM] ASC,
[RETAILAFFILIATIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTAFFILIATION_CUSTACCOUNTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTAFFILIATION] ADD  CONSTRAINT [DF_RETAILCUSTAFFILIATION_CUSTACCOUNTNUM]  DEFAULT ('') FOR [CUSTACCOUNTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTAFFILIATION_RETAILAFFILIATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTAFFILIATION] ADD  CONSTRAINT [DF_RETAILCUSTAFFILIATION_RETAILAFFILIATIONID]  DEFAULT ((0)) FOR [RETAILAFFILIATIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCUSTAFFILIATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILCUSTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILCUSTTABLE](
[RECID] [bigint] NOT NULL,
[ACCOUNTNUM] [nvarchar](20) NOT NULL,
[IMAGE] [nvarchar](1999) NOT NULL,
[NONCHARGABLEACCOUNT] [int] NOT NULL,
[POSTASSHIPMENT] [int] NOT NULL,
[RECEIPTEMAIL] [nvarchar](80) NOT NULL,
[RECEIPTOPTION] [int] NOT NULL,
[REQUIRESAPPROVAL] [int] NOT NULL,
[USEORDERNUMBERREFERENCE] [int] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-344762130_-2129881424] PRIMARY KEY CLUSTERED 
(
[ACCOUNTNUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_ACCOUNTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_ACCOUNTNUM]  DEFAULT ('') FOR [ACCOUNTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_IMAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_IMAGE]  DEFAULT ('') FOR [IMAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_NONCHARGABLEACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_NONCHARGABLEACCOUNT]  DEFAULT ((0)) FOR [NONCHARGABLEACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_POSTASSHIPMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_POSTASSHIPMENT]  DEFAULT ((0)) FOR [POSTASSHIPMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_RECEIPTEMAIL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_RECEIPTEMAIL]  DEFAULT ('') FOR [RECEIPTEMAIL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_RECEIPTOPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_RECEIPTOPTION]  DEFAULT ((0)) FOR [RECEIPTOPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_REQUIRESAPPROVAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_REQUIRESAPPROVAL]  DEFAULT ((0)) FOR [REQUIRESAPPROVAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_USEORDERNUMBERREFERENCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_USEORDERNUMBERREFERENCE]  DEFAULT ((0)) FOR [USEORDERNUMBERREFERENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILCUSTTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILCUSTTABLE] ADD  CONSTRAINT [DF_RETAILCUSTTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILCUSTTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDEVICE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDEVICE](
[RECID] [bigint] NOT NULL,
[ACTIVATEDDATETIME] [datetime] NOT NULL,
[ACTIVATEDDATETIMETZID] [int] NOT NULL,
[ACTIVATIONSTATUS] [int] NOT NULL,
[DEACTIVATECOMMENTS] [nvarchar](256) NOT NULL,
[DEACTIVATEDDATETIME] [datetime] NOT NULL,
[DEACTIVATEDDATETIMETZID] [int] NOT NULL,
[DESCRIPTION] [nvarchar](50) NOT NULL,
[DEVICEID] [nvarchar](64) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TYPE] [bigint] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1029059569_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1029059569_-34442163] UNIQUE NONCLUSTERED 
(
[DEVICEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_ACTIVATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_ACTIVATEDDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [ACTIVATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_ACTIVATEDDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_ACTIVATEDDATETIMETZID]  DEFAULT ((37001)) FOR [ACTIVATEDDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_ACTIVATIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_ACTIVATIONSTATUS]  DEFAULT ((0)) FOR [ACTIVATIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_DEACTIVATECOMMENTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_DEACTIVATECOMMENTS]  DEFAULT ('') FOR [DEACTIVATECOMMENTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_DEACTIVATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_DEACTIVATEDDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DEACTIVATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_DEACTIVATEDDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_DEACTIVATEDDATETIMETZID]  DEFAULT ((37001)) FOR [DEACTIVATEDDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_DEVICEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_DEVICEID]  DEFAULT ('') FOR [DEVICEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICE] ADD  CONSTRAINT [DF_RETAILDEVICE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDEVICE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDEVICETYPES]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDEVICETYPES](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[DESIGNERFORM] [int] NOT NULL,
[TYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2081582748_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2081582748_648562881] UNIQUE NONCLUSTERED 
(
[TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICETYPES_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICETYPES] ADD  CONSTRAINT [DF_RETAILDEVICETYPES_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICETYPES_DESIGNERFORM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICETYPES] ADD  CONSTRAINT [DF_RETAILDEVICETYPES_DESIGNERFORM]  DEFAULT ((0)) FOR [DESIGNERFORM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDEVICETYPES_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDEVICETYPES] ADD  CONSTRAINT [DF_RETAILDEVICETYPES_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDEVICETYPES] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTCODE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTCODE](
[RECID] [bigint] NOT NULL,
[BARCODE] [nvarchar](80) NOT NULL,
[DISCOUNTCODE] [nvarchar](15) NOT NULL,
[DISCOUNTOFFERID] [nvarchar](20) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1508518185_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1508518185_626142578] UNIQUE NONCLUSTERED 
(
[DISCOUNTCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTCODE_BARCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTCODE] ADD  CONSTRAINT [DF_RETAILDISCOUNTCODE_BARCODE]  DEFAULT ('') FOR [BARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTCODE_DISCOUNTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTCODE] ADD  CONSTRAINT [DF_RETAILDISCOUNTCODE_DISCOUNTCODE]  DEFAULT ('') FOR [DISCOUNTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTCODE_DISCOUNTOFFERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTCODE] ADD  CONSTRAINT [DF_RETAILDISCOUNTCODE_DISCOUNTOFFERID]  DEFAULT ('') FOR [DISCOUNTOFFERID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTCODE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTLINEMIXANDMATCH]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTLINEMIXANDMATCH](
[RECID] [bigint] NOT NULL,
[DISCOUNTTYPE] [int] NULL,
[LINEGROUP] [nvarchar](10) NULL,
[NUMBEROFITEMSNEEDED] [int] NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1305177448_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTLINEMIXANDMATCH] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTLINEMULTIBUY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTLINEMULTIBUY](
[RECID] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1725387923_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTLINEMULTIBUY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTLINEOFFER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTLINEOFFER](
[RECID] [bigint] NOT NULL,
[DISCAMOUNT] [numeric](32, 16) NULL,
[DISCOUNTMETHOD] [int] NULL,
[DISCPCT] [numeric](32, 16) NULL,
[OFFERPRICE] [numeric](32, 16) NULL,
[OFFERPRICEINCLTAX] [numeric](32, 16) NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1716167346_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTLINEOFFER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTMIXANDMATCH]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTMIXANDMATCH](
[RECID] [bigint] NOT NULL,
[DEALPRICEVALUE] [numeric](32, 16) NULL,
[DISCOUNTAMOUNTVALUE] [numeric](32, 16) NULL,
[MIXANDMATCHDISCOUNTTYPE] [int] NULL,
[NOOFLEASTEXPENSIVELINES] [int] NULL,
[NUMBEROFTIMESAPPLICABLE] [int] NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1039421858_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTMIXANDMATCH] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTMULTIBUY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTMULTIBUY](
[RECID] [bigint] NOT NULL,
[MULTIBUYDISCOUNTTYPE] [int] NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1945564883_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTMULTIBUY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTOFFER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTOFFER](
[RECID] [bigint] NOT NULL,
[DISCONPOS] [int] NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_926028480_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTOFFER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTPRICEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTPRICEGROUP](
[RECID] [bigint] NOT NULL,
[OFFERID] [nvarchar](20) NOT NULL,
[PRICEDISCGROUP] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-755294702_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-755294702_1520629562] UNIQUE NONCLUSTERED 
(
[OFFERID] ASC,
[PRICEDISCGROUP] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTPRICEGROUP_OFFERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTPRICEGROUP] ADD  CONSTRAINT [DF_RETAILDISCOUNTPRICEGROUP_OFFERID]  DEFAULT ('') FOR [OFFERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTPRICEGROUP_PRICEDISCGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTPRICEGROUP] ADD  CONSTRAINT [DF_RETAILDISCOUNTPRICEGROUP_PRICEDISCGROUP]  DEFAULT ((0)) FOR [PRICEDISCGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTPRICEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTTHRESHOLD]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTTHRESHOLD](
[RECID] [bigint] NOT NULL,
[COUNTNONDISCOUNTITEMS] [int] NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-363700915_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTTHRESHOLD] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTTHRESHOLDTIERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTTHRESHOLDTIERS](
[RECID] [bigint] NOT NULL,
[AMOUNTTHRESHOLD] [numeric](32, 16) NOT NULL,
[DISCOUNTMETHOD] [int] NOT NULL,
[DISCOUNTVALUE] [numeric](32, 16) NOT NULL,
[OFFERID] [nvarchar](20) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1862032774_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTTHRESHOLDTIERS_AMOUNTTHRESHOLD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTTHRESHOLDTIERS] ADD  CONSTRAINT [DF_RETAILDISCOUNTTHRESHOLDTIERS_AMOUNTTHRESHOLD]  DEFAULT ((0)) FOR [AMOUNTTHRESHOLD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTTHRESHOLDTIERS_DISCOUNTMETHOD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTTHRESHOLDTIERS] ADD  CONSTRAINT [DF_RETAILDISCOUNTTHRESHOLDTIERS_DISCOUNTMETHOD]  DEFAULT ((0)) FOR [DISCOUNTMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTTHRESHOLDTIERS_DISCOUNTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTTHRESHOLDTIERS] ADD  CONSTRAINT [DF_RETAILDISCOUNTTHRESHOLDTIERS_DISCOUNTVALUE]  DEFAULT ((0)) FOR [DISCOUNTVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTTHRESHOLDTIERS_OFFERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTTHRESHOLDTIERS] ADD  CONSTRAINT [DF_RETAILDISCOUNTTHRESHOLDTIERS_OFFERID]  DEFAULT ('') FOR [OFFERID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTTHRESHOLDTIERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDISCOUNTVALIDATIONPERIOD]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD](
[RECID] [bigint] NOT NULL,
[ENDINGTIME] [int] NOT NULL,
[ENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[FRIDAYENDINGTIME] [int] NOT NULL,
[FRIDAYENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[FRIDAYSTARTINGTIME] [int] NOT NULL,
[FRIDAYTIMEWITHINBOUNDS] [int] NOT NULL,
[MONDAYENDINGTIME] [int] NOT NULL,
[MONDAYENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[MONDAYSTARTINGTIME] [int] NOT NULL,
[MONDAYTIMEWITHINBOUNDS] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PERIODID] [nvarchar](10) NOT NULL,
[SATURDAYENDINGTIME] [int] NOT NULL,
[SATURDAYENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[SATURDAYSTARTINGTIME] [int] NOT NULL,
[SATURDAYTIMEWITHINBOUNDS] [int] NOT NULL,
[STARTINGTIME] [int] NOT NULL,
[SUNDAYENDINGTIME] [int] NOT NULL,
[SUNDAYENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[SUNDAYSTARTINGTIME] [int] NOT NULL,
[SUNDAYTIMEWITHINBOUNDS] [int] NOT NULL,
[THUESDAYENDINGTIME] [int] NOT NULL,
[THUESDAYENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[THUESDAYSTARTINGTIME] [int] NOT NULL,
[THUESDAYTIMEWITHINBOUNDS] [int] NOT NULL,
[THURSDAYENDINGTIME] [int] NOT NULL,
[THURSDAYENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[THURSDAYSTARTINGTIME] [int] NOT NULL,
[THURSDAYTIMEWITHINBOUNDS] [int] NOT NULL,
[TIMEWITHINBOUNDS] [int] NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL,
[WEDNESDAYENDINGTIME] [int] NOT NULL,
[WEDNESDAYENDINGTIMEAFTERMIDNIGHT] [int] NOT NULL,
[WEDNESDAYSTARTINGTIME] [int] NOT NULL,
[WEDNESDAYTIMEWITHINBOUNDS] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1032774252_-1360894778] PRIMARY KEY CLUSTERED 
(
[PERIODID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_ENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_ENDINGTIME]  DEFAULT ((0)) FOR [ENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_ENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_ENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [ENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYENDINGTIME]  DEFAULT ((0)) FOR [FRIDAYENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [FRIDAYENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYSTARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYSTARTINGTIME]  DEFAULT ((0)) FOR [FRIDAYSTARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYTIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_FRIDAYTIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [FRIDAYTIMEWITHINBOUNDS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYENDINGTIME]  DEFAULT ((0)) FOR [MONDAYENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [MONDAYENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYSTARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYSTARTINGTIME]  DEFAULT ((0)) FOR [MONDAYSTARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYTIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_MONDAYTIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [MONDAYTIMEWITHINBOUNDS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_PERIODID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_PERIODID]  DEFAULT ('') FOR [PERIODID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYENDINGTIME]  DEFAULT ((0)) FOR [SATURDAYENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [SATURDAYENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYSTARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYSTARTINGTIME]  DEFAULT ((0)) FOR [SATURDAYSTARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYTIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SATURDAYTIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [SATURDAYTIMEWITHINBOUNDS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_STARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_STARTINGTIME]  DEFAULT ((0)) FOR [STARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYENDINGTIME]  DEFAULT ((0)) FOR [SUNDAYENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [SUNDAYENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYSTARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYSTARTINGTIME]  DEFAULT ((0)) FOR [SUNDAYSTARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYTIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_SUNDAYTIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [SUNDAYTIMEWITHINBOUNDS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYENDINGTIME]  DEFAULT ((0)) FOR [THUESDAYENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [THUESDAYENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYSTARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYSTARTINGTIME]  DEFAULT ((0)) FOR [THUESDAYSTARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYTIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THUESDAYTIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [THUESDAYTIMEWITHINBOUNDS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYENDINGTIME]  DEFAULT ((0)) FOR [THURSDAYENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [THURSDAYENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYSTARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYSTARTINGTIME]  DEFAULT ((0)) FOR [THURSDAYSTARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYTIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_THURSDAYTIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [THURSDAYTIMEWITHINBOUNDS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_TIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_TIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [TIMEWITHINBOUNDS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYENDINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYENDINGTIME]  DEFAULT ((0)) FOR [WEDNESDAYENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYENDINGTIMEAFTERMIDNIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYENDINGTIMEAFTERMIDNIGHT]  DEFAULT ((0)) FOR [WEDNESDAYENDINGTIMEAFTERMIDNIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYSTARTINGTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYSTARTINGTIME]  DEFAULT ((0)) FOR [WEDNESDAYSTARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYTIMEWITHINBOUNDS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDISCOUNTVALIDATIONPERIOD] ADD  CONSTRAINT [DF_RETAILDISCOUNTVALIDATIONPERIOD_WEDNESDAYTIMEWITHINBOUNDS]  DEFAULT ((0)) FOR [WEDNESDAYTIMEWITHINBOUNDS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDISCOUNTVALIDATIONPERIOD] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDLVMODEADDRESSEXPLODED]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDLVMODEADDRESSEXPLODED](
[RECID] [bigint] NOT NULL,
[COUNTRYREGION] [nvarchar](10) NOT NULL,
[DLVMODE] [bigint] NOT NULL,
[STATE] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1442873101_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1442873101_1977120800] UNIQUE NONCLUSTERED 
(
[STATE] ASC,
[DLVMODE] ASC,
[COUNTRYREGION] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODEADDRESSEXPLODED_COUNTRYREGION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODEADDRESSEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODEADDRESSEXPLODED_COUNTRYREGION]  DEFAULT ('') FOR [COUNTRYREGION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODEADDRESSEXPLODED_DLVMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODEADDRESSEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODEADDRESSEXPLODED_DLVMODE]  DEFAULT ((0)) FOR [DLVMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODEADDRESSEXPLODED_STATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODEADDRESSEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODEADDRESSEXPLODED_STATE]  DEFAULT ('') FOR [STATE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDLVMODEADDRESSEXPLODED] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDLVMODECHANNELEXPLODED]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDLVMODECHANNELEXPLODED](
[RECID] [bigint] NOT NULL,
[DLVMODE] [bigint] NOT NULL,
[OMOPERATINGUNIT] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-750738950_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-750738950_-724959869] UNIQUE NONCLUSTERED 
(
[OMOPERATINGUNIT] ASC,
[DLVMODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODECHANNELEXPLODED_DLVMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODECHANNELEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODECHANNELEXPLODED_DLVMODE]  DEFAULT ((0)) FOR [DLVMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODECHANNELEXPLODED_OMOPERATINGUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODECHANNELEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODECHANNELEXPLODED_OMOPERATINGUNIT]  DEFAULT ((0)) FOR [OMOPERATINGUNIT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDLVMODECHANNELEXPLODED] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILDLVMODEPRODUCTEXPLODED]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILDLVMODEPRODUCTEXPLODED](
[RECID] [bigint] NOT NULL,
[DLVMODE] [bigint] NOT NULL,
[INVENTDIM] [nvarchar](20) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1711265534_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1711265534_-1243541637] UNIQUE NONCLUSTERED 
(
[DLVMODE] ASC,
[ITEMID] ASC,
[INVENTDIM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODEPRODUCTEXPLODED_DLVMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODEPRODUCTEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODEPRODUCTEXPLODED_DLVMODE]  DEFAULT ((0)) FOR [DLVMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODEPRODUCTEXPLODED_INVENTDIM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODEPRODUCTEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODEPRODUCTEXPLODED_INVENTDIM]  DEFAULT ('') FOR [INVENTDIM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILDLVMODEPRODUCTEXPLODED_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILDLVMODEPRODUCTEXPLODED] ADD  CONSTRAINT [DF_RETAILDLVMODEPRODUCTEXPLODED_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILDLVMODEPRODUCTEXPLODED] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALDOCUMENTMODEL2_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR](
[CONSUMERCNPJCPFNUMBER] [nvarchar](20) NOT NULL,
[FISCALDOCUMENTACCOUNTNUM] [nvarchar](20) NOT NULL,
[FISCALDOCUMENTDATE] [date] NOT NULL,
[FISCALDOCUMENTNUMBER] [nvarchar](20) NOT NULL,
[FISCALDOCUMENTSERIES] [nvarchar](3) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STATUS] [int] NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TOTALAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALSURCHARGEAMOUNT] [numeric](32, 16) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-536311148_419671329] PRIMARY KEY CLUSTERED 
(
[FISCALDOCUMENTDATE] ASC,
[FISCALDOCUMENTNUMBER] ASC,
[FISCALDOCUMENTSERIES] ASC,
[TERMINALID] ASC,
[STOREID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALDOCUMENTMODEL2_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_CONSUMERCNPJCPFNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_CONSUMERCNPJCPFNUMBER]  DEFAULT ('') FOR [CONSUMERCNPJCPFNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTACCOUNTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTACCOUNTNUM]  DEFAULT ('') FOR [FISCALDOCUMENTACCOUNTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTDATE]  DEFAULT ('1900-01-01') FOR [FISCALDOCUMENTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTNUMBER]  DEFAULT ('') FOR [FISCALDOCUMENTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTSERIES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_FISCALDOCUMENTSERIES]  DEFAULT ('') FOR [FISCALDOCUMENTSERIES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_TOTALAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_TOTALAMOUNT]  DEFAULT ((0)) FOR [TOTALAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_TOTALDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_TOTALDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [TOTALDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_TOTALSURCHARGEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_TOTALSURCHARGEAMOUNT]  DEFAULT ((0)) FOR [TOTALSURCHARGEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALDOCUMENTMODEL2_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR](
[CFOP] [nvarchar](5) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[LINEAMOUNT] [numeric](32, 16) NOT NULL,
[LINEDISCOUNT] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[LINESURCHARGE] [numeric](32, 16) NOT NULL,
[QUANTITY] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[UNIT] [nvarchar](10) NOT NULL,
[UNITPRICE] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-642316962_-1103390687] PRIMARY KEY CLUSTERED 
(
[LINENUM] ASC,
[TRANSACTIONID] ASC,
[TERMINALID] ASC,
[STOREID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALDOCUMENTMODEL2LINE_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_CFOP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_CFOP]  DEFAULT ('') FOR [CFOP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINEAMOUNT]  DEFAULT ((0)) FOR [LINEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINEDISCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINEDISCOUNT]  DEFAULT ((0)) FOR [LINEDISCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINESURCHARGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_LINESURCHARGE]  DEFAULT ((0)) FOR [LINESURCHARGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_QUANTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_QUANTITY]  DEFAULT ((0)) FOR [QUANTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_UNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_UNIT]  DEFAULT ('') FOR [UNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_UNITPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2LINE_BR_UNITPRICE]  DEFAULT ((0)) FOR [UNITPRICE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALDOCUMENTMODEL2LINE_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR](
[FISCALVALUE] [int] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TAXAMOUNT] [numeric](32, 16) NOT NULL,
[TAXATIONCODE] [nvarchar](3) NOT NULL,
[TAXATIONORIGIN] [int] NOT NULL,
[TAXBASEAMOUNT] [numeric](32, 16) NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXREDUCTIONPCT] [numeric](32, 16) NOT NULL,
[TAXTYPE] [int] NOT NULL,
[TAXVALUE] [numeric](32, 16) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1437421203_-1871252748] PRIMARY KEY CLUSTERED 
(
[LINENUM] ASC,
[TAXTYPE] ASC,
[TRANSACTIONID] ASC,
[TERMINALID] ASC,
[STOREID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_FISCALVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_FISCALVALUE]  DEFAULT ((0)) FOR [FISCALVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXAMOUNT]  DEFAULT ((0)) FOR [TAXAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXATIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXATIONCODE]  DEFAULT ('') FOR [TAXATIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXATIONORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXATIONORIGIN]  DEFAULT ((0)) FOR [TAXATIONORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXBASEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXBASEAMOUNT]  DEFAULT ((0)) FOR [TAXBASEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXREDUCTIONPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXREDUCTIONPCT]  DEFAULT ((0)) FOR [TAXREDUCTIONPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXTYPE]  DEFAULT ((0)) FOR [TAXTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TAXVALUE]  DEFAULT ((0)) FOR [TAXVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALPRINTER_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALPRINTER_BR](
[ADDITIONALFISCALMEMORYINDEX] [int] NOT NULL,
[FISCALESTABLISHMENT] [nvarchar](10) NOT NULL,
[FISCALRECEIPTMODEL] [nvarchar](3) NOT NULL,
[MANUFACTURER] [nvarchar](20) NOT NULL,
[MODELNUMBER] [nvarchar](30) NOT NULL,
[NATIONALCODE] [nvarchar](6) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[RESTARTOPERATIONNUMBER] [int] NOT NULL,
[SERIALNUMBER] [nvarchar](20) NOT NULL,
[SOFTWAREDATE] [date] NOT NULL,
[SOFTWAREVERSION] [nvarchar](10) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TERMINALNUMBER] [int] NOT NULL,
[TYPE] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-802645346_100835462] PRIMARY KEY CLUSTERED 
(
[SERIALNUMBER] ASC,
[ADDITIONALFISCALMEMORYINDEX] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[RESTARTOPERATIONNUMBER] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALPRINTER_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_ADDITIONALFISCALMEMORYINDEX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_ADDITIONALFISCALMEMORYINDEX]  DEFAULT ((0)) FOR [ADDITIONALFISCALMEMORYINDEX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_FISCALESTABLISHMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_FISCALESTABLISHMENT]  DEFAULT ('') FOR [FISCALESTABLISHMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_FISCALRECEIPTMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_FISCALRECEIPTMODEL]  DEFAULT ('') FOR [FISCALRECEIPTMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_MANUFACTURER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_MANUFACTURER]  DEFAULT ('') FOR [MANUFACTURER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_MODELNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_MODELNUMBER]  DEFAULT ('') FOR [MODELNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_NATIONALCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_NATIONALCODE]  DEFAULT ('') FOR [NATIONALCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_RESTARTOPERATIONNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_RESTARTOPERATIONNUMBER]  DEFAULT ((0)) FOR [RESTARTOPERATIONNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_SERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_SERIALNUMBER]  DEFAULT ('') FOR [SERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_SOFTWAREDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_SOFTWAREDATE]  DEFAULT ('1900-01-01') FOR [SOFTWAREDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_SOFTWAREVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_SOFTWAREVERSION]  DEFAULT ('') FOR [SOFTWAREVERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_TERMINALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_TERMINALNUMBER]  DEFAULT ((0)) FOR [TERMINALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTER_BR_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTER_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTER_BR_TYPE]  DEFAULT ('') FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALPRINTER_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALPRINTERREPORT_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALPRINTERREPORT_BR](
[ADDITIONALFISCALMEMORYINDEX] [int] NOT NULL,
[CREDITDEBITRECEIPTNUMBER] [int] NOT NULL,
[FISCALPRINTERSERIALNUMBER] [nvarchar](20) NOT NULL,
[MANAGEMENTREPORTNUMBER] [int] NOT NULL,
[NONFISCALOPERATIONNUMBER] [int] NOT NULL,
[RECEIPTNUMBER] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[REPORTDATETIME] [datetime] NOT NULL,
[REPORTDATETIMETZID] [int] NOT NULL,
[REPORTTYPE] [nchar](2) NOT NULL,
[RESTARTOPERATIONNUMBER] [int] NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONDATETIME] [datetime] NOT NULL,
[TRANSACTIONDATETIMETZID] [int] NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1122718616_-645973167] PRIMARY KEY CLUSTERED 
(
[FISCALPRINTERSERIALNUMBER] ASC,
[ADDITIONALFISCALMEMORYINDEX] ASC,
[RESTARTOPERATIONNUMBER] ASC,
[RECEIPTNUMBER] ASC,
[TRANSACTIONID] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALPRINTERREPORT_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_ADDITIONALFISCALMEMORYINDEX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_ADDITIONALFISCALMEMORYINDEX]  DEFAULT ((0)) FOR [ADDITIONALFISCALMEMORYINDEX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_CREDITDEBITRECEIPTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_CREDITDEBITRECEIPTNUMBER]  DEFAULT ((0)) FOR [CREDITDEBITRECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_FISCALPRINTERSERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_FISCALPRINTERSERIALNUMBER]  DEFAULT ('') FOR [FISCALPRINTERSERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_MANAGEMENTREPORTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_MANAGEMENTREPORTNUMBER]  DEFAULT ((0)) FOR [MANAGEMENTREPORTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_NONFISCALOPERATIONNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_NONFISCALOPERATIONNUMBER]  DEFAULT ((0)) FOR [NONFISCALOPERATIONNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_RECEIPTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_RECEIPTNUMBER]  DEFAULT ((0)) FOR [RECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_REPORTDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_REPORTDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [REPORTDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_REPORTDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_REPORTDATETIMETZID]  DEFAULT ((37001)) FOR [REPORTDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_REPORTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_REPORTTYPE]  DEFAULT ('') FOR [REPORTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_RESTARTOPERATIONNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_RESTARTOPERATIONNUMBER]  DEFAULT ((0)) FOR [RESTARTOPERATIONNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_TRANSACTIONDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_TRANSACTIONDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSACTIONDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_TRANSACTIONDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_TRANSACTIONDATETIMETZID]  DEFAULT ((37001)) FOR [TRANSACTIONDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALPRINTERREPORT_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALPRINTERREPORT_BR] ADD  CONSTRAINT [DF_RETAILFISCALPRINTERREPORT_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALPRINTERREPORT_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALRECEIPT_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALRECEIPT_BR](
[ACCOUNTINGDATE] [date] NOT NULL,
[ADDITIONALFISCALMEMORYINDEX] [int] NOT NULL,
[CONSUMERCNPJCPFNUMBER] [nvarchar](20) NOT NULL,
[CONSUMERNAME] [nvarchar](100) NOT NULL,
[FISCALESTABLISHMENT] [nvarchar](10) NOT NULL,
[FISCALPRINTERSERIALNUMBER] [nvarchar](20) NOT NULL,
[FISCALRECEIPTDATETIME] [datetime] NOT NULL,
[FISCALRECEIPTDATETIMETZID] [int] NOT NULL,
[FISCALRECEIPTMODEL] [nvarchar](3) NOT NULL,
[FISCALRECEIPTNUMBER] [int] NOT NULL,
[PRINTEDTOTALDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[PRINTEDTOTALSURCHARGEAMOUNT] [numeric](32, 16) NOT NULL,
[QUANTITYDECIMALS] [int] NOT NULL,
[RECEIPTNUMBER] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STATUS] [int] NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TOTALAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALSURCHARGEAMOUNT] [numeric](32, 16) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[UNITDECIMALS] [int] NOT NULL,
[VOIDEDAFTERENDRECEIPT] [int] NOT NULL,
[ZREPORTNUMBER] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1580227714_-397801874] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALRECEIPT_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_ACCOUNTINGDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_ACCOUNTINGDATE]  DEFAULT ('1900-01-01') FOR [ACCOUNTINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_ADDITIONALFISCALMEMORYINDEX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_ADDITIONALFISCALMEMORYINDEX]  DEFAULT ((0)) FOR [ADDITIONALFISCALMEMORYINDEX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_CONSUMERCNPJCPFNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_CONSUMERCNPJCPFNUMBER]  DEFAULT ('') FOR [CONSUMERCNPJCPFNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_CONSUMERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_CONSUMERNAME]  DEFAULT ('') FOR [CONSUMERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_FISCALESTABLISHMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_FISCALESTABLISHMENT]  DEFAULT ('') FOR [FISCALESTABLISHMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_FISCALPRINTERSERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_FISCALPRINTERSERIALNUMBER]  DEFAULT ('') FOR [FISCALPRINTERSERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [FISCALRECEIPTDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTDATETIMETZID]  DEFAULT ((37001)) FOR [FISCALRECEIPTDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTMODEL]  DEFAULT ('') FOR [FISCALRECEIPTMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_FISCALRECEIPTNUMBER]  DEFAULT ((0)) FOR [FISCALRECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_PRINTEDTOTALDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_PRINTEDTOTALDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [PRINTEDTOTALDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_PRINTEDTOTALSURCHARGEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_PRINTEDTOTALSURCHARGEAMOUNT]  DEFAULT ((0)) FOR [PRINTEDTOTALSURCHARGEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_QUANTITYDECIMALS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_QUANTITYDECIMALS]  DEFAULT ((0)) FOR [QUANTITYDECIMALS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_RECEIPTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_RECEIPTNUMBER]  DEFAULT ((0)) FOR [RECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_TOTALAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_TOTALAMOUNT]  DEFAULT ((0)) FOR [TOTALAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_TOTALDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_TOTALDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [TOTALDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_TOTALSURCHARGEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_TOTALSURCHARGEAMOUNT]  DEFAULT ((0)) FOR [TOTALSURCHARGEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_UNITDECIMALS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_UNITDECIMALS]  DEFAULT ((0)) FOR [UNITDECIMALS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_VOIDEDAFTERENDRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_VOIDEDAFTERENDRECEIPT]  DEFAULT ((0)) FOR [VOIDEDAFTERENDRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPT_BR_ZREPORTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPT_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPT_BR_ZREPORTNUMBER]  DEFAULT ((0)) FOR [ZREPORTNUMBER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALRECEIPT_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALRECEIPTLINE_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALRECEIPTLINE_BR](
[CANCELLEDQUANTITY] [numeric](32, 16) NOT NULL,
[CFOP] [nvarchar](5) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[ITEMTYPE] [nvarchar](10) NOT NULL,
[LINEAMOUNT] [numeric](32, 16) NOT NULL,
[LINEDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[LINESURCHARGEAMOUNT] [numeric](32, 16) NOT NULL,
[PRINTEDLINEDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[PRINTEDLINESURCHARGEAMOUNT] [numeric](32, 16) NOT NULL,
[QUANTITY] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[UNIT] [nvarchar](10) NOT NULL,
[UNITPRICE] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_283734048_-1103390687] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALRECEIPTLINE_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_CANCELLEDQUANTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_CANCELLEDQUANTITY]  DEFAULT ((0)) FOR [CANCELLEDQUANTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_CFOP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_CFOP]  DEFAULT ('') FOR [CFOP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_ITEMTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_ITEMTYPE]  DEFAULT ('') FOR [ITEMTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_LINEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_LINEAMOUNT]  DEFAULT ((0)) FOR [LINEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_LINEDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_LINEDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [LINEDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_LINESURCHARGEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_LINESURCHARGEAMOUNT]  DEFAULT ((0)) FOR [LINESURCHARGEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_PRINTEDLINEDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_PRINTEDLINEDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [PRINTEDLINEDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_PRINTEDLINESURCHARGEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_PRINTEDLINESURCHARGEAMOUNT]  DEFAULT ((0)) FOR [PRINTEDLINESURCHARGEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_QUANTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_QUANTITY]  DEFAULT ((0)) FOR [QUANTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_UNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_UNIT]  DEFAULT ('') FOR [UNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTLINE_BR_UNITPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTLINE_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTLINE_BR_UNITPRICE]  DEFAULT ((0)) FOR [UNITPRICE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALRECEIPTLINE_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFISCALRECEIPTTAXTRANS_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR](
[FISCALVALUE] [int] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TAXAMOUNT] [numeric](32, 16) NOT NULL,
[TAXATIONCODE] [nvarchar](3) NOT NULL,
[TAXBASEAMOUNT] [numeric](32, 16) NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXTYPE] [int] NOT NULL,
[TAXVALUE] [numeric](32, 16) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TOTALIZERINDEX] [int] NOT NULL,
[TOTALIZERNAME] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_711206165_-1871252748] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[TAXTYPE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILFISCALRECEIPTTAXTRANS_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_FISCALVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_FISCALVALUE]  DEFAULT ((0)) FOR [FISCALVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXAMOUNT]  DEFAULT ((0)) FOR [TAXAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXATIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXATIONCODE]  DEFAULT ('') FOR [TAXATIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXBASEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXBASEAMOUNT]  DEFAULT ((0)) FOR [TAXBASEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXTYPE]  DEFAULT ((0)) FOR [TAXTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TAXVALUE]  DEFAULT ((0)) FOR [TAXVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TOTALIZERINDEX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TOTALIZERINDEX]  DEFAULT ((0)) FOR [TOTALIZERINDEX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TOTALIZERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TOTALIZERNAME]  DEFAULT ('') FOR [TOTALIZERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFISCALRECEIPTTAXTRANS_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] ADD  CONSTRAINT [DF_RETAILFISCALRECEIPTTAXTRANS_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFISCALRECEIPTTAXTRANS_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFORMLAYOUT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFORMLAYOUT](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[FOOTERXML] [nvarchar](max) NULL,
[FORMLAYOUTID] [nvarchar](10) NOT NULL,
[HEADERXML] [nvarchar](max) NULL,
[LAYOUTTYPE] [int] NOT NULL,
[LINESXML] [nvarchar](max) NULL,
[PRINTASSLIP] [int] NOT NULL,
[PRINTBEHAVIOUR] [int] NOT NULL,
[PROMPTQUESTION] [int] NOT NULL,
[TITLE] [nvarchar](30) NOT NULL,
[UPPERCASE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1005248327_-609586253] PRIMARY KEY CLUSTERED 
(
[FORMLAYOUTID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_FORMLAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_FORMLAYOUTID]  DEFAULT ('') FOR [FORMLAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_LAYOUTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_LAYOUTTYPE]  DEFAULT ((0)) FOR [LAYOUTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_PRINTASSLIP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_PRINTASSLIP]  DEFAULT ((0)) FOR [PRINTASSLIP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_PRINTBEHAVIOUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_PRINTBEHAVIOUR]  DEFAULT ((0)) FOR [PRINTBEHAVIOUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_PROMPTQUESTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_PROMPTQUESTION]  DEFAULT ((0)) FOR [PROMPTQUESTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_TITLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_TITLE]  DEFAULT ('') FOR [TITLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFORMLAYOUT_UPPERCASE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFORMLAYOUT] ADD  CONSTRAINT [DF_RETAILFORMLAYOUT_UPPERCASE]  DEFAULT ((0)) FOR [UPPERCASE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFORMLAYOUT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILFUNCTIONALITYPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILFUNCTIONALITYPROFILE](
[RECID] [bigint] NOT NULL,
[ADDTAXONPRICES] [int] NOT NULL,
[AGGREGATEITEMS] [int] NOT NULL,
[AGGREGATEITEMSFORPRINTING] [int] NOT NULL,
[AGGREGATEPAYMENTS] [int] NOT NULL,
[AMOUNTDECIMALPLACES] [nvarchar](10) NOT NULL,
[AMOUNTROUNDINGTO] [numeric](32, 16) NOT NULL,
[APPLYDISCOUNTONUNITPRICES] [int] NOT NULL,
[AUDITENABLED] [int] NOT NULL,
[BACKUPTRAININGTRANSACTIONS] [int] NOT NULL,
[BLOCKEDCLOSEDACCOUNT] [int] NOT NULL,
[CENTRALTABLESERVER] [nvarchar](256) NOT NULL,
[CENTRALTABLESERVERPORT] [nvarchar](10) NOT NULL,
[CURRENCYSYMBOL] [nvarchar](10) NOT NULL,
[DAYSCUSTOMERHISTORY] [int] NOT NULL,
[DAYSTRANSACTIONSEXISTS] [int] NOT NULL,
[DECIMALNOTREQUIREDFORMINORCURRENCYUNIT] [int] NOT NULL,
[DISCOUNTATTOTAL] [nvarchar](10) NOT NULL,
[DISPLAYSECONDARYTOTALCURRENCY] [int] NOT NULL,
[ENDOFTRANSACTION] [nvarchar](10) NOT NULL,
[EODBANKTOTALSVERIFICATION] [int] NOT NULL,
[INCLUDEKITCOMPONENTS] [int] NOT NULL,
[ITEMNOTONFILE] [nvarchar](10) NOT NULL,
[LIMITSTAFFLISTTOSTORE] [int] NOT NULL,
[LINEITEMTAXCHANGE] [nvarchar](10) NOT NULL,
[MANUALCALCULATEDISCOUNTS] [int] NOT NULL,
[MARKDOWN] [nvarchar](10) NOT NULL,
[MARKUP] [nvarchar](10) NOT NULL,
[MAXIMUMPRICE] [numeric](32, 16) NOT NULL,
[MAXIMUMQTY] [numeric](32, 16) NOT NULL,
[MAXIMUMSTORETRANSLOG] [int] NOT NULL,
[MAXTRANSACTIONSEARCHRESULTS] [int] NOT NULL,
[MINIMUMPASSWORDLENGTH] [int] NOT NULL,
[MULTIBLEITEMSYMBOL] [nvarchar](10) NOT NULL,
[MUSTKEYINPRICEIFZERO] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[NEGATIVEADJUSTMENT] [nvarchar](10) NOT NULL,
[NEGATIVESALESLINE] [nvarchar](10) NOT NULL,
[NOSALE] [nvarchar](10) NOT NULL,
[NOTAXUSED] [int] NOT NULL,
[OVERRIDEPRICE] [nvarchar](10) NOT NULL,
[PRICEDECIMALPLACES] [nvarchar](10) NOT NULL,
[PRICEROUNDINGTO] [numeric](32, 16) NOT NULL,
[PRINTXREPORTONTERMINAL] [int] NOT NULL,
[PROFILEID] [nvarchar](10) NOT NULL,
[REFUNDSALE] [nvarchar](10) NOT NULL,
[REQUIREAMOUNTDECLARATION] [int] NOT NULL,
[RETAILRECEIPTPROFILE] [nvarchar](10) NOT NULL,
[SALESPERSON] [nvarchar](10) NOT NULL,
[SALESPERSONMODE] [int] NOT NULL,
[SECONDARYTOTALCURRENCY] [nvarchar](3) NOT NULL,
[SERIALNUMBER] [nvarchar](10) NOT NULL,
[SHOWSTAFFLISTATLOGON] [int] NOT NULL,
[SKIPTAXONRECEIPT] [int] NOT NULL,
[STAFFBARCODELOGON] [int] NOT NULL,
[STAFFBARCODELOGONREQUIRESPASSWORD] [int] NOT NULL,
[STAFFCARDLOGON] [int] NOT NULL,
[STAFFCARDLOGONREQUIRESPASSWORD] [int] NOT NULL,
[STARTOFTRANSACTION] [nvarchar](10) NOT NULL,
[SUPPORTEDCOUNTRYREGIONISOCODE] [nchar](2) NOT NULL,
[TAENABLEREGISTRATION] [int] NOT NULL,
[TAXREGISTRATIONNUMBERONRECEIPT] [int] NOT NULL,
[TENDERDECLARATION] [nvarchar](10) NOT NULL,
[TRANSACTIONDELETEREMINDER] [int] NOT NULL,
[TRANSACTIONTAXCHANGE] [nvarchar](10) NOT NULL,
[TSCENTRALTABLESERVER] [int] NOT NULL,
[TSCUSTOMER] [int] NOT NULL,
[TSDATAENTRIES] [int] NOT NULL,
[TSFLOATINGCASHIER] [int] NOT NULL,
[TSINVENTORYLOOKUP] [int] NOT NULL,
[TSRESENDDELAY] [int] NOT NULL,
[TSSENDTRANSACTIONS] [int] NOT NULL,
[TSSENDVOIDTRANSACTIONS] [int] NOT NULL,
[TSSTAFF] [int] NOT NULL,
[TSSUSPENDRETRIEVETRANSACTIONS] [int] NOT NULL,
[TSTRANSACTIONRESENDLIMIT] [int] NOT NULL,
[TSUPDATEREPLICATIONCOUNTER] [int] NOT NULL,
[VOIDISPRESSED] [nvarchar](10) NOT NULL,
[VOIDPAYMENT] [nvarchar](10) NOT NULL,
[VOIDTRANSACTION] [nvarchar](10) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-953240733_-2102841330] PRIMARY KEY CLUSTERED 
(
[PROFILEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_ADDTAXONPRICES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_ADDTAXONPRICES]  DEFAULT ((0)) FOR [ADDTAXONPRICES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_AGGREGATEITEMS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_AGGREGATEITEMS]  DEFAULT ((0)) FOR [AGGREGATEITEMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_AGGREGATEITEMSFORPRINTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_AGGREGATEITEMSFORPRINTING]  DEFAULT ((0)) FOR [AGGREGATEITEMSFORPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_AGGREGATEPAYMENTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_AGGREGATEPAYMENTS]  DEFAULT ((0)) FOR [AGGREGATEPAYMENTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_AMOUNTDECIMALPLACES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_AMOUNTDECIMALPLACES]  DEFAULT ('') FOR [AMOUNTDECIMALPLACES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_AMOUNTROUNDINGTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_AMOUNTROUNDINGTO]  DEFAULT ((0)) FOR [AMOUNTROUNDINGTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_APPLYDISCOUNTONUNITPRICES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_APPLYDISCOUNTONUNITPRICES]  DEFAULT ((0)) FOR [APPLYDISCOUNTONUNITPRICES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_AUDITENABLED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_AUDITENABLED]  DEFAULT ((0)) FOR [AUDITENABLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_BACKUPTRAININGTRANSACTIONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_BACKUPTRAININGTRANSACTIONS]  DEFAULT ((0)) FOR [BACKUPTRAININGTRANSACTIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_BLOCKEDCLOSEDACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_BLOCKEDCLOSEDACCOUNT]  DEFAULT ((0)) FOR [BLOCKEDCLOSEDACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_CENTRALTABLESERVER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_CENTRALTABLESERVER]  DEFAULT ('') FOR [CENTRALTABLESERVER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_CENTRALTABLESERVERPORT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_CENTRALTABLESERVERPORT]  DEFAULT ('') FOR [CENTRALTABLESERVERPORT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_CURRENCYSYMBOL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_CURRENCYSYMBOL]  DEFAULT ('') FOR [CURRENCYSYMBOL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_DAYSCUSTOMERHISTORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_DAYSCUSTOMERHISTORY]  DEFAULT ((0)) FOR [DAYSCUSTOMERHISTORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_DAYSTRANSACTIONSEXISTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_DAYSTRANSACTIONSEXISTS]  DEFAULT ((0)) FOR [DAYSTRANSACTIONSEXISTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_DECIMALNOTREQUIREDFORMINORCURRENCYUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_DECIMALNOTREQUIREDFORMINORCURRENCYUNIT]  DEFAULT ((0)) FOR [DECIMALNOTREQUIREDFORMINORCURRENCYUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_DISCOUNTATTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_DISCOUNTATTOTAL]  DEFAULT ('') FOR [DISCOUNTATTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_DISPLAYSECONDARYTOTALCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_DISPLAYSECONDARYTOTALCURRENCY]  DEFAULT ((0)) FOR [DISPLAYSECONDARYTOTALCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_ENDOFTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_ENDOFTRANSACTION]  DEFAULT ('') FOR [ENDOFTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_EODBANKTOTALSVERIFICATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_EODBANKTOTALSVERIFICATION]  DEFAULT ((0)) FOR [EODBANKTOTALSVERIFICATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_INCLUDEKITCOMPONENTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_INCLUDEKITCOMPONENTS]  DEFAULT ((0)) FOR [INCLUDEKITCOMPONENTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_ITEMNOTONFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_ITEMNOTONFILE]  DEFAULT ('') FOR [ITEMNOTONFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_LIMITSTAFFLISTTOSTORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_LIMITSTAFFLISTTOSTORE]  DEFAULT ((0)) FOR [LIMITSTAFFLISTTOSTORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_LINEITEMTAXCHANGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_LINEITEMTAXCHANGE]  DEFAULT ('') FOR [LINEITEMTAXCHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MANUALCALCULATEDISCOUNTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MANUALCALCULATEDISCOUNTS]  DEFAULT ((0)) FOR [MANUALCALCULATEDISCOUNTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MARKDOWN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MARKDOWN]  DEFAULT ('') FOR [MARKDOWN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MARKUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MARKUP]  DEFAULT ('') FOR [MARKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MAXIMUMPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MAXIMUMPRICE]  DEFAULT ((0)) FOR [MAXIMUMPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MAXIMUMQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MAXIMUMQTY]  DEFAULT ((0)) FOR [MAXIMUMQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MAXIMUMSTORETRANSLOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MAXIMUMSTORETRANSLOG]  DEFAULT ((0)) FOR [MAXIMUMSTORETRANSLOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MAXTRANSACTIONSEARCHRESULTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MAXTRANSACTIONSEARCHRESULTS]  DEFAULT ((0)) FOR [MAXTRANSACTIONSEARCHRESULTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MINIMUMPASSWORDLENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MINIMUMPASSWORDLENGTH]  DEFAULT ((0)) FOR [MINIMUMPASSWORDLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MULTIBLEITEMSYMBOL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MULTIBLEITEMSYMBOL]  DEFAULT ('') FOR [MULTIBLEITEMSYMBOL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MUSTKEYINPRICEIFZERO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MUSTKEYINPRICEIFZERO]  DEFAULT ((0)) FOR [MUSTKEYINPRICEIFZERO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_NEGATIVEADJUSTMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_NEGATIVEADJUSTMENT]  DEFAULT ('') FOR [NEGATIVEADJUSTMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_NEGATIVESALESLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_NEGATIVESALESLINE]  DEFAULT ('') FOR [NEGATIVESALESLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_NOSALE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_NOSALE]  DEFAULT ('') FOR [NOSALE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_NOTAXUSED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_NOTAXUSED]  DEFAULT ((0)) FOR [NOTAXUSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_OVERRIDEPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_OVERRIDEPRICE]  DEFAULT ('') FOR [OVERRIDEPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_PRICEDECIMALPLACES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_PRICEDECIMALPLACES]  DEFAULT ('') FOR [PRICEDECIMALPLACES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_PRICEROUNDINGTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_PRICEROUNDINGTO]  DEFAULT ((0)) FOR [PRICEROUNDINGTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_PRINTXREPORTONTERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_PRINTXREPORTONTERMINAL]  DEFAULT ((0)) FOR [PRINTXREPORTONTERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_PROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_PROFILEID]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_REFUNDSALE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_REFUNDSALE]  DEFAULT ('') FOR [REFUNDSALE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_REQUIREAMOUNTDECLARATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_REQUIREAMOUNTDECLARATION]  DEFAULT ((0)) FOR [REQUIREAMOUNTDECLARATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_RETAILRECEIPTPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_RETAILRECEIPTPROFILE]  DEFAULT ('') FOR [RETAILRECEIPTPROFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_SALESPERSON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_SALESPERSON]  DEFAULT ('') FOR [SALESPERSON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_SALESPERSONMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_SALESPERSONMODE]  DEFAULT ((0)) FOR [SALESPERSONMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_SECONDARYTOTALCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_SECONDARYTOTALCURRENCY]  DEFAULT ('') FOR [SECONDARYTOTALCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_SERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_SERIALNUMBER]  DEFAULT ('') FOR [SERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_SHOWSTAFFLISTATLOGON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_SHOWSTAFFLISTATLOGON]  DEFAULT ((0)) FOR [SHOWSTAFFLISTATLOGON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_SKIPTAXONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_SKIPTAXONRECEIPT]  DEFAULT ((0)) FOR [SKIPTAXONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_STAFFBARCODELOGON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_STAFFBARCODELOGON]  DEFAULT ((0)) FOR [STAFFBARCODELOGON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_STAFFBARCODELOGONREQUIRESPASSWORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_STAFFBARCODELOGONREQUIRESPASSWORD]  DEFAULT ((0)) FOR [STAFFBARCODELOGONREQUIRESPASSWORD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_STAFFCARDLOGON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_STAFFCARDLOGON]  DEFAULT ((0)) FOR [STAFFCARDLOGON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_STAFFCARDLOGONREQUIRESPASSWORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_STAFFCARDLOGONREQUIRESPASSWORD]  DEFAULT ((0)) FOR [STAFFCARDLOGONREQUIRESPASSWORD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_STARTOFTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_STARTOFTRANSACTION]  DEFAULT ('') FOR [STARTOFTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_SUPPORTEDCOUNTRYREGIONISOCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_SUPPORTEDCOUNTRYREGIONISOCODE]  DEFAULT ('') FOR [SUPPORTEDCOUNTRYREGIONISOCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TAENABLEREGISTRATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TAENABLEREGISTRATION]  DEFAULT ((0)) FOR [TAENABLEREGISTRATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TAXREGISTRATIONNUMBERONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TAXREGISTRATIONNUMBERONRECEIPT]  DEFAULT ((0)) FOR [TAXREGISTRATIONNUMBERONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TENDERDECLARATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TENDERDECLARATION]  DEFAULT ('') FOR [TENDERDECLARATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TRANSACTIONDELETEREMINDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TRANSACTIONDELETEREMINDER]  DEFAULT ((0)) FOR [TRANSACTIONDELETEREMINDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TRANSACTIONTAXCHANGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TRANSACTIONTAXCHANGE]  DEFAULT ('') FOR [TRANSACTIONTAXCHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSCENTRALTABLESERVER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSCENTRALTABLESERVER]  DEFAULT ((0)) FOR [TSCENTRALTABLESERVER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSCUSTOMER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSCUSTOMER]  DEFAULT ((0)) FOR [TSCUSTOMER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSDATAENTRIES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSDATAENTRIES]  DEFAULT ((0)) FOR [TSDATAENTRIES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSFLOATINGCASHIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSFLOATINGCASHIER]  DEFAULT ((0)) FOR [TSFLOATINGCASHIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSINVENTORYLOOKUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSINVENTORYLOOKUP]  DEFAULT ((0)) FOR [TSINVENTORYLOOKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSRESENDDELAY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSRESENDDELAY]  DEFAULT ((0)) FOR [TSRESENDDELAY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSSENDTRANSACTIONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSSENDTRANSACTIONS]  DEFAULT ((0)) FOR [TSSENDTRANSACTIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSSENDVOIDTRANSACTIONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSSENDVOIDTRANSACTIONS]  DEFAULT ((0)) FOR [TSSENDVOIDTRANSACTIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSSTAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSSTAFF]  DEFAULT ((0)) FOR [TSSTAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSSUSPENDRETRIEVETRANSACTIONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSSUSPENDRETRIEVETRANSACTIONS]  DEFAULT ((0)) FOR [TSSUSPENDRETRIEVETRANSACTIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSTRANSACTIONRESENDLIMIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSTRANSACTIONRESENDLIMIT]  DEFAULT ((0)) FOR [TSTRANSACTIONRESENDLIMIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_TSUPDATEREPLICATIONCOUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_TSUPDATEREPLICATIONCOUNTER]  DEFAULT ((0)) FOR [TSUPDATEREPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_VOIDISPRESSED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_VOIDISPRESSED]  DEFAULT ('') FOR [VOIDISPRESSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_VOIDPAYMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_VOIDPAYMENT]  DEFAULT ('') FOR [VOIDPAYMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_VOIDTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_VOIDTRANSACTION]  DEFAULT ('') FOR [VOIDTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILFUNCTIONALITYPROFILE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILFUNCTIONALITYPROFILE] ADD  CONSTRAINT [DF_RETAILFUNCTIONALITYPROFILE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILFUNCTIONALITYPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILGROUPMEMBERLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILGROUPMEMBERLINE](
[RECID] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[VARIANT] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1245137364_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILGROUPMEMBERLINE_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILGROUPMEMBERLINE] ADD  CONSTRAINT [DF_RETAILGROUPMEMBERLINE_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILGROUPMEMBERLINE_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILGROUPMEMBERLINE] ADD  CONSTRAINT [DF_RETAILGROUPMEMBERLINE_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILGROUPMEMBERLINE_VARIANT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILGROUPMEMBERLINE] ADD  CONSTRAINT [DF_RETAILGROUPMEMBERLINE_VARIANT]  DEFAULT ((0)) FOR [VARIANT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILGROUPMEMBERLINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILHARDWAREPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILHARDWAREPROFILE](
[RECID] [bigint] NOT NULL,
[CAPTUREEXTRADATA] [int] NOT NULL,
[CASHCHANGER] [int] NOT NULL,
[CASHCHANGERINITSETTINGS] [nvarchar](100) NOT NULL,
[CASHCHANGERPORTSETTINGS] [nvarchar](50) NOT NULL,
[CCTV] [int] NOT NULL,
[CCTVCAMERA] [nvarchar](60) NOT NULL,
[CCTVHOSTNAME] [nvarchar](60) NOT NULL,
[CCTVPORT] [int] NOT NULL,
[DELAYFORLINKEDITEMS] [int] NOT NULL,
[DISPLAYBALANCETEXT] [nvarchar](60) NOT NULL,
[DISPLAYBINCONVERSION] [int] NOT NULL,
[DISPLAYCHARACTERSET] [int] NOT NULL,
[DISPLAYCLOSEDLINE1] [nvarchar](60) NOT NULL,
[DISPLAYCLOSEDLINE2] [nvarchar](60) NOT NULL,
[DISPLAYDESCRIPTION] [nvarchar](60) NOT NULL,
[DISPLAYDEVICE] [int] NOT NULL,
[DISPLAYDEVICENAME] [nvarchar](60) NOT NULL,
[DISPLAYLINKEDITEM] [int] NOT NULL,
[DISPLAYTERMINALCLOSED] [int] NOT NULL,
[DISPLAYTOTALTEXT] [nvarchar](60) NOT NULL,
[DOCINSERTREMOVALTIMEOUT] [int] NOT NULL,
[DRAWER] [int] NOT NULL,
[DRAWER2] [int] NOT NULL,
[DRAWER2DESCRIPTION] [nvarchar](60) NOT NULL,
[DRAWER2DEVICENAME] [nvarchar](512) NOT NULL,
[DRAWER2MAKE] [nvarchar](30) NOT NULL,
[DRAWER2MODEL] [nvarchar](30) NOT NULL,
[DRAWERDESCRIPTION] [nvarchar](60) NOT NULL,
[DRAWERDEVICENAME] [nvarchar](512) NOT NULL,
[DRAWERMAKE] [nvarchar](30) NOT NULL,
[DRAWERMODEL] [nvarchar](30) NOT NULL,
[DUALDISPLAY] [int] NOT NULL,
[DUALDISPLAYBROWSERURL] [nvarchar](255) NOT NULL,
[DUALDISPLAYIMAGEINTERVAL] [int] NOT NULL,
[DUALDISPLAYIMAGEPATH] [nvarchar](259) NOT NULL,
[DUALDISPLAYRECEIPTPERCENTAGE] [numeric](32, 16) NOT NULL,
[DUALDISPLAYTYPE] [int] NOT NULL,
[EFT] [int] NOT NULL,
[EFTCOMPANYID] [nvarchar](50) NOT NULL,
[EFTCONFIGURATION] [int] NOT NULL,
[EFTCONNECTORNAME] [nvarchar](50) NOT NULL,
[EFTCONNECTORPROPERTIES] [nvarchar](max) NULL,
[EFTDATA] [nvarchar](128) NOT NULL,
[EFTDESCRIPTION] [nvarchar](60) NOT NULL,
[EFTMERCHANTID] [nvarchar](25) NOT NULL,
[EFTPASSWORD] [nvarchar](16) NOT NULL,
[EFTSERVERNAME] [nvarchar](80) NOT NULL,
[EFTSERVERPORT] [nvarchar](10) NOT NULL,
[EFTUSERID] [nvarchar](60) NOT NULL,
[ENDTRACK1] [nvarchar](5) NOT NULL,
[ENDTRACK2] [nchar](1) NOT NULL,
[FISCALPRINTER] [int] NOT NULL,
[FISCALPRINTERDESCRIPTION] [nvarchar](60) NOT NULL,
[FISCALPRINTERDEVICENAME] [nvarchar](512) NOT NULL,
[FORMXPOS] [int] NOT NULL,
[FORMYPOS] [int] NOT NULL,
[HARDTOTAL] [int] NOT NULL,
[HARDTOTALDESCRIPTION] [nvarchar](60) NOT NULL,
[HARDTOTALDEVICENAME] [nvarchar](512) NOT NULL,
[KEYBOARDMAPPINGID] [nvarchar](10) NOT NULL,
[KEYLOCK] [int] NOT NULL,
[KEYLOCKDESCRIPTION] [nvarchar](60) NOT NULL,
[KEYLOCKDEVICENAME] [nvarchar](512) NOT NULL,
[LOGO] [int] NOT NULL,
[LOGOALIGNMENT] [int] NOT NULL,
[LOGOBITMAP] [varbinary](max) NULL,
[MANUALINPUTALLOWED] [int] NOT NULL,
[MAXINVOICELINES] [int] NOT NULL,
[MICR] [int] NOT NULL,
[MICRDESCRIPTION] [nvarchar](60) NOT NULL,
[MICRDRIVERNAME] [nvarchar](30) NOT NULL,
[MSR] [int] NOT NULL,
[MSRDESCRIPTION] [nvarchar](60) NOT NULL,
[MSRDEVICENAME] [nvarchar](512) NOT NULL,
[MSRMAKE] [nvarchar](30) NOT NULL,
[MSRMODEL] [nvarchar](30) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PHARMACY] [int] NOT NULL,
[PHARMACYHOST] [nvarchar](60) NOT NULL,
[PHARMACYPORT] [int] NOT NULL,
[PINPAD] [int] NOT NULL,
[PINPADDESCRIPTION] [nvarchar](60) NOT NULL,
[PINPADDEVICENAME] [nvarchar](512) NOT NULL,
[PINPADMAKE] [nvarchar](30) NOT NULL,
[PINPADMODEL] [nvarchar](30) NOT NULL,
[PRINTBINARYCONVERSION] [int] NOT NULL,
[PRINTER] [int] NOT NULL,
[PRINTER2] [int] NOT NULL,
[PRINTER2BINARYCONVERSION] [int] NOT NULL,
[PRINTER2CHARACTERSET] [int] NOT NULL,
[PRINTER2DESCRIPTION] [nvarchar](60) NOT NULL,
[PRINTER2DEVICENAME] [nvarchar](512) NOT NULL,
[PRINTER2DOCINSERTREMOVALTIMEOUT] [int] NOT NULL,
[PRINTER2LOGO] [int] NOT NULL,
[PRINTER2LOGOALIGNMENT] [int] NOT NULL,
[PRINTER2LOGOBITMAP] [varbinary](max) NULL,
[PRINTER2MAKE] [nvarchar](30) NOT NULL,
[PRINTER2MODEL] [nvarchar](30) NOT NULL,
[PRINTER2RECEIPTPROFILEID] [nvarchar](10) NOT NULL,
[PRINTERCHARACTERSET] [int] NOT NULL,
[PRINTERDESCRIPTION] [nvarchar](60) NOT NULL,
[PRINTERDEVICENAME] [nvarchar](512) NOT NULL,
[PRINTERMAKE] [nvarchar](30) NOT NULL,
[PRINTERMODEL] [nvarchar](30) NOT NULL,
[PRINTERRECEIPTPROFILEID] [nvarchar](10) NOT NULL,
[PROFILEID] [nvarchar](10) NOT NULL,
[RFIDDESCRIPTION] [nvarchar](60) NOT NULL,
[RFIDDEVICENAME] [nvarchar](512) NOT NULL,
[RFIDSCANNERTYPE] [int] NOT NULL,
[SCALE] [int] NOT NULL,
[SCALEDESCRIPTION] [nvarchar](60) NOT NULL,
[SCALEDEVICENAME] [nvarchar](512) NOT NULL,
[SCANNER] [int] NOT NULL,
[SCANNER2] [int] NOT NULL,
[SCANNER2DESCRIPTION] [nvarchar](60) NOT NULL,
[SCANNER2DEVICENAME] [nvarchar](512) NOT NULL,
[SCANNERDESCRIPTION] [nvarchar](60) NOT NULL,
[SCANNERDEVICENAME] [nvarchar](512) NOT NULL,
[SCREENKEYBOARD] [int] NOT NULL,
[SEPARATOR1] [nchar](1) NOT NULL,
[SHOWPICTURE] [int] NOT NULL,
[SIGCAP] [int] NOT NULL,
[SIGCAPDESCRIPTION] [nvarchar](60) NOT NULL,
[SIGCAPDEVICENAME] [nvarchar](512) NOT NULL,
[SIGCAPFORMNAME] [nvarchar](50) NOT NULL,
[SIGCAPMAKE] [nvarchar](30) NOT NULL,
[SIGCAPMODEL] [nvarchar](30) NOT NULL,
[STARTTRACK1] [nvarchar](5) NOT NULL,
[STARTTRACK2AFTER] [int] NOT NULL,
[TIMEOUTINSEC] [int] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1111485814_-2102841330] PRIMARY KEY CLUSTERED 
(
[PROFILEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CAPTUREEXTRADATA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CAPTUREEXTRADATA]  DEFAULT ((0)) FOR [CAPTUREEXTRADATA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CASHCHANGER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CASHCHANGER]  DEFAULT ((0)) FOR [CASHCHANGER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CASHCHANGERINITSETTINGS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CASHCHANGERINITSETTINGS]  DEFAULT ('') FOR [CASHCHANGERINITSETTINGS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CASHCHANGERPORTSETTINGS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CASHCHANGERPORTSETTINGS]  DEFAULT ('') FOR [CASHCHANGERPORTSETTINGS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CCTV]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CCTV]  DEFAULT ((0)) FOR [CCTV]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CCTVCAMERA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CCTVCAMERA]  DEFAULT ('') FOR [CCTVCAMERA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CCTVHOSTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CCTVHOSTNAME]  DEFAULT ('') FOR [CCTVHOSTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_CCTVPORT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_CCTVPORT]  DEFAULT ((0)) FOR [CCTVPORT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DELAYFORLINKEDITEMS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DELAYFORLINKEDITEMS]  DEFAULT ((0)) FOR [DELAYFORLINKEDITEMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYBALANCETEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYBALANCETEXT]  DEFAULT ('') FOR [DISPLAYBALANCETEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYBINCONVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYBINCONVERSION]  DEFAULT ((0)) FOR [DISPLAYBINCONVERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYCHARACTERSET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYCHARACTERSET]  DEFAULT ((0)) FOR [DISPLAYCHARACTERSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYCLOSEDLINE1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYCLOSEDLINE1]  DEFAULT ('') FOR [DISPLAYCLOSEDLINE1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYCLOSEDLINE2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYCLOSEDLINE2]  DEFAULT ('') FOR [DISPLAYCLOSEDLINE2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYDESCRIPTION]  DEFAULT ('') FOR [DISPLAYDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYDEVICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYDEVICE]  DEFAULT ((0)) FOR [DISPLAYDEVICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYDEVICENAME]  DEFAULT ('') FOR [DISPLAYDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYLINKEDITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYLINKEDITEM]  DEFAULT ((0)) FOR [DISPLAYLINKEDITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYTERMINALCLOSED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYTERMINALCLOSED]  DEFAULT ((0)) FOR [DISPLAYTERMINALCLOSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DISPLAYTOTALTEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DISPLAYTOTALTEXT]  DEFAULT ('') FOR [DISPLAYTOTALTEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DOCINSERTREMOVALTIMEOUT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DOCINSERTREMOVALTIMEOUT]  DEFAULT ((0)) FOR [DOCINSERTREMOVALTIMEOUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWER]  DEFAULT ((0)) FOR [DRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWER2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWER2]  DEFAULT ((0)) FOR [DRAWER2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWER2DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWER2DESCRIPTION]  DEFAULT ('') FOR [DRAWER2DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWER2DEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWER2DEVICENAME]  DEFAULT ('') FOR [DRAWER2DEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWER2MAKE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWER2MAKE]  DEFAULT ('') FOR [DRAWER2MAKE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWER2MODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWER2MODEL]  DEFAULT ('') FOR [DRAWER2MODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWERDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWERDESCRIPTION]  DEFAULT ('') FOR [DRAWERDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWERDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWERDEVICENAME]  DEFAULT ('') FOR [DRAWERDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWERMAKE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWERMAKE]  DEFAULT ('') FOR [DRAWERMAKE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DRAWERMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DRAWERMODEL]  DEFAULT ('') FOR [DRAWERMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DUALDISPLAY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DUALDISPLAY]  DEFAULT ((0)) FOR [DUALDISPLAY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DUALDISPLAYBROWSERURL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DUALDISPLAYBROWSERURL]  DEFAULT ('') FOR [DUALDISPLAYBROWSERURL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DUALDISPLAYIMAGEINTERVAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DUALDISPLAYIMAGEINTERVAL]  DEFAULT ((0)) FOR [DUALDISPLAYIMAGEINTERVAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DUALDISPLAYIMAGEPATH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DUALDISPLAYIMAGEPATH]  DEFAULT ('') FOR [DUALDISPLAYIMAGEPATH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DUALDISPLAYRECEIPTPERCENTAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DUALDISPLAYRECEIPTPERCENTAGE]  DEFAULT ((0)) FOR [DUALDISPLAYRECEIPTPERCENTAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_DUALDISPLAYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_DUALDISPLAYTYPE]  DEFAULT ((0)) FOR [DUALDISPLAYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFT]  DEFAULT ((0)) FOR [EFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTCOMPANYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTCOMPANYID]  DEFAULT ('') FOR [EFTCOMPANYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTCONFIGURATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTCONFIGURATION]  DEFAULT ((0)) FOR [EFTCONFIGURATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTCONNECTORNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTCONNECTORNAME]  DEFAULT ('') FOR [EFTCONNECTORNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTDATA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTDATA]  DEFAULT ('') FOR [EFTDATA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTDESCRIPTION]  DEFAULT ('') FOR [EFTDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTMERCHANTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTMERCHANTID]  DEFAULT ('') FOR [EFTMERCHANTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTPASSWORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTPASSWORD]  DEFAULT ('') FOR [EFTPASSWORD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTSERVERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTSERVERNAME]  DEFAULT ('') FOR [EFTSERVERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTSERVERPORT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTSERVERPORT]  DEFAULT ('') FOR [EFTSERVERPORT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_EFTUSERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_EFTUSERID]  DEFAULT ('') FOR [EFTUSERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_ENDTRACK1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_ENDTRACK1]  DEFAULT ('') FOR [ENDTRACK1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_ENDTRACK2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_ENDTRACK2]  DEFAULT ('') FOR [ENDTRACK2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_FISCALPRINTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_FISCALPRINTER]  DEFAULT ((0)) FOR [FISCALPRINTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_FISCALPRINTERDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_FISCALPRINTERDESCRIPTION]  DEFAULT ('') FOR [FISCALPRINTERDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_FISCALPRINTERDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_FISCALPRINTERDEVICENAME]  DEFAULT ('') FOR [FISCALPRINTERDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_FORMXPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_FORMXPOS]  DEFAULT ((0)) FOR [FORMXPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_FORMYPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_FORMYPOS]  DEFAULT ((0)) FOR [FORMYPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_HARDTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_HARDTOTAL]  DEFAULT ((0)) FOR [HARDTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_HARDTOTALDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_HARDTOTALDESCRIPTION]  DEFAULT ('') FOR [HARDTOTALDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_HARDTOTALDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_HARDTOTALDEVICENAME]  DEFAULT ('') FOR [HARDTOTALDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_KEYBOARDMAPPINGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_KEYBOARDMAPPINGID]  DEFAULT ('') FOR [KEYBOARDMAPPINGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_KEYLOCK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_KEYLOCK]  DEFAULT ((0)) FOR [KEYLOCK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_KEYLOCKDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_KEYLOCKDESCRIPTION]  DEFAULT ('') FOR [KEYLOCKDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_KEYLOCKDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_KEYLOCKDEVICENAME]  DEFAULT ('') FOR [KEYLOCKDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_LOGO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_LOGO]  DEFAULT ((0)) FOR [LOGO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_LOGOALIGNMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_LOGOALIGNMENT]  DEFAULT ((0)) FOR [LOGOALIGNMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MANUALINPUTALLOWED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MANUALINPUTALLOWED]  DEFAULT ((0)) FOR [MANUALINPUTALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MAXINVOICELINES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MAXINVOICELINES]  DEFAULT ((0)) FOR [MAXINVOICELINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MICR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MICR]  DEFAULT ((0)) FOR [MICR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MICRDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MICRDESCRIPTION]  DEFAULT ('') FOR [MICRDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MICRDRIVERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MICRDRIVERNAME]  DEFAULT ('') FOR [MICRDRIVERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MSR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MSR]  DEFAULT ((0)) FOR [MSR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MSRDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MSRDESCRIPTION]  DEFAULT ('') FOR [MSRDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MSRDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MSRDEVICENAME]  DEFAULT ('') FOR [MSRDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MSRMAKE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MSRMAKE]  DEFAULT ('') FOR [MSRMAKE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MSRMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MSRMODEL]  DEFAULT ('') FOR [MSRMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PHARMACY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PHARMACY]  DEFAULT ((0)) FOR [PHARMACY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PHARMACYHOST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PHARMACYHOST]  DEFAULT ('') FOR [PHARMACYHOST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PHARMACYPORT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PHARMACYPORT]  DEFAULT ((0)) FOR [PHARMACYPORT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PINPAD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PINPAD]  DEFAULT ((0)) FOR [PINPAD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PINPADDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PINPADDESCRIPTION]  DEFAULT ('') FOR [PINPADDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PINPADDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PINPADDEVICENAME]  DEFAULT ('') FOR [PINPADDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PINPADMAKE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PINPADMAKE]  DEFAULT ('') FOR [PINPADMAKE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PINPADMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PINPADMODEL]  DEFAULT ('') FOR [PINPADMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTBINARYCONVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTBINARYCONVERSION]  DEFAULT ((0)) FOR [PRINTBINARYCONVERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER]  DEFAULT ((0)) FOR [PRINTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2]  DEFAULT ((0)) FOR [PRINTER2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2BINARYCONVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2BINARYCONVERSION]  DEFAULT ((0)) FOR [PRINTER2BINARYCONVERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2CHARACTERSET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2CHARACTERSET]  DEFAULT ((0)) FOR [PRINTER2CHARACTERSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2DESCRIPTION]  DEFAULT ('') FOR [PRINTER2DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2DEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2DEVICENAME]  DEFAULT ('') FOR [PRINTER2DEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2DOCINSERTREMOVALTIMEOUT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2DOCINSERTREMOVALTIMEOUT]  DEFAULT ((0)) FOR [PRINTER2DOCINSERTREMOVALTIMEOUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2LOGO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2LOGO]  DEFAULT ((0)) FOR [PRINTER2LOGO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2LOGOALIGNMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2LOGOALIGNMENT]  DEFAULT ((0)) FOR [PRINTER2LOGOALIGNMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2MAKE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2MAKE]  DEFAULT ('') FOR [PRINTER2MAKE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2MODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2MODEL]  DEFAULT ('') FOR [PRINTER2MODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTER2RECEIPTPROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTER2RECEIPTPROFILEID]  DEFAULT ('') FOR [PRINTER2RECEIPTPROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTERCHARACTERSET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTERCHARACTERSET]  DEFAULT ((0)) FOR [PRINTERCHARACTERSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTERDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTERDESCRIPTION]  DEFAULT ('') FOR [PRINTERDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTERDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTERDEVICENAME]  DEFAULT ('') FOR [PRINTERDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTERMAKE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTERMAKE]  DEFAULT ('') FOR [PRINTERMAKE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTERMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTERMODEL]  DEFAULT ('') FOR [PRINTERMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PRINTERRECEIPTPROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PRINTERRECEIPTPROFILEID]  DEFAULT ('') FOR [PRINTERRECEIPTPROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_PROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_PROFILEID]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_RFIDDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_RFIDDESCRIPTION]  DEFAULT ('') FOR [RFIDDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_RFIDDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_RFIDDEVICENAME]  DEFAULT ('') FOR [RFIDDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_RFIDSCANNERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_RFIDSCANNERTYPE]  DEFAULT ((0)) FOR [RFIDSCANNERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCALE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCALE]  DEFAULT ((0)) FOR [SCALE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCALEDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCALEDESCRIPTION]  DEFAULT ('') FOR [SCALEDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCALEDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCALEDEVICENAME]  DEFAULT ('') FOR [SCALEDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCANNER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCANNER]  DEFAULT ((0)) FOR [SCANNER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCANNER2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCANNER2]  DEFAULT ((0)) FOR [SCANNER2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCANNER2DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCANNER2DESCRIPTION]  DEFAULT ('') FOR [SCANNER2DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCANNER2DEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCANNER2DEVICENAME]  DEFAULT ('') FOR [SCANNER2DEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCANNERDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCANNERDESCRIPTION]  DEFAULT ('') FOR [SCANNERDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCANNERDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCANNERDEVICENAME]  DEFAULT ('') FOR [SCANNERDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SCREENKEYBOARD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SCREENKEYBOARD]  DEFAULT ((0)) FOR [SCREENKEYBOARD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SEPARATOR1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SEPARATOR1]  DEFAULT ('') FOR [SEPARATOR1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SHOWPICTURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SHOWPICTURE]  DEFAULT ((0)) FOR [SHOWPICTURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SIGCAP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SIGCAP]  DEFAULT ((0)) FOR [SIGCAP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SIGCAPDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SIGCAPDESCRIPTION]  DEFAULT ('') FOR [SIGCAPDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SIGCAPDEVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SIGCAPDEVICENAME]  DEFAULT ('') FOR [SIGCAPDEVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SIGCAPFORMNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SIGCAPFORMNAME]  DEFAULT ('') FOR [SIGCAPFORMNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SIGCAPMAKE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SIGCAPMAKE]  DEFAULT ('') FOR [SIGCAPMAKE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_SIGCAPMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_SIGCAPMODEL]  DEFAULT ('') FOR [SIGCAPMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_STARTTRACK1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_STARTTRACK1]  DEFAULT ('') FOR [STARTTRACK1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_STARTTRACK2AFTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_STARTTRACK2AFTER]  DEFAULT ((0)) FOR [STARTTRACK2AFTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_TIMEOUTINSEC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_TIMEOUTINSEC]  DEFAULT ((0)) FOR [TIMEOUTINSEC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILHARDWAREPROFILE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD  CONSTRAINT [DF_RETAILHARDWAREPROFILE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILHARDWAREPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILIMAGES]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILIMAGES](
[RECID] [bigint] NOT NULL,
[PICTURE] [varbinary](max) NULL,
[PICTUREID] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-588735509_1340322720] PRIMARY KEY CLUSTERED 
(
[PICTUREID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILIMAGES_PICTUREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILIMAGES] ADD  CONSTRAINT [DF_RETAILIMAGES_PICTUREID]  DEFAULT ((0)) FOR [PICTUREID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILIMAGES] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINCOMEEXPENSEACCOUNTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE](
[RECID] [bigint] NOT NULL,
[ACCOUNTNUM] [nvarchar](10) NOT NULL,
[ACCOUNTTYPE] [int] NOT NULL,
[MESSAGELINE1] [nvarchar](30) NOT NULL,
[MESSAGELINE2] [nvarchar](30) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[NAMEALIAS] [nvarchar](20) NOT NULL,
[SLIPTEXT1] [nvarchar](30) NOT NULL,
[SLIPTEXT2] [nvarchar](30) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[MODIFIEDTRANSACTIONID] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1430111471_-2115689213] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[ACCOUNTNUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_ACCOUNTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_ACCOUNTNUM]  DEFAULT ('') FOR [ACCOUNTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_ACCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_ACCOUNTTYPE]  DEFAULT ((0)) FOR [ACCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_MESSAGELINE1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_MESSAGELINE1]  DEFAULT ('') FOR [MESSAGELINE1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_MESSAGELINE2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_MESSAGELINE2]  DEFAULT ('') FOR [MESSAGELINE2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_NAMEALIAS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_NAMEALIAS]  DEFAULT ('') FOR [NAMEALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_SLIPTEXT1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_SLIPTEXT1]  DEFAULT ('') FOR [SLIPTEXT1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_SLIPTEXT2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_SLIPTEXT2]  DEFAULT ('') FOR [SLIPTEXT2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINCOMEEXPENSEACCOUNTTABLE_MODIFIEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] ADD  CONSTRAINT [DF_RETAILINCOMEEXPENSEACCOUNTTABLE_MODIFIEDTRANSACTIONID]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINCOMEEXPENSEACCOUNTTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFOCODE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFOCODE](
[RECID] [bigint] NOT NULL,
[INFOCODEID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1162389280_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1162389280_-1624030085] UNIQUE NONCLUSTERED 
(
[INFOCODEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODE_INFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODE] ADD  CONSTRAINT [DF_RETAILINFOCODE_INFOCODEID]  DEFAULT ('') FOR [INFOCODEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFOCODE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFOCODEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFOCODEGROUP](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[GROUPID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2072258145_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2072258145_1109132959] UNIQUE NONCLUSTERED 
(
[GROUPID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODEGROUP_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODEGROUP] ADD  CONSTRAINT [DF_RETAILINFOCODEGROUP_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODEGROUP_GROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODEGROUP] ADD  CONSTRAINT [DF_RETAILINFOCODEGROUP_GROUPID]  DEFAULT ('') FOR [GROUPID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFOCODEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFOCODEGROUPSPECIFIC]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFOCODEGROUPSPECIFIC](
[RECID] [bigint] NOT NULL,
[GROUPID] [nvarchar](10) NOT NULL,
[INFOCODEID] [nvarchar](10) NOT NULL,
[PRIORITY] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1342306497_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1342306497_887621465] UNIQUE NONCLUSTERED 
(
[GROUPID] ASC,
[INFOCODEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODEGROUPSPECIFIC_GROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODEGROUPSPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODEGROUPSPECIFIC_GROUPID]  DEFAULT ('') FOR [GROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODEGROUPSPECIFIC_INFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODEGROUPSPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODEGROUPSPECIFIC_INFOCODEID]  DEFAULT ('') FOR [INFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODEGROUPSPECIFIC_PRIORITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODEGROUPSPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODEGROUPSPECIFIC_PRIORITY]  DEFAULT ((0)) FOR [PRIORITY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFOCODEGROUPSPECIFIC] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFOCODETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFOCODETABLE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[INFOCODEID] [nvarchar](10) NOT NULL,
[INPUTREQUIRED] [int] NOT NULL,
[INPUTTYPE] [int] NOT NULL,
[LINKEDINFOCODEID] [nvarchar](10) NOT NULL,
[MAXIMUMLENGTH] [int] NOT NULL,
[MAXIMUMVALUE] [numeric](32, 16) NOT NULL,
[MINIMUMLENGTH] [int] NOT NULL,
[MINIMUMVALUE] [numeric](32, 16) NOT NULL,
[ONCEPERTRANSACTION] [int] NOT NULL,
[PRINTINPUTNAMEONRECEIPT] [int] NOT NULL,
[PRINTINPUTONRECEIPT] [int] NOT NULL,
[PRINTPROMPTONRECEIPT] [int] NOT NULL,
[PROMPT] [nvarchar](60) NOT NULL,
[RANDOMCOUNTER] [numeric](32, 16) NOT NULL,
[RANDOMFACTOR] [numeric](32, 16) NOT NULL,
[RETAILUSEINFOCODE] [int] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2047807304_-246962802] PRIMARY KEY CLUSTERED 
(
[INFOCODEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_INFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_INFOCODEID]  DEFAULT ('') FOR [INFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_INPUTREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_INPUTREQUIRED]  DEFAULT ((0)) FOR [INPUTREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_INPUTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_INPUTTYPE]  DEFAULT ((0)) FOR [INPUTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_LINKEDINFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_LINKEDINFOCODEID]  DEFAULT ('') FOR [LINKEDINFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_MAXIMUMLENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_MAXIMUMLENGTH]  DEFAULT ((0)) FOR [MAXIMUMLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_MAXIMUMVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_MAXIMUMVALUE]  DEFAULT ((0)) FOR [MAXIMUMVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_MINIMUMLENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_MINIMUMLENGTH]  DEFAULT ((0)) FOR [MINIMUMLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_MINIMUMVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_MINIMUMVALUE]  DEFAULT ((0)) FOR [MINIMUMVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_ONCEPERTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_ONCEPERTRANSACTION]  DEFAULT ((0)) FOR [ONCEPERTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_PRINTINPUTNAMEONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_PRINTINPUTNAMEONRECEIPT]  DEFAULT ((0)) FOR [PRINTINPUTNAMEONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_PRINTINPUTONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_PRINTINPUTONRECEIPT]  DEFAULT ((0)) FOR [PRINTINPUTONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_PRINTPROMPTONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_PRINTPROMPTONRECEIPT]  DEFAULT ((0)) FOR [PRINTPROMPTONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_PROMPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_PROMPT]  DEFAULT ('') FOR [PROMPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_RANDOMCOUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_RANDOMCOUNTER]  DEFAULT ((0)) FOR [RANDOMCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_RANDOMFACTOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_RANDOMFACTOR]  DEFAULT ((0)) FOR [RANDOMFACTOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_RETAILUSEINFOCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_RETAILUSEINFOCODE]  DEFAULT ((0)) FOR [RETAILUSEINFOCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLE] ADD  CONSTRAINT [DF_RETAILINFOCODETABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFOCODETABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFOCODETABLESPECIFIC]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFOCODETABLESPECIFIC](
[RECID] [bigint] NOT NULL,
[INFOCODEID] [nvarchar](10) NOT NULL,
[INPUTREQUIRED] [int] NOT NULL,
[REFRELATION] [nvarchar](64) NOT NULL,
[REFRELATION2] [nvarchar](64) NOT NULL,
[REFRELATION3] [nvarchar](64) NOT NULL,
[REFTABLEID] [int] NOT NULL,
[SEQUENCE] [int] NOT NULL,
[WHENREQUIRED] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_798844888_-1498359599] PRIMARY KEY CLUSTERED 
(
[REFTABLEID] ASC,
[REFRELATION] ASC,
[REFRELATION2] ASC,
[REFRELATION3] ASC,
[INFOCODEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_INFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_INFOCODEID]  DEFAULT ('') FOR [INFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_INPUTREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_INPUTREQUIRED]  DEFAULT ((0)) FOR [INPUTREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_REFRELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_REFRELATION]  DEFAULT ('') FOR [REFRELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_REFRELATION2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_REFRELATION2]  DEFAULT ('') FOR [REFRELATION2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_REFRELATION3]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_REFRELATION3]  DEFAULT ('') FOR [REFRELATION3]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_REFTABLEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_REFTABLEID]  DEFAULT ((0)) FOR [REFTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_SEQUENCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_SEQUENCE]  DEFAULT ((0)) FOR [SEQUENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETABLESPECIFIC_WHENREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETABLESPECIFIC] ADD  CONSTRAINT [DF_RETAILINFOCODETABLESPECIFIC_WHENREQUIRED]  DEFAULT ((0)) FOR [WHENREQUIRED]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFOCODETABLESPECIFIC] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFOCODETRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFOCODETRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[INFOCODE] [bigint] NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[PROMPT] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_202291299_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_202291299_1070488980] UNIQUE NONCLUSTERED 
(
[INFOCODE] ASC,
[LANGUAGEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETRANSLATION] ADD  CONSTRAINT [DF_RETAILINFOCODETRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETRANSLATION_INFOCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETRANSLATION] ADD  CONSTRAINT [DF_RETAILINFOCODETRANSLATION_INFOCODE]  DEFAULT ((0)) FOR [INFOCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETRANSLATION] ADD  CONSTRAINT [DF_RETAILINFOCODETRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFOCODETRANSLATION_PROMPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFOCODETRANSLATION] ADD  CONSTRAINT [DF_RETAILINFOCODETRANSLATION_PROMPT]  DEFAULT ('') FOR [PROMPT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFOCODETRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFORMATIONSUBCODETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFORMATIONSUBCODETABLE](
[RECID] [bigint] NOT NULL,
[AMOUNTPERCENT] [numeric](32, 16) NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[INFOCODEID] [nvarchar](10) NOT NULL,
[NEWSALESLINE] [int] NOT NULL,
[PRICETYPE] [int] NOT NULL,
[SUBCODEID] [nvarchar](10) NOT NULL,
[TRIGGERCODE] [nvarchar](20) NOT NULL,
[TRIGGERFUNCTION] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2013310740_1087960115] PRIMARY KEY CLUSTERED 
(
[INFOCODEID] ASC,
[SUBCODEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_AMOUNTPERCENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_AMOUNTPERCENT]  DEFAULT ((0)) FOR [AMOUNTPERCENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_INFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_INFOCODEID]  DEFAULT ('') FOR [INFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_NEWSALESLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_NEWSALESLINE]  DEFAULT ((0)) FOR [NEWSALESLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_PRICETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_PRICETYPE]  DEFAULT ((0)) FOR [PRICETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_SUBCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_SUBCODEID]  DEFAULT ('') FOR [SUBCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_TRIGGERCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_TRIGGERCODE]  DEFAULT ('') FOR [TRIGGERCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETABLE_TRIGGERFUNCTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETABLE] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETABLE_TRIGGERFUNCTION]  DEFAULT ((0)) FOR [TRIGGERFUNCTION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFORMATIONSUBCODETABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINFORMATIONSUBCODETRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINFORMATIONSUBCODETRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[INFOSUBCODE] [bigint] NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1974585269_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1974585269_-310291638] UNIQUE NONCLUSTERED 
(
[INFOSUBCODE] ASC,
[LANGUAGEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETRANSLATION] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETRANSLATION_INFOSUBCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETRANSLATION] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETRANSLATION_INFOSUBCODE]  DEFAULT ((0)) FOR [INFOSUBCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINFORMATIONSUBCODETRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINFORMATIONSUBCODETRANSLATION] ADD  CONSTRAINT [DF_RETAILINFORMATIONSUBCODETRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINFORMATIONSUBCODETRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINTERNALORGANIZATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINTERNALORGANIZATION](
[RECID] [bigint] NOT NULL,
[INTERNALORGANIZATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_423793179_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_423793179_1393859730] UNIQUE NONCLUSTERED 
(
[INTERNALORGANIZATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINTERNALORGANIZATION_INTERNALORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINTERNALORGANIZATION] ADD  CONSTRAINT [DF_RETAILINTERNALORGANIZATION_INTERNALORGANIZATION]  DEFAULT ((0)) FOR [INTERNALORGANIZATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINTERNALORGANIZATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINVENTAVAILABILITY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINVENTAVAILABILITY](
[RECID] [bigint] NOT NULL,
[AVAILPHYSICAL] [numeric](32, 16) NOT NULL,
[INVENTDIMRECID] [bigint] NOT NULL,
[ITEMRECID] [bigint] NOT NULL,
[LASTINVENTTRANS] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-155348074_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-155348074_789383996] UNIQUE NONCLUSTERED 
(
[ITEMRECID] ASC,
[INVENTDIMRECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTAVAILABILITY_AVAILPHYSICAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTAVAILABILITY] ADD  CONSTRAINT [DF_RETAILINVENTAVAILABILITY_AVAILPHYSICAL]  DEFAULT ((0)) FOR [AVAILPHYSICAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTAVAILABILITY_INVENTDIMRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTAVAILABILITY] ADD  CONSTRAINT [DF_RETAILINVENTAVAILABILITY_INVENTDIMRECID]  DEFAULT ((0)) FOR [INVENTDIMRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTAVAILABILITY_ITEMRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTAVAILABILITY] ADD  CONSTRAINT [DF_RETAILINVENTAVAILABILITY_ITEMRECID]  DEFAULT ((0)) FOR [ITEMRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTAVAILABILITY_LASTINVENTTRANS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTAVAILABILITY] ADD  CONSTRAINT [DF_RETAILINVENTAVAILABILITY_LASTINVENTTRANS]  DEFAULT ((0)) FOR [LASTINVENTTRANS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINVENTAVAILABILITY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINVENTLINKEDITEM]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINVENTLINKEDITEM](
[RECID] [bigint] NOT NULL,
[BLOCKED] [int] NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[LINKEDITEMID] [nvarchar](20) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[UNIT] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-126780815_-221054464] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[UNIT] ASC,
[LINKEDITEMID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTLINKEDITEM_BLOCKED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTLINKEDITEM] ADD  CONSTRAINT [DF_RETAILINVENTLINKEDITEM_BLOCKED]  DEFAULT ((0)) FOR [BLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTLINKEDITEM_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTLINKEDITEM] ADD  CONSTRAINT [DF_RETAILINVENTLINKEDITEM_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTLINKEDITEM_LINKEDITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTLINKEDITEM] ADD  CONSTRAINT [DF_RETAILINVENTLINKEDITEM_LINKEDITEMID]  DEFAULT ('') FOR [LINKEDITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTLINKEDITEM_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTLINKEDITEM] ADD  CONSTRAINT [DF_RETAILINVENTLINKEDITEM_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTLINKEDITEM_UNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTLINKEDITEM] ADD  CONSTRAINT [DF_RETAILINVENTLINKEDITEM_UNIT]  DEFAULT ('') FOR [UNIT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINVENTLINKEDITEM] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILINVENTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILINVENTTABLE](
[RECID] [bigint] NOT NULL,
[BARCODESETUPID] [nvarchar](10) NOT NULL,
[BASECOMPARISONUNITCODE] [nvarchar](10) NOT NULL,
[BLOCKEDONPOS] [int] NOT NULL,
[DATEBLOCKED] [date] NOT NULL,
[DATETOACTIVATEITEM] [date] NOT NULL,
[DATETOBEBLOCKED] [date] NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[KEYINGINPRICE] [int] NOT NULL,
[KEYINGINQTY] [int] NOT NULL,
[MUSTKEYINCOMMENT] [int] NOT NULL,
[NODISCOUNTALLOWED] [int] NOT NULL,
[PRINTVARIANTSSHELFLABELS] [int] NOT NULL,
[PROHIBITRETURN_RU] [int] NOT NULL,
[QTYBECOMESNEGATIVE] [int] NOT NULL,
[SCALEITEM] [int] NOT NULL,
[USEEANSTANDARDBARCODE] [int] NOT NULL,
[ZEROPRICEVALID] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1553584605_1428044496] PRIMARY KEY CLUSTERED 
(
[ITEMID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_BARCODESETUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_BARCODESETUPID]  DEFAULT ('') FOR [BARCODESETUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_BASECOMPARISONUNITCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_BASECOMPARISONUNITCODE]  DEFAULT ('') FOR [BASECOMPARISONUNITCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_BLOCKEDONPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_BLOCKEDONPOS]  DEFAULT ((0)) FOR [BLOCKEDONPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_DATEBLOCKED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_DATEBLOCKED]  DEFAULT ('1900-01-01') FOR [DATEBLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_DATETOACTIVATEITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_DATETOACTIVATEITEM]  DEFAULT ('1900-01-01') FOR [DATETOACTIVATEITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_DATETOBEBLOCKED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_DATETOBEBLOCKED]  DEFAULT ('1900-01-01') FOR [DATETOBEBLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_KEYINGINPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_KEYINGINPRICE]  DEFAULT ((0)) FOR [KEYINGINPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_KEYINGINQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_KEYINGINQTY]  DEFAULT ((0)) FOR [KEYINGINQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_MUSTKEYINCOMMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_MUSTKEYINCOMMENT]  DEFAULT ((0)) FOR [MUSTKEYINCOMMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_NODISCOUNTALLOWED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_NODISCOUNTALLOWED]  DEFAULT ((0)) FOR [NODISCOUNTALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_PRINTVARIANTSSHELFLABELS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_PRINTVARIANTSSHELFLABELS]  DEFAULT ((0)) FOR [PRINTVARIANTSSHELFLABELS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_PROHIBITRETURN_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_PROHIBITRETURN_RU]  DEFAULT ((0)) FOR [PROHIBITRETURN_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_QTYBECOMESNEGATIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_QTYBECOMESNEGATIVE]  DEFAULT ((0)) FOR [QTYBECOMESNEGATIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_SCALEITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_SCALEITEM]  DEFAULT ((0)) FOR [SCALEITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_USEEANSTANDARDBARCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_USEEANSTANDARDBARCODE]  DEFAULT ((0)) FOR [USEEANSTANDARDBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILINVENTTABLE_ZEROPRICEVALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILINVENTTABLE] ADD  CONSTRAINT [DF_RETAILINVENTTABLE_ZEROPRICEVALID]  DEFAULT ((0)) FOR [ZEROPRICEVALID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILINVENTTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILJOBPOSPERMISSIONGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILJOBPOSPERMISSIONGROUP](
[RECID] [bigint] NOT NULL,
[JOB] [bigint] NOT NULL,
[RETAILPOSPERMISSIONGROUP] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_495795012_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_495795012_-384136432] UNIQUE NONCLUSTERED 
(
[JOB] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILJOBPOSPERMISSIONGROUP_JOB]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILJOBPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILJOBPOSPERMISSIONGROUP_JOB]  DEFAULT ((0)) FOR [JOB]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILJOBPOSPERMISSIONGROUP_RETAILPOSPERMISSIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILJOBPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILJOBPOSPERMISSIONGROUP_RETAILPOSPERMISSIONGROUP]  DEFAULT ((0)) FOR [RETAILPOSPERMISSIONGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILJOBPOSPERMISSIONGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKEYBOARDBUTTONCONTROL]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKEYBOARDBUTTONCONTROL](
[RECID] [bigint] NOT NULL,
[BUTTONCONTROLID] [int] NOT NULL,
[DEFAULTCOLOR] [nvarchar](10) NOT NULL,
[DEFAULTFONT] [nvarchar](32) NOT NULL,
[DEFAULTFONTSIZE] [int] NOT NULL,
[DEFAULTFONTSTYLE] [int] NOT NULL,
[NAME] [nvarchar](50) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_316740147_-1011273354] PRIMARY KEY CLUSTERED 
(
[BUTTONCONTROLID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROL_BUTTONCONTROLID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROL] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROL_BUTTONCONTROLID]  DEFAULT ((0)) FOR [BUTTONCONTROLID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTCOLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROL] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTCOLOR]  DEFAULT ('') FOR [DEFAULTCOLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTFONT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROL] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTFONT]  DEFAULT ('') FOR [DEFAULTFONT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTFONTSIZE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROL] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTFONTSIZE]  DEFAULT ((0)) FOR [DEFAULTFONTSIZE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTFONTSTYLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROL] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROL_DEFAULTFONTSTYLE]  DEFAULT ((0)) FOR [DEFAULTFONTSTYLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROL_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROL] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROL_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKEYBOARDBUTTONCONTROL] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKEYBOARDBUTTONCONTROLB]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB](
[RECID] [bigint] NOT NULL,
[ACTION] [int] NOT NULL,
[ACTIONPROPERTY] [nvarchar](1000) NOT NULL,
[BUTTONCONTROLID] [int] NOT NULL,
[COLOUR] [nvarchar](20) NOT NULL,
[DISPLAYTEXT] [nvarchar](50) NOT NULL,
[FONTSIZE] [int] NOT NULL,
[FONTSTYLE] [int] NOT NULL,
[ID] [int] NOT NULL,
[PICTURE] [nvarchar](max) NULL,
[ROWNUM] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_876263485_-594239886] PRIMARY KEY CLUSTERED 
(
[ID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_ACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_ACTION]  DEFAULT ((0)) FOR [ACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_ACTIONPROPERTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_ACTIONPROPERTY]  DEFAULT ('') FOR [ACTIONPROPERTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_BUTTONCONTROLID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_BUTTONCONTROLID]  DEFAULT ((0)) FOR [BUTTONCONTROLID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_COLOUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_COLOUR]  DEFAULT ('') FOR [COLOUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_DISPLAYTEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_DISPLAYTEXT]  DEFAULT ('') FOR [DISPLAYTEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_FONTSIZE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_FONTSIZE]  DEFAULT ((0)) FOR [FONTSIZE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_FONTSTYLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_FONTSTYLE]  DEFAULT ((0)) FOR [FONTSTYLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_ID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_ID]  DEFAULT ((0)) FOR [ID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDBUTTONCONTROLB_ROWNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDBUTTONCONTROLB] ADD  CONSTRAINT [DF_RETAILKEYBOARDBUTTONCONTROLB_ROWNUM]  DEFAULT ((0)) FOR [ROWNUM]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKEYBOARDBUTTONCONTROLB] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKEYBOARDMAPPINGTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKEYBOARDMAPPINGTABLE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[KEYBOARDMAPPINGID] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1200005738_96064522] PRIMARY KEY CLUSTERED 
(
[KEYBOARDMAPPINGID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDMAPPINGTABLE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDMAPPINGTABLE] ADD  CONSTRAINT [DF_RETAILKEYBOARDMAPPINGTABLE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDMAPPINGTABLE_KEYBOARDMAPPINGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDMAPPINGTABLE] ADD  CONSTRAINT [DF_RETAILKEYBOARDMAPPINGTABLE_KEYBOARDMAPPINGID]  DEFAULT ('') FOR [KEYBOARDMAPPINGID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKEYBOARDMAPPINGTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKEYBOARDMAPPINGTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKEYBOARDMAPPINGTRANS](
[RECID] [bigint] NOT NULL,
[ACTION] [int] NOT NULL,
[ACTIONPROPERTY] [nvarchar](1000) NOT NULL,
[ASCIIVALUE] [int] NOT NULL,
[KEYBOARDMAPPINGID] [nvarchar](10) NOT NULL,
[KEYCHAR] [nchar](1) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1979216936_-159151230] PRIMARY KEY CLUSTERED 
(
[KEYBOARDMAPPINGID] ASC,
[ASCIIVALUE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDMAPPINGTRANS_ACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDMAPPINGTRANS] ADD  CONSTRAINT [DF_RETAILKEYBOARDMAPPINGTRANS_ACTION]  DEFAULT ((0)) FOR [ACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDMAPPINGTRANS_ACTIONPROPERTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDMAPPINGTRANS] ADD  CONSTRAINT [DF_RETAILKEYBOARDMAPPINGTRANS_ACTIONPROPERTY]  DEFAULT ('') FOR [ACTIONPROPERTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDMAPPINGTRANS_ASCIIVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDMAPPINGTRANS] ADD  CONSTRAINT [DF_RETAILKEYBOARDMAPPINGTRANS_ASCIIVALUE]  DEFAULT ((0)) FOR [ASCIIVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDMAPPINGTRANS_KEYBOARDMAPPINGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDMAPPINGTRANS] ADD  CONSTRAINT [DF_RETAILKEYBOARDMAPPINGTRANS_KEYBOARDMAPPINGID]  DEFAULT ('') FOR [KEYBOARDMAPPINGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKEYBOARDMAPPINGTRANS_KEYCHAR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKEYBOARDMAPPINGTRANS] ADD  CONSTRAINT [DF_RETAILKEYBOARDMAPPINGTRANS_KEYCHAR]  DEFAULT ('') FOR [KEYCHAR]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKEYBOARDMAPPINGTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKIT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKIT](
[RECID] [bigint] NOT NULL,
[DISASSEMBLYATREGISTERALLOWED] [int] NOT NULL,
[DISCONTINUEKIT] [int] NOT NULL,
[PRODUCTMASTER] [bigint] NOT NULL,
[STATUS] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_209556489_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_209556489_1729947418] UNIQUE NONCLUSTERED 
(
[PRODUCTMASTER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKIT_DISASSEMBLYATREGISTERALLOWED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKIT] ADD  CONSTRAINT [DF_RETAILKIT_DISASSEMBLYATREGISTERALLOWED]  DEFAULT ((0)) FOR [DISASSEMBLYATREGISTERALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKIT_DISCONTINUEKIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKIT] ADD  CONSTRAINT [DF_RETAILKIT_DISCONTINUEKIT]  DEFAULT ((0)) FOR [DISCONTINUEKIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKIT_PRODUCTMASTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKIT] ADD  CONSTRAINT [DF_RETAILKIT_PRODUCTMASTER]  DEFAULT ((0)) FOR [PRODUCTMASTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKIT_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKIT] ADD  CONSTRAINT [DF_RETAILKIT_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKIT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKITCOMPONENT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKITCOMPONENT](
[RECID] [bigint] NOT NULL,
[COMPONENT] [bigint] NOT NULL,
[DONOTSHOWATREGISTER] [int] NOT NULL,
[KIT] [bigint] NOT NULL,
[QUANTITY] [numeric](32, 16) NOT NULL,
[UNITOFMEASURE] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_816282606_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENT_COMPONENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITCOMPONENT_COMPONENT]  DEFAULT ((0)) FOR [COMPONENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENT_DONOTSHOWATREGISTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITCOMPONENT_DONOTSHOWATREGISTER]  DEFAULT ((0)) FOR [DONOTSHOWATREGISTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENT_KIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITCOMPONENT_KIT]  DEFAULT ((0)) FOR [KIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENT_QUANTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITCOMPONENT_QUANTITY]  DEFAULT ((0)) FOR [QUANTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENT_UNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITCOMPONENT_UNITOFMEASURE]  DEFAULT ((0)) FOR [UNITOFMEASURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENT_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITCOMPONENT_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENT_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITCOMPONENT_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKITCOMPONENT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKITCOMPONENTSUBSTITUTE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKITCOMPONENTSUBSTITUTE](
[RECID] [bigint] NOT NULL,
[KITCOMPONENT] [bigint] NOT NULL,
[QUANTITY] [numeric](32, 16) NOT NULL,
[SUBSTITUTEPRODUCT] [bigint] NOT NULL,
[UNITOFMEASURE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1352945126_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1352945126_160563956] UNIQUE NONCLUSTERED 
(
[KITCOMPONENT] ASC,
[SUBSTITUTEPRODUCT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENTSUBSTITUTE_KITCOMPONENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENTSUBSTITUTE] ADD  CONSTRAINT [DF_RETAILKITCOMPONENTSUBSTITUTE_KITCOMPONENT]  DEFAULT ((0)) FOR [KITCOMPONENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENTSUBSTITUTE_QUANTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENTSUBSTITUTE] ADD  CONSTRAINT [DF_RETAILKITCOMPONENTSUBSTITUTE_QUANTITY]  DEFAULT ((0)) FOR [QUANTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENTSUBSTITUTE_SUBSTITUTEPRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENTSUBSTITUTE] ADD  CONSTRAINT [DF_RETAILKITCOMPONENTSUBSTITUTE_SUBSTITUTEPRODUCT]  DEFAULT ((0)) FOR [SUBSTITUTEPRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITCOMPONENTSUBSTITUTE_UNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITCOMPONENTSUBSTITUTE] ADD  CONSTRAINT [DF_RETAILKITCOMPONENTSUBSTITUTE_UNITOFMEASURE]  DEFAULT ((0)) FOR [UNITOFMEASURE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKITCOMPONENTSUBSTITUTE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKITRELEASEDSUBSTITUTECHARGE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKITRELEASEDSUBSTITUTECHARGE](
[RECID] [bigint] NOT NULL,
[KITCOMPONENTSUBSTITUTE] [bigint] NOT NULL,
[SUBSTITUTECHARGE] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1490136328_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITRELEASEDSUBSTITUTECHARGE_KITCOMPONENTSUBSTITUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITRELEASEDSUBSTITUTECHARGE] ADD  CONSTRAINT [DF_RETAILKITRELEASEDSUBSTITUTECHARGE_KITCOMPONENTSUBSTITUTE]  DEFAULT ((0)) FOR [KITCOMPONENTSUBSTITUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITRELEASEDSUBSTITUTECHARGE_SUBSTITUTECHARGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITRELEASEDSUBSTITUTECHARGE] ADD  CONSTRAINT [DF_RETAILKITRELEASEDSUBSTITUTECHARGE_SUBSTITUTECHARGE]  DEFAULT ((0)) FOR [SUBSTITUTECHARGE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKITRELEASEDSUBSTITUTECHARGE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILKITVARIANTCOMPONENT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILKITVARIANTCOMPONENT](
[RECID] [bigint] NOT NULL,
[COMPONENT] [bigint] NOT NULL,
[COMPONENTRECID] [bigint] NOT NULL,
[KITVARIANT] [bigint] NOT NULL,
[QUANTITY] [numeric](32, 16) NOT NULL,
[UNITOFMEASURE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1748165813_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1748165813_1499849031] UNIQUE NONCLUSTERED 
(
[KITVARIANT] ASC,
[COMPONENT] ASC,
[COMPONENTRECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITVARIANTCOMPONENT_COMPONENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITVARIANTCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITVARIANTCOMPONENT_COMPONENT]  DEFAULT ((0)) FOR [COMPONENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITVARIANTCOMPONENT_COMPONENTRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITVARIANTCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITVARIANTCOMPONENT_COMPONENTRECID]  DEFAULT ((0)) FOR [COMPONENTRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITVARIANTCOMPONENT_KITVARIANT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITVARIANTCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITVARIANTCOMPONENT_KITVARIANT]  DEFAULT ((0)) FOR [KITVARIANT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITVARIANTCOMPONENT_QUANTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITVARIANTCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITVARIANTCOMPONENT_QUANTITY]  DEFAULT ((0)) FOR [QUANTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILKITVARIANTCOMPONENT_UNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILKITVARIANTCOMPONENT] ADD  CONSTRAINT [DF_RETAILKITVARIANTCOMPONENT_UNITOFMEASURE]  DEFAULT ((0)) FOR [UNITOFMEASURE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILKITVARIANTCOMPONENT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLANGUAGETEXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLANGUAGETEXT](
[RECID] [bigint] NOT NULL,
[ACTIVE] [int] NOT NULL,
[DATECREATED] [date] NOT NULL,
[DATEUPDATED] [date] NOT NULL,
[ERRORTEXT] [int] NOT NULL,
[FIRSTINVERSION] [nvarchar](20) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[MODULEID] [int] NOT NULL,
[TEXT] [nvarchar](250) NOT NULL,
[TEXTID] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1986448268_2004151621] PRIMARY KEY CLUSTERED 
(
[LANGUAGEID] ASC,
[TEXTID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_ACTIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_ACTIVE]  DEFAULT ((0)) FOR [ACTIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_DATECREATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_DATECREATED]  DEFAULT ('1900-01-01') FOR [DATECREATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_DATEUPDATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_DATEUPDATED]  DEFAULT ('1900-01-01') FOR [DATEUPDATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_ERRORTEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_ERRORTEXT]  DEFAULT ((0)) FOR [ERRORTEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_FIRSTINVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_FIRSTINVERSION]  DEFAULT ('') FOR [FIRSTINVERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_MODULEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_MODULEID]  DEFAULT ((0)) FOR [MODULEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_TEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_TEXT]  DEFAULT ('') FOR [TEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLANGUAGETEXT_TEXTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLANGUAGETEXT] ADD  CONSTRAINT [DF_RETAILLANGUAGETEXT_TEXTID]  DEFAULT ((0)) FOR [TEXTID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLANGUAGETEXT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLISTINGSTATUSLOG]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLISTINGSTATUSLOG](
[ACTIONSTATUS] [int] NOT NULL,
[APPLIEDACTION] [int] NOT NULL,
[CATALOG] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CHANNELLISTINGID] [nvarchar](50) NOT NULL,
[LISTINGMODIFIEDDATETIME] [datetime] NOT NULL,
[LISTINGMODIFIEDDATETIMETZID] [int] NOT NULL,
[PROCESSED] [int] NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STATUSDATETIME] [datetime] NOT NULL,
[STATUSDATETIMETZID] [int] NOT NULL,
[STATUSMESSAGE] [nvarchar](2048) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2129744063_-2139665100] PRIMARY KEY CLUSTERED 
(
[PRODUCT] ASC,
[CATALOG] ASC,
[CHANNEL] ASC,
[LISTINGMODIFIEDDATETIME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILLISTINGSTATUSLOG_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_ACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_ACTIONSTATUS]  DEFAULT ((0)) FOR [ACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_APPLIEDACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_APPLIEDACTION]  DEFAULT ((0)) FOR [APPLIEDACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_CATALOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_CATALOG]  DEFAULT ((0)) FOR [CATALOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_CHANNELLISTINGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_CHANNELLISTINGID]  DEFAULT ('') FOR [CHANNELLISTINGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [LISTINGMODIFIEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIMETZID]  DEFAULT ((37001)) FOR [LISTINGMODIFIEDDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_PROCESSED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_PROCESSED]  DEFAULT ((0)) FOR [PROCESSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_STATUSDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_STATUSDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [STATUSDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_STATUSDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_STATUSDATETIMETZID]  DEFAULT ((37001)) FOR [STATUSDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLISTINGSTATUSLOG_STATUSMESSAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD  CONSTRAINT [DF_RETAILLISTINGSTATUSLOG_STATUSMESSAGE]  DEFAULT ('') FOR [STATUSMESSAGE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLISTINGSTATUSLOG] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOG]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOG](
[CODEUNIT] [nvarchar](100) NOT NULL,
[DURATIONINMILLISEC] [int] NOT NULL,
[LOGDATE] [date] NOT NULL,
[LOGLEVEL] [int] NOT NULL,
[LOGSTRING] [nvarchar](max) NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[RETAILLOGID] [bigint] NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1372356043_-1275116490] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[RETAILLOGID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILLOG_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOG_CODEUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOG] ADD  CONSTRAINT [DF_RETAILLOG_CODEUNIT]  DEFAULT ('') FOR [CODEUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOG_DURATIONINMILLISEC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOG] ADD  CONSTRAINT [DF_RETAILLOG_DURATIONINMILLISEC]  DEFAULT ((0)) FOR [DURATIONINMILLISEC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOG_LOGDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOG] ADD  CONSTRAINT [DF_RETAILLOG_LOGDATE]  DEFAULT ('1900-01-01') FOR [LOGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOG_LOGLEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOG] ADD  CONSTRAINT [DF_RETAILLOG_LOGLEVEL]  DEFAULT ((0)) FOR [LOGLEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOG_RETAILLOGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOG] ADD  CONSTRAINT [DF_RETAILLOG_RETAILLOGID]  DEFAULT ((0)) FOR [RETAILLOGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOG_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOG] ADD  CONSTRAINT [DF_RETAILLOG_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOG_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOG] ADD  CONSTRAINT [DF_RETAILLOG_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOG] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYCARD]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYCARD](
[RECID] [bigint] NOT NULL,
[CARDNUMBER] [nvarchar](30) NOT NULL,
[CARDTENDERTYPE] [int] NOT NULL,
[PARTY] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_162050765_-700086456] PRIMARY KEY CLUSTERED 
(
[CARDNUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARD_CARDNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARD] ADD  CONSTRAINT [DF_RETAILLOYALTYCARD_CARDNUMBER]  DEFAULT ('') FOR [CARDNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARD_CARDTENDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARD] ADD  CONSTRAINT [DF_RETAILLOYALTYCARD_CARDTENDERTYPE]  DEFAULT ((0)) FOR [CARDTENDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARD_PARTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARD] ADD  CONSTRAINT [DF_RETAILLOYALTYCARD_PARTY]  DEFAULT ((0)) FOR [PARTY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYCARD] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYCARDTIER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYCARDTIER](
[RECID] [bigint] NOT NULL,
[AFFILIATION] [bigint] NOT NULL,
[LOYALTYCARD] [bigint] NOT NULL,
[LOYALTYTIER] [bigint] NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1091320793_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARDTIER_AFFILIATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARDTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYCARDTIER_AFFILIATION]  DEFAULT ((0)) FOR [AFFILIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARDTIER_LOYALTYCARD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARDTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYCARDTIER_LOYALTYCARD]  DEFAULT ((0)) FOR [LOYALTYCARD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARDTIER_LOYALTYTIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARDTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYCARDTIER_LOYALTYTIER]  DEFAULT ((0)) FOR [LOYALTYTIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARDTIER_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARDTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYCARDTIER_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYCARDTIER_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYCARDTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYCARDTIER_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYCARDTIER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYEARNSCHEMELINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE](
[RECID] [bigint] NOT NULL,
[FROMACTIVITYAMOUNTCURRENCY] [nvarchar](3) NOT NULL,
[FROMACTIVITYAMOUNTQTY] [numeric](32, 16) NOT NULL,
[FROMACTIVITYRETAILGROUPMEMBERLINE] [bigint] NOT NULL,
[FROMACTIVITYTYPE] [int] NOT NULL,
[LOYALTYSCHEME] [bigint] NOT NULL,
[LOYALTYTIER] [bigint] NOT NULL,
[TOREWARDPOINT] [bigint] NOT NULL,
[TOREWARDPOINTAMOUNTQTY] [numeric](32, 16) NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-818822738_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYAMOUNTCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYAMOUNTCURRENCY]  DEFAULT ('') FOR [FROMACTIVITYAMOUNTCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYAMOUNTQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYAMOUNTQTY]  DEFAULT ((0)) FOR [FROMACTIVITYAMOUNTQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYRETAILGROUPMEMBERLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYRETAILGROUPMEMBERLINE]  DEFAULT ((0)) FOR [FROMACTIVITYRETAILGROUPMEMBERLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_FROMACTIVITYTYPE]  DEFAULT ((0)) FOR [FROMACTIVITYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_LOYALTYSCHEME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_LOYALTYSCHEME]  DEFAULT ((0)) FOR [LOYALTYSCHEME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_LOYALTYTIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_LOYALTYTIER]  DEFAULT ((0)) FOR [LOYALTYTIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_TOREWARDPOINT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_TOREWARDPOINT]  DEFAULT ((0)) FOR [TOREWARDPOINT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_TOREWARDPOINTAMOUNTQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_TOREWARDPOINTAMOUNTQTY]  DEFAULT ((0)) FOR [TOREWARDPOINTAMOUNTQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYEARNSCHEMELINE_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYEARNSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYEARNSCHEMELINE_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYEARNSCHEMELINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYREDEEMSCHEMELINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE](
[RECID] [bigint] NOT NULL,
[FROMREWARDPOINT] [bigint] NOT NULL,
[FROMREWARDPOINTAMOUNTQTY] [numeric](32, 16) NOT NULL,
[LOYALTYSCHEME] [bigint] NOT NULL,
[LOYALTYTIER] [bigint] NOT NULL,
[TORETAILGROUPMEMBERLINE] [bigint] NOT NULL,
[TOREWARDAMOUNTCURRENCY] [nvarchar](3) NOT NULL,
[TOREWARDAMOUNTQTY] [numeric](32, 16) NOT NULL,
[TOREWARDTYPE] [int] NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1369333272_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_FROMREWARDPOINT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_FROMREWARDPOINT]  DEFAULT ((0)) FOR [FROMREWARDPOINT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_FROMREWARDPOINTAMOUNTQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_FROMREWARDPOINTAMOUNTQTY]  DEFAULT ((0)) FOR [FROMREWARDPOINTAMOUNTQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_LOYALTYSCHEME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_LOYALTYSCHEME]  DEFAULT ((0)) FOR [LOYALTYSCHEME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_LOYALTYTIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_LOYALTYTIER]  DEFAULT ((0)) FOR [LOYALTYTIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_TORETAILGROUPMEMBERLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_TORETAILGROUPMEMBERLINE]  DEFAULT ((0)) FOR [TORETAILGROUPMEMBERLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_TOREWARDAMOUNTCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_TOREWARDAMOUNTCURRENCY]  DEFAULT ('') FOR [TOREWARDAMOUNTCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_TOREWARDAMOUNTQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_TOREWARDAMOUNTQTY]  DEFAULT ((0)) FOR [TOREWARDAMOUNTQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_TOREWARDTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_TOREWARDTYPE]  DEFAULT ((0)) FOR [TOREWARDTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREDEEMSCHEMELINE_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREDEEMSCHEMELINE] ADD  CONSTRAINT [DF_RETAILLOYALTYREDEEMSCHEMELINE_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYREDEEMSCHEMELINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYREWARDPOINT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYREWARDPOINT](
[RECID] [bigint] NOT NULL,
[EXPIRATIONTIMEUNIT] [int] NOT NULL,
[EXPIRATIONTIMEVALUE] [int] NOT NULL,
[REDEEMABLE] [int] NOT NULL,
[REDEEMRANKING] [int] NOT NULL,
[REWARDPOINTCURRENCY] [nvarchar](3) NOT NULL,
[REWARDPOINTID] [nvarchar](64) NOT NULL,
[REWARDPOINTTYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_493823852_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_493823852_315656331] UNIQUE NONCLUSTERED 
(
[REWARDPOINTID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINT_EXPIRATIONTIMEUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINT] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINT_EXPIRATIONTIMEUNIT]  DEFAULT ((0)) FOR [EXPIRATIONTIMEUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINT_EXPIRATIONTIMEVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINT] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINT_EXPIRATIONTIMEVALUE]  DEFAULT ((0)) FOR [EXPIRATIONTIMEVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINT_REDEEMABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINT] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINT_REDEEMABLE]  DEFAULT ((0)) FOR [REDEEMABLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINT_REDEEMRANKING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINT] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINT_REDEEMRANKING]  DEFAULT ((0)) FOR [REDEEMRANKING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINT_REWARDPOINTCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINT] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINT_REWARDPOINTCURRENCY]  DEFAULT ('') FOR [REWARDPOINTCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINT_REWARDPOINTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINT] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINT_REWARDPOINTID]  DEFAULT ('') FOR [REWARDPOINTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINT_REWARDPOINTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINT] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINT_REWARDPOINTTYPE]  DEFAULT ((0)) FOR [REWARDPOINTTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYREWARDPOINT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYREWARDPOINTTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYREWARDPOINTTRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[REWARDPOINT] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1988105865_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1988105865_1050693241] UNIQUE NONCLUSTERED 
(
[LANGUAGEID] ASC,
[REWARDPOINT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINTTRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINTTRANSLATION] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINTTRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINTTRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINTTRANSLATION] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINTTRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYREWARDPOINTTRANSLATION_REWARDPOINT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYREWARDPOINTTRANSLATION] ADD  CONSTRAINT [DF_RETAILLOYALTYREWARDPOINTTRANSLATION_REWARDPOINT]  DEFAULT ((0)) FOR [REWARDPOINT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYREWARDPOINTTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYSCHEME]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYSCHEME](
[RECID] [bigint] NOT NULL,
[AFFILIATION] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[LOYALTYSCHEMEID] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1146749838_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1146749838_-1598981990] UNIQUE NONCLUSTERED 
(
[LOYALTYSCHEMEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEME_AFFILIATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEME] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEME_AFFILIATION]  DEFAULT ((0)) FOR [AFFILIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEME_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEME] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEME_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEME_LOYALTYSCHEMEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEME] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEME_LOYALTYSCHEMEID]  DEFAULT ('') FOR [LOYALTYSCHEMEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYSCHEME] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYSCHEMECHANNEL]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYSCHEMECHANNEL](
[RECID] [bigint] NOT NULL,
[LOYALTYSCHEME] [bigint] NOT NULL,
[OMHIERARCHYTYPE] [bigint] NOT NULL,
[OMINTERNALORGANIZATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-836280753_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-836280753_-1434205541] UNIQUE NONCLUSTERED 
(
[LOYALTYSCHEME] ASC,
[OMINTERNALORGANIZATION] ASC,
[OMHIERARCHYTYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEMECHANNEL_LOYALTYSCHEME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEMECHANNEL] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEMECHANNEL_LOYALTYSCHEME]  DEFAULT ((0)) FOR [LOYALTYSCHEME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEMECHANNEL_OMHIERARCHYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEMECHANNEL] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEMECHANNEL_OMHIERARCHYTYPE]  DEFAULT ((0)) FOR [OMHIERARCHYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEMECHANNEL_OMINTERNALORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEMECHANNEL] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEMECHANNEL_OMINTERNALORGANIZATION]  DEFAULT ((0)) FOR [OMINTERNALORGANIZATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYSCHEMECHANNEL] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYSCHEMECHANNELEXPLODED]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYSCHEMECHANNELEXPLODED](
[RECID] [bigint] NOT NULL,
[LOYALTYSCHEME] [bigint] NOT NULL,
[OMOPERATINGUNIT] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-539412674_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-539412674_-1453058155] UNIQUE NONCLUSTERED 
(
[OMOPERATINGUNIT] ASC,
[LOYALTYSCHEME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEMECHANNELEXPLODED_LOYALTYSCHEME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEMECHANNELEXPLODED] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEMECHANNELEXPLODED_LOYALTYSCHEME]  DEFAULT ((0)) FOR [LOYALTYSCHEME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYSCHEMECHANNELEXPLODED_OMOPERATINGUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYSCHEMECHANNELEXPLODED] ADD  CONSTRAINT [DF_RETAILLOYALTYSCHEMECHANNELEXPLODED_OMOPERATINGUNIT]  DEFAULT ((0)) FOR [OMOPERATINGUNIT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYSCHEMECHANNELEXPLODED] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYTIER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYTIER](
[RECID] [bigint] NOT NULL,
[AFFILIATION] [bigint] NOT NULL,
[TIERID] [nvarchar](64) NOT NULL,
[TIERLEVEL] [numeric](32, 16) NOT NULL,
[VALIDDATEINTERVAL] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1384088785_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1384088785_-1841329999] UNIQUE NONCLUSTERED 
(
[AFFILIATION] ASC,
[TIERLEVEL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1384088785_-2103951646] UNIQUE NONCLUSTERED 
(
[AFFILIATION] ASC,
[TIERID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYTIER_AFFILIATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYTIER_AFFILIATION]  DEFAULT ((0)) FOR [AFFILIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYTIER_TIERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYTIER_TIERID]  DEFAULT ('') FOR [TIERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYTIER_TIERLEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYTIER_TIERLEVEL]  DEFAULT ((0)) FOR [TIERLEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYTIER_VALIDDATEINTERVAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYTIER] ADD  CONSTRAINT [DF_RETAILLOYALTYTIER_VALIDDATEINTERVAL]  DEFAULT ('') FOR [VALIDDATEINTERVAL]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYTIER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILLOYALTYTIERTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILLOYALTYTIERTRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[LOYALTYTIER] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_822357336_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_822357336_-1167379206] UNIQUE NONCLUSTERED 
(
[LANGUAGEID] ASC,
[LOYALTYTIER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYTIERTRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYTIERTRANSLATION] ADD  CONSTRAINT [DF_RETAILLOYALTYTIERTRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYTIERTRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYTIERTRANSLATION] ADD  CONSTRAINT [DF_RETAILLOYALTYTIERTRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILLOYALTYTIERTRANSLATION_LOYALTYTIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILLOYALTYTIERTRANSLATION] ADD  CONSTRAINT [DF_RETAILLOYALTYTIERTRANSLATION_LOYALTYTIER]  DEFAULT ((0)) FOR [LOYALTYTIER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILLOYALTYTIERTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILMIXANDMATCHLINEGROUPS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILMIXANDMATCHLINEGROUPS](
[RECID] [bigint] NOT NULL,
[DISCOUNTLINECOLORID] [int] NOT NULL,
[MIXANDMATCHID] [nvarchar](20) NOT NULL,
[MIXANDMATCHLINEGROUP] [nvarchar](10) NOT NULL,
[NUMBEROFITEMSNEEDED] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_149219285_708740483] PRIMARY KEY CLUSTERED 
(
[MIXANDMATCHID] ASC,
[MIXANDMATCHLINEGROUP] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILMIXANDMATCHLINEGROUPS_DISCOUNTLINECOLORID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILMIXANDMATCHLINEGROUPS] ADD  CONSTRAINT [DF_RETAILMIXANDMATCHLINEGROUPS_DISCOUNTLINECOLORID]  DEFAULT ((0)) FOR [DISCOUNTLINECOLORID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILMIXANDMATCHLINEGROUPS_MIXANDMATCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILMIXANDMATCHLINEGROUPS] ADD  CONSTRAINT [DF_RETAILMIXANDMATCHLINEGROUPS_MIXANDMATCHID]  DEFAULT ('') FOR [MIXANDMATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILMIXANDMATCHLINEGROUPS_MIXANDMATCHLINEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILMIXANDMATCHLINEGROUPS] ADD  CONSTRAINT [DF_RETAILMIXANDMATCHLINEGROUPS_MIXANDMATCHLINEGROUP]  DEFAULT ('') FOR [MIXANDMATCHLINEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILMIXANDMATCHLINEGROUPS_NUMBEROFITEMSNEEDED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILMIXANDMATCHLINEGROUPS] ADD  CONSTRAINT [DF_RETAILMIXANDMATCHLINEGROUPS_NUMBEROFITEMSNEEDED]  DEFAULT ((0)) FOR [NUMBEROFITEMSNEEDED]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILMIXANDMATCHLINEGROUPS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILMULTIBUYDISCOUNTLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILMULTIBUYDISCOUNTLINE](
[RECID] [bigint] NOT NULL,
[MULTIBUYID] [nvarchar](40) NOT NULL,
[PRICEDISCPCT] [numeric](32, 16) NOT NULL,
[QTYLOWEST] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-320805805_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-320805805_294269066] UNIQUE NONCLUSTERED 
(
[MULTIBUYID] ASC,
[QTYLOWEST] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILMULTIBUYDISCOUNTLINE_MULTIBUYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILMULTIBUYDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILMULTIBUYDISCOUNTLINE_MULTIBUYID]  DEFAULT ('') FOR [MULTIBUYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILMULTIBUYDISCOUNTLINE_PRICEDISCPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILMULTIBUYDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILMULTIBUYDISCOUNTLINE_PRICEDISCPCT]  DEFAULT ((0)) FOR [PRICEDISCPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILMULTIBUYDISCOUNTLINE_QTYLOWEST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILMULTIBUYDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILMULTIBUYDISCOUNTLINE_QTYLOWEST]  DEFAULT ((0)) FOR [QTYLOWEST]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILMULTIBUYDISCOUNTLINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILOFFLINEPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILOFFLINEPROFILE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](256) NOT NULL,
[NAME] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1301352601_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1301352601_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINEPROFILE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINEPROFILE] ADD  CONSTRAINT [DF_RETAILOFFLINEPROFILE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINEPROFILE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINEPROFILE] ADD  CONSTRAINT [DF_RETAILOFFLINEPROFILE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILOFFLINEPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILOFFLINEPROFILESCOPES]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILOFFLINEPROFILESCOPES](
[RECID] [bigint] NOT NULL,
[PROFILEID] [bigint] NOT NULL,
[SCOPEID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1443309648_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINEPROFILESCOPES_PROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINEPROFILESCOPES] ADD  CONSTRAINT [DF_RETAILOFFLINEPROFILESCOPES_PROFILEID]  DEFAULT ((0)) FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINEPROFILESCOPES_SCOPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINEPROFILESCOPES] ADD  CONSTRAINT [DF_RETAILOFFLINEPROFILESCOPES_SCOPEID]  DEFAULT ((0)) FOR [SCOPEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILOFFLINEPROFILESCOPES] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILOFFLINESCOPE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILOFFLINESCOPE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](256) NOT NULL,
[LASTSYNCTIME] [datetime] NOT NULL,
[LASTSYNCTIMETZID] [int] NOT NULL,
[SYNCDIRECTION] [int] NOT NULL,
[SYNCFREQUENCY] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1144720460_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1144720460_-1781313101] UNIQUE NONCLUSTERED 
(
[DESCRIPTION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINESCOPE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINESCOPE] ADD  CONSTRAINT [DF_RETAILOFFLINESCOPE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINESCOPE_LASTSYNCTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINESCOPE] ADD  CONSTRAINT [DF_RETAILOFFLINESCOPE_LASTSYNCTIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [LASTSYNCTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINESCOPE_LASTSYNCTIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINESCOPE] ADD  CONSTRAINT [DF_RETAILOFFLINESCOPE_LASTSYNCTIMETZID]  DEFAULT ((37001)) FOR [LASTSYNCTIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINESCOPE_SYNCDIRECTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINESCOPE] ADD  CONSTRAINT [DF_RETAILOFFLINESCOPE_SYNCDIRECTION]  DEFAULT ((0)) FOR [SYNCDIRECTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINESCOPE_SYNCFREQUENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINESCOPE] ADD  CONSTRAINT [DF_RETAILOFFLINESCOPE_SYNCFREQUENCY]  DEFAULT ((0)) FOR [SYNCFREQUENCY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILOFFLINESCOPE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILOFFLINESCOPETABLES]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILOFFLINESCOPETABLES](
[RECID] [bigint] NOT NULL,
[SCOPEID] [bigint] NOT NULL,
[SYNCTABLEID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-118421387_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-118421387_-1026021288] UNIQUE NONCLUSTERED 
(
[SYNCTABLEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINESCOPETABLES_SCOPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINESCOPETABLES] ADD  CONSTRAINT [DF_RETAILOFFLINESCOPETABLES_SCOPEID]  DEFAULT ((0)) FOR [SCOPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINESCOPETABLES_SYNCTABLEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINESCOPETABLES] ADD  CONSTRAINT [DF_RETAILOFFLINESCOPETABLES_SYNCTABLEID]  DEFAULT ((0)) FOR [SYNCTABLEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILOFFLINESCOPETABLES] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILOFFLINETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILOFFLINETABLE](
[RECID] [bigint] NOT NULL,
[TABLENAME] [nvarchar](50) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1221725956_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINETABLE_TABLENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINETABLE] ADD  CONSTRAINT [DF_RETAILOFFLINETABLE_TABLENAME]  DEFAULT ('') FOR [TABLENAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILOFFLINETABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILOFFLINETABLECOLUMNS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILOFFLINETABLECOLUMNS](
[RECID] [bigint] NOT NULL,
[SYNCCOLUMNNAME] [nvarchar](40) NOT NULL,
[SYNCTABLE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1599311751_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINETABLECOLUMNS_SYNCCOLUMNNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINETABLECOLUMNS] ADD  CONSTRAINT [DF_RETAILOFFLINETABLECOLUMNS_SYNCCOLUMNNAME]  DEFAULT ('') FOR [SYNCCOLUMNNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOFFLINETABLECOLUMNS_SYNCTABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOFFLINETABLECOLUMNS] ADD  CONSTRAINT [DF_RETAILOFFLINETABLECOLUMNS_SYNCTABLE]  DEFAULT ((0)) FOR [SYNCTABLE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILOFFLINETABLECOLUMNS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILONLINECHANNELPUBLISHSTATUS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILONLINECHANNELPUBLISHSTATUS](
[RECID] [bigint] NOT NULL,
[ONLINECHANNEL] [bigint] NOT NULL,
[PUBLISHSTATUS] [int] NOT NULL,
[PUBLISHSTATUSMESSAGE] [nvarchar](max) NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-664677306_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-664677306_1180044546] UNIQUE NONCLUSTERED 
(
[ONLINECHANNEL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILONLINECHANNELPUBLISHSTATUS_ONLINECHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILONLINECHANNELPUBLISHSTATUS] ADD  CONSTRAINT [DF_RETAILONLINECHANNELPUBLISHSTATUS_ONLINECHANNEL]  DEFAULT ((0)) FOR [ONLINECHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILONLINECHANNELPUBLISHSTATUS_PUBLISHSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILONLINECHANNELPUBLISHSTATUS] ADD  CONSTRAINT [DF_RETAILONLINECHANNELPUBLISHSTATUS_PUBLISHSTATUS]  DEFAULT ((0)) FOR [PUBLISHSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILONLINECHANNELPUBLISHSTATUS_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILONLINECHANNELPUBLISHSTATUS] ADD  CONSTRAINT [DF_RETAILONLINECHANNELPUBLISHSTATUS_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILONLINECHANNELPUBLISHSTATUS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILONLINECHANNELPUBLISHSTATUS] ADD  CONSTRAINT [DF_RETAILONLINECHANNELPUBLISHSTATUS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILONLINECHANNELPUBLISHSTATUS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILOPERATIONS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILOPERATIONS](
[RECID] [bigint] NOT NULL,
[CHECKUSERACCESS] [int] NOT NULL,
[OPERATIONID] [int] NOT NULL,
[OPERATIONNAME] [nvarchar](50) NOT NULL,
[PERMISSIONID] [int] NOT NULL,
[PERMISSIONID2] [int] NOT NULL,
[USEROPERATION] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1234623639_-1629766275] PRIMARY KEY CLUSTERED 
(
[OPERATIONID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOPERATIONS_CHECKUSERACCESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOPERATIONS] ADD  CONSTRAINT [DF_RETAILOPERATIONS_CHECKUSERACCESS]  DEFAULT ((0)) FOR [CHECKUSERACCESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOPERATIONS_OPERATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOPERATIONS] ADD  CONSTRAINT [DF_RETAILOPERATIONS_OPERATIONID]  DEFAULT ((0)) FOR [OPERATIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOPERATIONS_OPERATIONNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOPERATIONS] ADD  CONSTRAINT [DF_RETAILOPERATIONS_OPERATIONNAME]  DEFAULT ('') FOR [OPERATIONNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOPERATIONS_PERMISSIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOPERATIONS] ADD  CONSTRAINT [DF_RETAILOPERATIONS_PERMISSIONID]  DEFAULT ((0)) FOR [PERMISSIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOPERATIONS_PERMISSIONID2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOPERATIONS] ADD  CONSTRAINT [DF_RETAILOPERATIONS_PERMISSIONID2]  DEFAULT ((0)) FOR [PERMISSIONID2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILOPERATIONS_USEROPERATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILOPERATIONS] ADD  CONSTRAINT [DF_RETAILOPERATIONS_USEROPERATION]  DEFAULT ((0)) FOR [USEROPERATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILOPERATIONS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPARAMETERS](
[RECID] [bigint] NOT NULL,
[AUTOMATICRETURNOFLOYALTYPAYMENT_RU] [int] NOT NULL,
[AWARDPOINTSFORPARTIALREDEMPTION_RU] [int] NOT NULL,
[CANCELLATIONCHARGE] [numeric](32, 16) NOT NULL,
[CANCELLATIONCHARGECODE] [nvarchar](10) NOT NULL,
[DEFAULTCUSTOMERPOSTING] [int] NOT NULL,
[DEFAULTORDERTYPE] [int] NOT NULL,
[DISCOUNTOFFERACTIVITYTYPE] [nvarchar](10) NOT NULL,
[EANLICENSENO] [nvarchar](10) NOT NULL,
[ELECTRONICDELIVERYMODECODE] [nvarchar](10) NOT NULL,
[EXPIRATIONDATE] [int] NOT NULL,
[GIFTCARDITEM] [nvarchar](20) NOT NULL,
[ITEMLABELLASTACTION] [nvarchar](10) NOT NULL,
[ITEMLABELSFORNEGATIVESTOCK] [int] NOT NULL,
[ITEMSALESSTATISTICSON] [int] NOT NULL,
[KEY] [int] NOT NULL,
[MINIMUMDEPOSITFORSALESORDER] [numeric](32, 16) NOT NULL,
[MINIMUMPASSWORDLENGTH] [int] NOT NULL,
[MIXANDMATCHACTIVITYTYPE] [nvarchar](10) NOT NULL,
[MULTIBUYACTIVITYTYPE] [nvarchar](10) NOT NULL,
[PAYMENTSTATISTICS] [int] NOT NULL,
[PICKUPDELIVERYMODECODE] [nvarchar](10) NOT NULL,
[POSTCUSTDISC] [int] NOT NULL,
[POSTINFOCODEDISC] [int] NOT NULL,
[POSTLINEDISC] [int] NOT NULL,
[POSTPERIODICDISC] [int] NOT NULL,
[POSTTOTALDISC] [int] NOT NULL,
[PROCESSGIFTCARDSASPREPAYMENTS_RU] [int] NOT NULL,
[PROCESSRETURNSASINORIGINALSALESHIFT_RU] [int] NOT NULL,
[PROPOSEREFUNDPAYMENTAMOUNT_RU] [int] NOT NULL,
[RECEIPTOPTION] [int] NOT NULL,
[REQUIRENUMERICCHAR] [int] NOT NULL,
[REQUIRESPECIALCHAR] [int] NOT NULL,
[REQUIREUPPERCASE] [int] NOT NULL,
[SHELFLABELLASTACTION] [nvarchar](10) NOT NULL,
[SHIPPINGCHARGECODE] [nvarchar](10) NOT NULL,
[STAFFSTATISTICS] [int] NOT NULL,
[TERMINALSTATISTICS] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1854178713_2053771816] PRIMARY KEY CLUSTERED 
(
[KEY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_AUTOMATICRETURNOFLOYALTYPAYMENT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_AUTOMATICRETURNOFLOYALTYPAYMENT_RU]  DEFAULT ((0)) FOR [AUTOMATICRETURNOFLOYALTYPAYMENT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_AWARDPOINTSFORPARTIALREDEMPTION_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_AWARDPOINTSFORPARTIALREDEMPTION_RU]  DEFAULT ((0)) FOR [AWARDPOINTSFORPARTIALREDEMPTION_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_CANCELLATIONCHARGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_CANCELLATIONCHARGE]  DEFAULT ((0)) FOR [CANCELLATIONCHARGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_CANCELLATIONCHARGECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_CANCELLATIONCHARGECODE]  DEFAULT ('') FOR [CANCELLATIONCHARGECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_DEFAULTCUSTOMERPOSTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_DEFAULTCUSTOMERPOSTING]  DEFAULT ((0)) FOR [DEFAULTCUSTOMERPOSTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_DEFAULTORDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_DEFAULTORDERTYPE]  DEFAULT ((0)) FOR [DEFAULTORDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_DISCOUNTOFFERACTIVITYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_DISCOUNTOFFERACTIVITYTYPE]  DEFAULT ('') FOR [DISCOUNTOFFERACTIVITYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_EANLICENSENO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_EANLICENSENO]  DEFAULT ('') FOR [EANLICENSENO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_ELECTRONICDELIVERYMODECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_ELECTRONICDELIVERYMODECODE]  DEFAULT ('') FOR [ELECTRONICDELIVERYMODECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_EXPIRATIONDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_EXPIRATIONDATE]  DEFAULT ((0)) FOR [EXPIRATIONDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_GIFTCARDITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_GIFTCARDITEM]  DEFAULT ('') FOR [GIFTCARDITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_ITEMLABELLASTACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_ITEMLABELLASTACTION]  DEFAULT ('') FOR [ITEMLABELLASTACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_ITEMLABELSFORNEGATIVESTOCK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_ITEMLABELSFORNEGATIVESTOCK]  DEFAULT ((0)) FOR [ITEMLABELSFORNEGATIVESTOCK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_ITEMSALESSTATISTICSON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_ITEMSALESSTATISTICSON]  DEFAULT ((0)) FOR [ITEMSALESSTATISTICSON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_MINIMUMDEPOSITFORSALESORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_MINIMUMDEPOSITFORSALESORDER]  DEFAULT ((0)) FOR [MINIMUMDEPOSITFORSALESORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_MINIMUMPASSWORDLENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_MINIMUMPASSWORDLENGTH]  DEFAULT ((0)) FOR [MINIMUMPASSWORDLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_MIXANDMATCHACTIVITYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_MIXANDMATCHACTIVITYTYPE]  DEFAULT ('') FOR [MIXANDMATCHACTIVITYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_MULTIBUYACTIVITYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_MULTIBUYACTIVITYTYPE]  DEFAULT ('') FOR [MULTIBUYACTIVITYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_PAYMENTSTATISTICS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_PAYMENTSTATISTICS]  DEFAULT ((0)) FOR [PAYMENTSTATISTICS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_PICKUPDELIVERYMODECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_PICKUPDELIVERYMODECODE]  DEFAULT ('') FOR [PICKUPDELIVERYMODECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_POSTCUSTDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_POSTCUSTDISC]  DEFAULT ((0)) FOR [POSTCUSTDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_POSTINFOCODEDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_POSTINFOCODEDISC]  DEFAULT ((0)) FOR [POSTINFOCODEDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_POSTLINEDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_POSTLINEDISC]  DEFAULT ((0)) FOR [POSTLINEDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_POSTPERIODICDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_POSTPERIODICDISC]  DEFAULT ((0)) FOR [POSTPERIODICDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_POSTTOTALDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_POSTTOTALDISC]  DEFAULT ((0)) FOR [POSTTOTALDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_PROCESSGIFTCARDSASPREPAYMENTS_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_PROCESSGIFTCARDSASPREPAYMENTS_RU]  DEFAULT ((0)) FOR [PROCESSGIFTCARDSASPREPAYMENTS_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_PROCESSRETURNSASINORIGINALSALESHIFT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_PROCESSRETURNSASINORIGINALSALESHIFT_RU]  DEFAULT ((0)) FOR [PROCESSRETURNSASINORIGINALSALESHIFT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_PROPOSEREFUNDPAYMENTAMOUNT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_PROPOSEREFUNDPAYMENTAMOUNT_RU]  DEFAULT ((0)) FOR [PROPOSEREFUNDPAYMENTAMOUNT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_RECEIPTOPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_RECEIPTOPTION]  DEFAULT ((0)) FOR [RECEIPTOPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_REQUIRENUMERICCHAR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_REQUIRENUMERICCHAR]  DEFAULT ((0)) FOR [REQUIRENUMERICCHAR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_REQUIRESPECIALCHAR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_REQUIRESPECIALCHAR]  DEFAULT ((0)) FOR [REQUIRESPECIALCHAR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_REQUIREUPPERCASE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_REQUIREUPPERCASE]  DEFAULT ((0)) FOR [REQUIREUPPERCASE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_SHELFLABELLASTACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_SHELFLABELLASTACTION]  DEFAULT ('') FOR [SHELFLABELLASTACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_SHIPPINGCHARGECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_SHIPPINGCHARGECODE]  DEFAULT ('') FOR [SHIPPINGCHARGECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_STAFFSTATISTICS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_STAFFSTATISTICS]  DEFAULT ((0)) FOR [STAFFSTATISTICS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPARAMETERS_TERMINALSTATISTICS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPARAMETERS] ADD  CONSTRAINT [DF_RETAILPARAMETERS_TERMINALSTATISTICS]  DEFAULT ((0)) FOR [TERMINALSTATISTICS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPERIODICDISCOUNT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPERIODICDISCOUNT](
[RECID] [bigint] NOT NULL,
[CONCURRENCYMODE] [int] NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[DATEVALIDATIONTYPE] [int] NOT NULL,
[DESCRIPTION] [nvarchar](max) NULL,
[DISCLAIMER] [nvarchar](max) NULL,
[DISCOUNTPERCENTVALUE] [numeric](32, 16) NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[ISDISCOUNTCODEREQUIRED] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[OFFERID] [nvarchar](20) NOT NULL,
[PERIODICDISCOUNTTYPE] [int] NOT NULL,
[PRICEDISCGROUP] [bigint] NOT NULL,
[STATUS] [int] NOT NULL,
[VALIDATIONPERIODID] [nvarchar](10) NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_444360761_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_444360761_1895356525] UNIQUE NONCLUSTERED 
(
[OFFERID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_CONCURRENCYMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_CONCURRENCYMODE]  DEFAULT ((0)) FOR [CONCURRENCYMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_DATEVALIDATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_DATEVALIDATIONTYPE]  DEFAULT ((0)) FOR [DATEVALIDATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_DISCOUNTPERCENTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_DISCOUNTPERCENTVALUE]  DEFAULT ((0)) FOR [DISCOUNTPERCENTVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_ISDISCOUNTCODEREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_ISDISCOUNTCODEREQUIRED]  DEFAULT ((0)) FOR [ISDISCOUNTCODEREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_OFFERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_OFFERID]  DEFAULT ('') FOR [OFFERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_PERIODICDISCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_PERIODICDISCOUNTTYPE]  DEFAULT ((0)) FOR [PERIODICDISCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_PRICEDISCGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_PRICEDISCGROUP]  DEFAULT ((0)) FOR [PRICEDISCGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_VALIDATIONPERIODID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_VALIDATIONPERIODID]  DEFAULT ('') FOR [VALIDATIONPERIODID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNT_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNT] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNT_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPERIODICDISCOUNT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPERIODICDISCOUNTLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPERIODICDISCOUNTLINE](
[RECID] [bigint] NOT NULL,
[DISCOUNTPERCENTORVALUE] [numeric](32, 16) NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[ISDISCOUNTCODEREQUIRED] [int] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[OFFERID] [nvarchar](20) NOT NULL,
[RETAILGROUPMEMBERLINE] [bigint] NOT NULL,
[STATUS] [int] NOT NULL,
[UNITOFMEASURE] [bigint] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2095525985_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2095525985_1217888543] UNIQUE NONCLUSTERED 
(
[OFFERID] ASC,
[LINENUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2095525985_-470159237] UNIQUE NONCLUSTERED 
(
[RETAILGROUPMEMBERLINE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_DISCOUNTPERCENTORVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_DISCOUNTPERCENTORVALUE]  DEFAULT ((0)) FOR [DISCOUNTPERCENTORVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_ISDISCOUNTCODEREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_ISDISCOUNTCODEREQUIRED]  DEFAULT ((0)) FOR [ISDISCOUNTCODEREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_OFFERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_OFFERID]  DEFAULT ('') FOR [OFFERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_RETAILGROUPMEMBERLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_RETAILGROUPMEMBERLINE]  DEFAULT ((0)) FOR [RETAILGROUPMEMBERLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERIODICDISCOUNTLINE_UNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERIODICDISCOUNTLINE] ADD  CONSTRAINT [DF_RETAILPERIODICDISCOUNTLINE_UNITOFMEASURE]  DEFAULT ((0)) FOR [UNITOFMEASURE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPERIODICDISCOUNTLINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPERMISSIONS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPERMISSIONS](
[RECID] [bigint] NOT NULL,
[PERMISSIONID] [int] NOT NULL,
[PERMISSIONNAME] [nvarchar](100) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-191668477_-407734873] PRIMARY KEY CLUSTERED 
(
[PERMISSIONID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERMISSIONS_PERMISSIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERMISSIONS] ADD  CONSTRAINT [DF_RETAILPERMISSIONS_PERMISSIONID]  DEFAULT ((0)) FOR [PERMISSIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPERMISSIONS_PERMISSIONNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPERMISSIONS] ADD  CONSTRAINT [DF_RETAILPERMISSIONS_PERMISSIONNAME]  DEFAULT ('') FOR [PERMISSIONNAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPERMISSIONS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPOSBATCHACCOUNTTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS](
[ACCOUNTNUM] [nvarchar](10) NOT NULL,
[ACCOUNTTYPE] [int] NOT NULL,
[AMOUNT] [numeric](32, 16) NOT NULL,
[BATCHID] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[REPLICATIONCOUNTER] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2072456596_1536653555] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[BATCHID] ASC,
[ACCOUNTNUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILPOSBATCHACCOUNTTRANS_REPLICATIONCOUNTER] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHACCOUNTTRANS_ACCOUNTNUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHACCOUNTTRANS_ACCOUNTNUM]  DEFAULT ('') FOR [ACCOUNTNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHACCOUNTTRANS_ACCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHACCOUNTTRANS_ACCOUNTTYPE]  DEFAULT ((0)) FOR [ACCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHACCOUNTTRANS_AMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHACCOUNTTRANS_AMOUNT]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHACCOUNTTRANS_BATCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHACCOUNTTRANS_BATCHID]  DEFAULT ((0)) FOR [BATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHACCOUNTTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHACCOUNTTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHACCOUNTTRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHACCOUNTTRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHACCOUNTTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHACCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHACCOUNTTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPOSBATCHACCOUNTTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPOSBATCHTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPOSBATCHTABLE](
[BATCHID] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CLOSEDATE] [date] NOT NULL,
[CLOSEDATETIMEUTC] [datetime] NOT NULL,
[CLOSEDATETIMEUTCTZID] [int] NOT NULL,
[CLOSEDATTERMINAL] [nvarchar](10) NOT NULL,
[CLOSETIME] [int] NOT NULL,
[CUSTOMERSCOUNT] [int] NOT NULL,
[DISCOUNTTOTAL] [numeric](32, 16) NOT NULL,
[LOGONSCOUNT] [int] NOT NULL,
[NOSALECOUNT] [int] NOT NULL,
[PAIDTOACCOUNTTOTAL] [numeric](32, 16) NOT NULL,
[POSTED] [int] NOT NULL,
[REPLICATIONCOUNTER] [int] IDENTITY(1,1) NOT NULL,
[RETURNSTOTAL] [numeric](32, 16) NOT NULL,
[ROUNDEDAMOUNTTOTAL] [numeric](32, 16) NOT NULL,
[SALESCOUNT] [int] NOT NULL,
[SALESTOTAL] [numeric](32, 16) NOT NULL,
[STAFFID] [nvarchar](25) NOT NULL,
[STARTDATE] [date] NOT NULL,
[STARTDATETIMEUTC] [datetime] NOT NULL,
[STARTDATETIMEUTCTZID] [int] NOT NULL,
[STARTTIME] [int] NOT NULL,
[STATUS] [int] NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TAXTOTAL] [numeric](32, 16) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONSCOUNT] [int] NOT NULL,
[VOIDSCOUNT] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1033447763_133955128] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[BATCHID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILPOSBATCHTABLE_REPLICATIONCOUNTER] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_BATCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_BATCHID]  DEFAULT ((0)) FOR [BATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_CLOSEDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_CLOSEDATE]  DEFAULT ('1900-01-01') FOR [CLOSEDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_CLOSEDATETIMEUTC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_CLOSEDATETIMEUTC]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CLOSEDATETIMEUTC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_CLOSEDATETIMEUTCTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_CLOSEDATETIMEUTCTZID]  DEFAULT ((37001)) FOR [CLOSEDATETIMEUTCTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_CLOSEDATTERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_CLOSEDATTERMINAL]  DEFAULT ('') FOR [CLOSEDATTERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_CLOSETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_CLOSETIME]  DEFAULT ((0)) FOR [CLOSETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_CUSTOMERSCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_CUSTOMERSCOUNT]  DEFAULT ((0)) FOR [CUSTOMERSCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_DISCOUNTTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_DISCOUNTTOTAL]  DEFAULT ((0)) FOR [DISCOUNTTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_LOGONSCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_LOGONSCOUNT]  DEFAULT ((0)) FOR [LOGONSCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_NOSALECOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_NOSALECOUNT]  DEFAULT ((0)) FOR [NOSALECOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_PAIDTOACCOUNTTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_PAIDTOACCOUNTTOTAL]  DEFAULT ((0)) FOR [PAIDTOACCOUNTTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_POSTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_POSTED]  DEFAULT ((0)) FOR [POSTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_RETURNSTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_RETURNSTOTAL]  DEFAULT ((0)) FOR [RETURNSTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_ROUNDEDAMOUNTTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_ROUNDEDAMOUNTTOTAL]  DEFAULT ((0)) FOR [ROUNDEDAMOUNTTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_SALESCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_SALESCOUNT]  DEFAULT ((0)) FOR [SALESCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_SALESTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_SALESTOTAL]  DEFAULT ((0)) FOR [SALESTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_STAFFID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_STAFFID]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_STARTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_STARTDATE]  DEFAULT ('1900-01-01') FOR [STARTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_STARTDATETIMEUTC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_STARTDATETIMEUTC]  DEFAULT ('1900-01-01 00:00:00.000') FOR [STARTDATETIMEUTC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_STARTDATETIMEUTCTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_STARTDATETIMEUTCTZID]  DEFAULT ((37001)) FOR [STARTDATETIMEUTCTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_STARTTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_STARTTIME]  DEFAULT ((0)) FOR [STARTTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_TAXTOTAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_TAXTOTAL]  DEFAULT ((0)) FOR [TAXTOTAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_TRANSACTIONSCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_TRANSACTIONSCOUNT]  DEFAULT ((0)) FOR [TRANSACTIONSCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTABLE_VOIDSCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTABLE] ADD  CONSTRAINT [DF_RETAILPOSBATCHTABLE_VOIDSCOUNT]  DEFAULT ((0)) FOR [VOIDSCOUNT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPOSBATCHTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPOSBATCHTENDERTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPOSBATCHTENDERTRANS](
[ADDTOTENDERAMOUNT] [numeric](32, 16) NOT NULL,
[ADDTOTENDERAMOUNTCUR] [numeric](32, 16) NOT NULL,
[BANKDROPAMOUNT] [numeric](32, 16) NOT NULL,
[BANKDROPAMOUNTCUR] [numeric](32, 16) NOT NULL,
[BATCHID] [bigint] NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[CHANGEAMOUNT] [numeric](32, 16) NOT NULL,
[CHANGEAMOUNTCUR] [numeric](32, 16) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[COUNT] [int] NOT NULL,
[COUNTINGREQUIRED] [int] NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[DECLARETENDERAMOUNT] [numeric](32, 16) NOT NULL,
[DECLARETENDERAMOUNTCUR] [numeric](32, 16) NOT NULL,
[REMOVETENDERAMOUNT] [numeric](32, 16) NOT NULL,
[REMOVETENDERAMOUNTCUR] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTER] [int] IDENTITY(1,1) NOT NULL,
[SAFEDROPAMOUNT] [numeric](32, 16) NOT NULL,
[SAFEDROPAMOUNTCUR] [numeric](32, 16) NOT NULL,
[STARTINGAMOUNT] [numeric](32, 16) NOT NULL,
[STARTINGAMOUNTCUR] [numeric](32, 16) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TENDEREDAMOUNT] [numeric](32, 16) NOT NULL,
[TENDEREDAMOUNTCUR] [numeric](32, 16) NOT NULL,
[TENDERTYPEID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1239242545_-1990270058] PRIMARY KEY CLUSTERED 
(
[CURRENCY] ASC,
[CARDTYPEID] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[BATCHID] ASC,
[TENDERTYPEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILPOSBATCHTENDERTRANS_REPLICATIONCOUNTER] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_ADDTOTENDERAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_ADDTOTENDERAMOUNT]  DEFAULT ((0)) FOR [ADDTOTENDERAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_ADDTOTENDERAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_ADDTOTENDERAMOUNTCUR]  DEFAULT ((0)) FOR [ADDTOTENDERAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_BANKDROPAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_BANKDROPAMOUNT]  DEFAULT ((0)) FOR [BANKDROPAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_BANKDROPAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_BANKDROPAMOUNTCUR]  DEFAULT ((0)) FOR [BANKDROPAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_BATCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_BATCHID]  DEFAULT ((0)) FOR [BATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_CARDTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_CARDTYPEID]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_CHANGEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_CHANGEAMOUNT]  DEFAULT ((0)) FOR [CHANGEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_CHANGEAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_CHANGEAMOUNTCUR]  DEFAULT ((0)) FOR [CHANGEAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_COUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_COUNT]  DEFAULT ((0)) FOR [COUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_COUNTINGREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_COUNTINGREQUIRED]  DEFAULT ((0)) FOR [COUNTINGREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_DECLARETENDERAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_DECLARETENDERAMOUNT]  DEFAULT ((0)) FOR [DECLARETENDERAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_DECLARETENDERAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_DECLARETENDERAMOUNTCUR]  DEFAULT ((0)) FOR [DECLARETENDERAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_REMOVETENDERAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_REMOVETENDERAMOUNT]  DEFAULT ((0)) FOR [REMOVETENDERAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_REMOVETENDERAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_REMOVETENDERAMOUNTCUR]  DEFAULT ((0)) FOR [REMOVETENDERAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_SAFEDROPAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_SAFEDROPAMOUNT]  DEFAULT ((0)) FOR [SAFEDROPAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_SAFEDROPAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_SAFEDROPAMOUNTCUR]  DEFAULT ((0)) FOR [SAFEDROPAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_STARTINGAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_STARTINGAMOUNT]  DEFAULT ((0)) FOR [STARTINGAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_STARTINGAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_STARTINGAMOUNTCUR]  DEFAULT ((0)) FOR [STARTINGAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_TENDEREDAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_TENDEREDAMOUNT]  DEFAULT ((0)) FOR [TENDEREDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_TENDEREDAMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_TENDEREDAMOUNTCUR]  DEFAULT ((0)) FOR [TENDEREDAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_TENDERTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_TENDERTYPEID]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSBATCHTENDERTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSBATCHTENDERTRANS] ADD  CONSTRAINT [DF_RETAILPOSBATCHTENDERTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPOSBATCHTENDERTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPOSITIONPOSPERMISSION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPOSITIONPOSPERMISSION](
[RECID] [bigint] NOT NULL,
[ALLOWBLINDCLOSE] [int] NOT NULL,
[ALLOWCHANGENOVOID] [int] NOT NULL,
[ALLOWCHANGEPERIPHERALSTATION] [int] NOT NULL,
[ALLOWCREATEORDER] [int] NOT NULL,
[ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU] [int] NOT NULL,
[ALLOWEDITORDER] [int] NOT NULL,
[ALLOWFLOATINGTENDERDECLARATION] [int] NOT NULL,
[ALLOWKITDISASSEMBLY] [int] NOT NULL,
[ALLOWMULTIPLELOGINS] [int] NOT NULL,
[ALLOWMULTIPLESHIFTLOGON] [int] NOT NULL,
[ALLOWNOTSAMEDATERETURN_RU] [int] NOT NULL,
[ALLOWOPENDRAWERONLY] [int] NOT NULL,
[ALLOWPASSWORDCHANGE] [int] NOT NULL,
[ALLOWPRICEOVERRIDE] [int] NOT NULL,
[ALLOWRESETPASSWORD] [int] NOT NULL,
[ALLOWRETRIEVEORDER] [int] NOT NULL,
[ALLOWRETURNOFNONRETURNABLEITEM_RU] [int] NOT NULL,
[ALLOWSALESTAXCHANGE] [int] NOT NULL,
[ALLOWTENDERDECLARATION] [int] NOT NULL,
[ALLOWTRANSACTIONSUSPENSION] [int] NOT NULL,
[ALLOWTRANSACTIONVOIDING] [int] NOT NULL,
[ALLOWXREPORTPRINTING] [int] NOT NULL,
[ALLOWZREPORTPRINTING] [int] NOT NULL,
[MANAGEDEVICE] [int] NOT NULL,
[MANAGERPRIVILEGES] [int] NOT NULL,
[MAXIMUMDISCOUNTPCT] [numeric](32, 16) NOT NULL,
[MAXLINEDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[MAXLINERETURNAMOUNT] [numeric](32, 16) NOT NULL,
[MAXTOTALDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[MAXTOTALDISCOUNTPCT] [numeric](32, 16) NOT NULL,
[MAXTOTALRETURNAMOUNT] [numeric](32, 16) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[POSITION] [bigint] NOT NULL,
[POSPERMISSIONGROUP] [bigint] NOT NULL,
[USEHANDHELD] [int] NOT NULL,
[VIEWTIMECLOCKENTRIES] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_562388273_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_562388273_-1074520080] UNIQUE NONCLUSTERED 
(
[POSITION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWBLINDCLOSE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWBLINDCLOSE]  DEFAULT ((0)) FOR [ALLOWBLINDCLOSE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWCHANGENOVOID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWCHANGENOVOID]  DEFAULT ((0)) FOR [ALLOWCHANGENOVOID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWCHANGEPERIPHERALSTATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWCHANGEPERIPHERALSTATION]  DEFAULT ((0)) FOR [ALLOWCHANGEPERIPHERALSTATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWCREATEORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWCREATEORDER]  DEFAULT ((0)) FOR [ALLOWCREATEORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU]  DEFAULT ((0)) FOR [ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWEDITORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWEDITORDER]  DEFAULT ((0)) FOR [ALLOWEDITORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWFLOATINGTENDERDECLARATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWFLOATINGTENDERDECLARATION]  DEFAULT ((0)) FOR [ALLOWFLOATINGTENDERDECLARATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWKITDISASSEMBLY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWKITDISASSEMBLY]  DEFAULT ((0)) FOR [ALLOWKITDISASSEMBLY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWMULTIPLELOGINS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWMULTIPLELOGINS]  DEFAULT ((0)) FOR [ALLOWMULTIPLELOGINS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWMULTIPLESHIFTLOGON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWMULTIPLESHIFTLOGON]  DEFAULT ((0)) FOR [ALLOWMULTIPLESHIFTLOGON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWNOTSAMEDATERETURN_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWNOTSAMEDATERETURN_RU]  DEFAULT ((0)) FOR [ALLOWNOTSAMEDATERETURN_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWOPENDRAWERONLY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWOPENDRAWERONLY]  DEFAULT ((0)) FOR [ALLOWOPENDRAWERONLY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWPASSWORDCHANGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWPASSWORDCHANGE]  DEFAULT ((0)) FOR [ALLOWPASSWORDCHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWPRICEOVERRIDE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWPRICEOVERRIDE]  DEFAULT ((0)) FOR [ALLOWPRICEOVERRIDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWRESETPASSWORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWRESETPASSWORD]  DEFAULT ((0)) FOR [ALLOWRESETPASSWORD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWRETRIEVEORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWRETRIEVEORDER]  DEFAULT ((0)) FOR [ALLOWRETRIEVEORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWRETURNOFNONRETURNABLEITEM_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWRETURNOFNONRETURNABLEITEM_RU]  DEFAULT ((0)) FOR [ALLOWRETURNOFNONRETURNABLEITEM_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWSALESTAXCHANGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWSALESTAXCHANGE]  DEFAULT ((0)) FOR [ALLOWSALESTAXCHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWTENDERDECLARATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWTENDERDECLARATION]  DEFAULT ((0)) FOR [ALLOWTENDERDECLARATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWTRANSACTIONSUSPENSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWTRANSACTIONSUSPENSION]  DEFAULT ((0)) FOR [ALLOWTRANSACTIONSUSPENSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWTRANSACTIONVOIDING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWTRANSACTIONVOIDING]  DEFAULT ((0)) FOR [ALLOWTRANSACTIONVOIDING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWXREPORTPRINTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWXREPORTPRINTING]  DEFAULT ((0)) FOR [ALLOWXREPORTPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_ALLOWZREPORTPRINTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_ALLOWZREPORTPRINTING]  DEFAULT ((0)) FOR [ALLOWZREPORTPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MANAGEDEVICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MANAGEDEVICE]  DEFAULT ((0)) FOR [MANAGEDEVICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MANAGERPRIVILEGES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MANAGERPRIVILEGES]  DEFAULT ((0)) FOR [MANAGERPRIVILEGES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MAXIMUMDISCOUNTPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MAXIMUMDISCOUNTPCT]  DEFAULT ((0)) FOR [MAXIMUMDISCOUNTPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MAXLINEDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MAXLINEDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [MAXLINEDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MAXLINERETURNAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MAXLINERETURNAMOUNT]  DEFAULT ((0)) FOR [MAXLINERETURNAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MAXTOTALDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MAXTOTALDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [MAXTOTALDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MAXTOTALDISCOUNTPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MAXTOTALDISCOUNTPCT]  DEFAULT ((0)) FOR [MAXTOTALDISCOUNTPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_MAXTOTALRETURNAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_MAXTOTALRETURNAMOUNT]  DEFAULT ((0)) FOR [MAXTOTALRETURNAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_POSITION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_POSITION]  DEFAULT ((0)) FOR [POSITION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_POSPERMISSIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_POSPERMISSIONGROUP]  DEFAULT ((0)) FOR [POSPERMISSIONGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_USEHANDHELD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_USEHANDHELD]  DEFAULT ((0)) FOR [USEHANDHELD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSITIONPOSPERMISSION_VIEWTIMECLOCKENTRIES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSITIONPOSPERMISSION] ADD  CONSTRAINT [DF_RETAILPOSITIONPOSPERMISSION_VIEWTIMECLOCKENTRIES]  DEFAULT ((0)) FOR [VIEWTIMECLOCKENTRIES]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPOSITIONPOSPERMISSION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPOSPERMISSIONGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPOSPERMISSIONGROUP](
[RECID] [bigint] NOT NULL,
[ALLOWBLINDCLOSE] [int] NOT NULL,
[ALLOWCHANGENOVOID] [int] NOT NULL,
[ALLOWCHANGEPERIPHERALSTATION] [int] NOT NULL,
[ALLOWCREATEORDER] [int] NOT NULL,
[ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU] [int] NOT NULL,
[ALLOWEDITORDER] [int] NOT NULL,
[ALLOWFLOATINGTENDERDECLARATION] [int] NOT NULL,
[ALLOWKITDISASSEMBLY] [int] NOT NULL,
[ALLOWMULTIPLELOGINS] [int] NOT NULL,
[ALLOWMULTIPLESHIFTLOGON] [int] NOT NULL,
[ALLOWNOTSAMEDATERETURN_RU] [int] NOT NULL,
[ALLOWOPENDRAWERONLY] [int] NOT NULL,
[ALLOWPASSWORDCHANGE] [int] NOT NULL,
[ALLOWPRICEOVERRIDE] [int] NOT NULL,
[ALLOWRESETPASSWORD] [int] NOT NULL,
[ALLOWRETRIEVEORDER] [int] NOT NULL,
[ALLOWRETURNOFNONRETURNABLEITEM_RU] [int] NOT NULL,
[ALLOWSALESTAXCHANGE] [int] NOT NULL,
[ALLOWTENDERDECLARATION] [int] NOT NULL,
[ALLOWTRANSACTIONSUSPENSION] [int] NOT NULL,
[ALLOWTRANSACTIONVOIDING] [int] NOT NULL,
[ALLOWXREPORTPRINTING] [int] NOT NULL,
[ALLOWZREPORTPRINTING] [int] NOT NULL,
[MANAGEDEVICE] [int] NOT NULL,
[MANAGERPRIVILEGES] [int] NOT NULL,
[MAXIMUMDISCOUNTPCT] [numeric](32, 16) NOT NULL,
[MAXLINEDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[MAXLINERETURNAMOUNT] [numeric](32, 16) NOT NULL,
[MAXTOTALDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[MAXTOTALDISCOUNTPCT] [numeric](32, 16) NOT NULL,
[MAXTOTALRETURNAMOUNT] [numeric](32, 16) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[POSPERMISSIONGROUPID] [nvarchar](10) NOT NULL,
[USEHANDHELD] [int] NOT NULL,
[VIEWTIMECLOCKENTRIES] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1827980109_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1827980109_-143086023] UNIQUE NONCLUSTERED 
(
[POSPERMISSIONGROUPID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWBLINDCLOSE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWBLINDCLOSE]  DEFAULT ((0)) FOR [ALLOWBLINDCLOSE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWCHANGENOVOID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWCHANGENOVOID]  DEFAULT ((0)) FOR [ALLOWCHANGENOVOID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWCHANGEPERIPHERALSTATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWCHANGEPERIPHERALSTATION]  DEFAULT ((0)) FOR [ALLOWCHANGEPERIPHERALSTATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWCREATEORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWCREATEORDER]  DEFAULT ((0)) FOR [ALLOWCREATEORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU]  DEFAULT ((0)) FOR [ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWEDITORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWEDITORDER]  DEFAULT ((0)) FOR [ALLOWEDITORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWFLOATINGTENDERDECLARATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWFLOATINGTENDERDECLARATION]  DEFAULT ((0)) FOR [ALLOWFLOATINGTENDERDECLARATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWKITDISASSEMBLY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWKITDISASSEMBLY]  DEFAULT ((0)) FOR [ALLOWKITDISASSEMBLY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWMULTIPLELOGINS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWMULTIPLELOGINS]  DEFAULT ((0)) FOR [ALLOWMULTIPLELOGINS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWMULTIPLESHIFTLOGON]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWMULTIPLESHIFTLOGON]  DEFAULT ((0)) FOR [ALLOWMULTIPLESHIFTLOGON]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWNOTSAMEDATERETURN_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWNOTSAMEDATERETURN_RU]  DEFAULT ((0)) FOR [ALLOWNOTSAMEDATERETURN_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWOPENDRAWERONLY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWOPENDRAWERONLY]  DEFAULT ((0)) FOR [ALLOWOPENDRAWERONLY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWPASSWORDCHANGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWPASSWORDCHANGE]  DEFAULT ((0)) FOR [ALLOWPASSWORDCHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWPRICEOVERRIDE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWPRICEOVERRIDE]  DEFAULT ((0)) FOR [ALLOWPRICEOVERRIDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWRESETPASSWORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWRESETPASSWORD]  DEFAULT ((0)) FOR [ALLOWRESETPASSWORD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWRETRIEVEORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWRETRIEVEORDER]  DEFAULT ((0)) FOR [ALLOWRETRIEVEORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWRETURNOFNONRETURNABLEITEM_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWRETURNOFNONRETURNABLEITEM_RU]  DEFAULT ((0)) FOR [ALLOWRETURNOFNONRETURNABLEITEM_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWSALESTAXCHANGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWSALESTAXCHANGE]  DEFAULT ((0)) FOR [ALLOWSALESTAXCHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWTENDERDECLARATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWTENDERDECLARATION]  DEFAULT ((0)) FOR [ALLOWTENDERDECLARATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWTRANSACTIONSUSPENSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWTRANSACTIONSUSPENSION]  DEFAULT ((0)) FOR [ALLOWTRANSACTIONSUSPENSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWTRANSACTIONVOIDING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWTRANSACTIONVOIDING]  DEFAULT ((0)) FOR [ALLOWTRANSACTIONVOIDING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWXREPORTPRINTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWXREPORTPRINTING]  DEFAULT ((0)) FOR [ALLOWXREPORTPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_ALLOWZREPORTPRINTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_ALLOWZREPORTPRINTING]  DEFAULT ((0)) FOR [ALLOWZREPORTPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MANAGEDEVICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MANAGEDEVICE]  DEFAULT ((0)) FOR [MANAGEDEVICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MANAGERPRIVILEGES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MANAGERPRIVILEGES]  DEFAULT ((0)) FOR [MANAGERPRIVILEGES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MAXIMUMDISCOUNTPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MAXIMUMDISCOUNTPCT]  DEFAULT ((0)) FOR [MAXIMUMDISCOUNTPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MAXLINEDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MAXLINEDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [MAXLINEDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MAXLINERETURNAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MAXLINERETURNAMOUNT]  DEFAULT ((0)) FOR [MAXLINERETURNAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MAXTOTALDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MAXTOTALDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [MAXTOTALDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MAXTOTALDISCOUNTPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MAXTOTALDISCOUNTPCT]  DEFAULT ((0)) FOR [MAXTOTALDISCOUNTPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_MAXTOTALRETURNAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_MAXTOTALRETURNAMOUNT]  DEFAULT ((0)) FOR [MAXTOTALRETURNAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_POSPERMISSIONGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_POSPERMISSIONGROUPID]  DEFAULT ('') FOR [POSPERMISSIONGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_USEHANDHELD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_USEHANDHELD]  DEFAULT ((0)) FOR [USEHANDHELD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSPERMISSIONGROUP_VIEWTIMECLOCKENTRIES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILPOSPERMISSIONGROUP_VIEWTIMECLOCKENTRIES]  DEFAULT ((0)) FOR [VIEWTIMECLOCKENTRIES]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPOSPERMISSIONGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPOSSEEDDATA]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPOSSEEDDATA](
[DATATYPE] [int] NOT NULL,
[DATAVALUE] [bigint] NOT NULL,
[STORENUMBER] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1653969084_-308865658] PRIMARY KEY CLUSTERED 
(
[DATATYPE] ASC,
[STORENUMBER] ASC,
[TERMINALID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSSEEDDATA_DATATYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSSEEDDATA] ADD  CONSTRAINT [DF_RETAILPOSSEEDDATA_DATATYPE]  DEFAULT ((0)) FOR [DATATYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSSEEDDATA_DATAVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSSEEDDATA] ADD  CONSTRAINT [DF_RETAILPOSSEEDDATA_DATAVALUE]  DEFAULT ((0)) FOR [DATAVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSSEEDDATA_STORENUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSSEEDDATA] ADD  CONSTRAINT [DF_RETAILPOSSEEDDATA_STORENUMBER]  DEFAULT ('') FOR [STORENUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSSEEDDATA_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSSEEDDATA] ADD  CONSTRAINT [DF_RETAILPOSSEEDDATA_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPOSSEEDDATA] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPOSTHEME]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPOSTHEME](
[RECID] [bigint] NOT NULL,
[DEVICETYPE] [bigint] NOT NULL,
[NAME] [nvarchar](100) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_955159962_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_955159962_516664720] UNIQUE NONCLUSTERED 
(
[DEVICETYPE] ASC,
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSTHEME_DEVICETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSTHEME] ADD  CONSTRAINT [DF_RETAILPOSTHEME_DEVICETYPE]  DEFAULT ((0)) FOR [DEVICETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPOSTHEME_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPOSTHEME] ADD  CONSTRAINT [DF_RETAILPOSTHEME_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPOSTHEME] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCATALOG]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCATALOG](
[RECID] [bigint] NOT NULL,
[ENABLESNAPSHOT] [int] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[OWNER] [bigint] NOT NULL,
[PUBLISHEDDATETIME] [datetime] NOT NULL,
[PUBLISHEDDATETIMETZID] [int] NOT NULL,
[PUBLISHEDVALIDFROM] [date] NOT NULL,
[PUBLISHEDVALIDTO] [date] NOT NULL,
[STATE] [int] NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDFROMDATETIME] [datetime] NOT NULL,
[VALIDFROMDATETIMETZID] [int] NOT NULL,
[VALIDTO] [date] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[MODIFIEDBY] [nvarchar](8) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1981983829_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1981983829_-162312163] UNIQUE CLUSTERED 
(
[ORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_ENABLESNAPSHOT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_ENABLESNAPSHOT]  DEFAULT ((0)) FOR [ENABLESNAPSHOT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_OWNER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_OWNER]  DEFAULT ((0)) FOR [OWNER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_PUBLISHEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_PUBLISHEDDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [PUBLISHEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_PUBLISHEDDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_PUBLISHEDDATETIMETZID]  DEFAULT ((37001)) FOR [PUBLISHEDDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_PUBLISHEDVALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_PUBLISHEDVALIDFROM]  DEFAULT ('1900-01-01') FOR [PUBLISHEDVALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_PUBLISHEDVALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_PUBLISHEDVALIDTO]  DEFAULT ('1900-01-01') FOR [PUBLISHEDVALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_STATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_STATE]  DEFAULT ((0)) FOR [STATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_VALIDFROM]  DEFAULT ('1900-01-01') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_VALIDFROMDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_VALIDFROMDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROMDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_VALIDFROMDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_VALIDFROMDATETIMETZID]  DEFAULT ((37001)) FOR [VALIDFROMDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_VALIDTO]  DEFAULT ('1900-01-01') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOG_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOG] ADD  CONSTRAINT [DF_RETAILPUBCATALOG_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCATALOG] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCATALOGINTERNALORG]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCATALOGINTERNALORG](
[RECID] [bigint] NOT NULL,
[CATALOG] [bigint] NOT NULL,
[INTERNALORGANIZATION] [bigint] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[ORIGINRECVERSION] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-756910420_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-756910420_102317915] UNIQUE CLUSTERED 
(
[CATALOG] ASC,
[INTERNALORGANIZATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-756910420_-162312163] UNIQUE NONCLUSTERED 
(
[ORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGINTERNALORG_CATALOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGINTERNALORG] ADD  CONSTRAINT [DF_RETAILPUBCATALOGINTERNALORG_CATALOG]  DEFAULT ((0)) FOR [CATALOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGINTERNALORG_INTERNALORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGINTERNALORG] ADD  CONSTRAINT [DF_RETAILPUBCATALOGINTERNALORG_INTERNALORGANIZATION]  DEFAULT ((0)) FOR [INTERNALORGANIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGINTERNALORG_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGINTERNALORG] ADD  CONSTRAINT [DF_RETAILPUBCATALOGINTERNALORG_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGINTERNALORG_ORIGINRECVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGINTERNALORG] ADD  CONSTRAINT [DF_RETAILPUBCATALOGINTERNALORG_ORIGINRECVERSION]  DEFAULT ((0)) FOR [ORIGINRECVERSION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCATALOGINTERNALORG] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCATALOGPRODUCT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCATALOGPRODUCT](
[RECID] [bigint] NOT NULL,
[CATALOG] [bigint] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[USEHIERARCHY] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_144266078_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_144266078_1631511146] UNIQUE CLUSTERED 
(
[CATALOG] ASC,
[PRODUCT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_144266078_-162312163] UNIQUE NONCLUSTERED 
(
[ORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCT_CATALOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCT] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCT_CATALOG]  DEFAULT ((0)) FOR [CATALOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCT_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCT] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCT_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCT_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCT] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCT_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCT_USEHIERARCHY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCT] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCT_USEHIERARCHY]  DEFAULT ((0)) FOR [USEHIERARCHY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCT_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCT] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCT_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCT_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCT] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCT_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCATALOGPRODUCT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCATALOGPRODUCTCATEGORY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY](
[RECID] [bigint] NOT NULL,
[CATALOGPRODUCT] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[CATEGORYHIERARCHY] [bigint] NOT NULL,
[INCLUDEEXCLUDETYPE] [int] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_838037498_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_838037498_1588830537] UNIQUE CLUSTERED 
(
[CATALOGPRODUCT] ASC,
[CATEGORY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTCATEGORY_CATALOGPRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTCATEGORY_CATALOGPRODUCT]  DEFAULT ((0)) FOR [CATALOGPRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORYHIERARCHY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORYHIERARCHY]  DEFAULT ((0)) FOR [CATEGORYHIERARCHY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTCATEGORY_INCLUDEEXCLUDETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTCATEGORY_INCLUDEEXCLUDETYPE]  DEFAULT ((0)) FOR [INCLUDEEXCLUDETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTCATEGORY_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTCATEGORY_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTCATEGORY_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTCATEGORY_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTCATEGORY_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTCATEGORY_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCATALOGPRODUCTRELATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATION](
[RECID] [bigint] NOT NULL,
[CATALOGPRODUCT] [bigint] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[PRODUCTRELATIONTYPE] [bigint] NOT NULL,
[RELATEDPRODUCT] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-756004594_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-756004594_-777987643] UNIQUE CLUSTERED 
(
[CATALOGPRODUCT] ASC,
[PRODUCTRELATIONTYPE] ASC,
[RELATEDPRODUCT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-756004594_1082545321] UNIQUE NONCLUSTERED 
(
[CATALOGPRODUCT] ASC,
[ORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTRELATION_CATALOGPRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTRELATION_CATALOGPRODUCT]  DEFAULT ((0)) FOR [CATALOGPRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTRELATION_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTRELATION_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTRELATION_PRODUCTRELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTRELATION_PRODUCTRELATIONTYPE]  DEFAULT ((0)) FOR [PRODUCTRELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTRELATION_RELATEDPRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTRELATION_RELATEDPRODUCT]  DEFAULT ((0)) FOR [RELATEDPRODUCT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCATALOGPRODUCTRELATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION](
[RECID] [bigint] NOT NULL,
[CATALOGPRODUCT] [bigint] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[PRODUCTRELATION] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-348013118_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-348013118_-609989922] UNIQUE CLUSTERED 
(
[CATALOGPRODUCT] ASC,
[PRODUCTRELATION] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-348013118_-162312163] UNIQUE NONCLUSTERED 
(
[ORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION_CATALOGPRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION_CATALOGPRODUCT]  DEFAULT ((0)) FOR [CATALOGPRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION_PRODUCTRELATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION_PRODUCTRELATION]  DEFAULT ((0)) FOR [PRODUCTRELATION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCATALOGTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCATALOGTRANSLATION](
[RECID] [bigint] NOT NULL,
[CATALOG] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](128) NOT NULL,
[FRIENDLYNAME] [nvarchar](60) NOT NULL,
[IMAGE] [nvarchar](1999) NOT NULL,
[LANGUAGE] [nvarchar](7) NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-897518270_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-897518270_-162312163] UNIQUE NONCLUSTERED 
(
[ORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-897518270_-1799725725] UNIQUE NONCLUSTERED 
(
[CATALOG] ASC,
[LANGUAGE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGTRANSLATION_CATALOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGTRANSLATION_CATALOG]  DEFAULT ((0)) FOR [CATALOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGTRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGTRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGTRANSLATION_FRIENDLYNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGTRANSLATION_FRIENDLYNAME]  DEFAULT ('') FOR [FRIENDLYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGTRANSLATION_IMAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGTRANSLATION_IMAGE]  DEFAULT ('') FOR [IMAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGTRANSLATION_LANGUAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGTRANSLATION_LANGUAGE]  DEFAULT ('') FOR [LANGUAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCATALOGTRANSLATION_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCATALOGTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBCATALOGTRANSLATION_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCATALOGTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBCHANNELATTRIBUTE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBCHANNELATTRIBUTE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[ATTRIBUTEVALUE] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1546253985_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1546253985_67495050] UNIQUE NONCLUSTERED 
(
[CHANNEL] ASC,
[ATTRIBUTE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCHANNELATTRIBUTE_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCHANNELATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBCHANNELATTRIBUTE_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCHANNELATTRIBUTE_ATTRIBUTEVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCHANNELATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBCHANNELATTRIBUTE_ATTRIBUTEVALUE]  DEFAULT ((0)) FOR [ATTRIBUTEVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBCHANNELATTRIBUTE_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBCHANNELATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBCHANNELATTRIBUTE_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBCHANNELATTRIBUTE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBECORESCATEGORY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBECORESCATEGORY](
[RECID] [bigint] NOT NULL,
[CATEGORYHIERARCHY] [bigint] NOT NULL,
[CHANGESTATUS] [int] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CODE] [nvarchar](20) NOT NULL,
[DEFAULTPROJECTGLOBALCATEGORY] [bigint] NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[ISACTIVE] [int] NOT NULL,
[ISCATEGORYATTRIBUTESINHERITED] [int] NOT NULL,
[ISTANGIBLE] [int] NOT NULL,
[NAME] [nvarchar](254) NOT NULL,
[NESTEDSETLEFT] [bigint] NOT NULL,
[NESTEDSETRIGHT] [bigint] NOT NULL,
[ORIGINID] [bigint] NOT NULL,
[ORIGININSTANCERELATIONTYPE] [bigint] NOT NULL,
[PARENTCATEGORY] [bigint] NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1427327759_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1427327759_516664720] UNIQUE NONCLUSTERED 
(
[NAME] ASC,
[CATEGORYHIERARCHY] ASC,
[CHANNEL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_CATEGORYHIERARCHY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_CATEGORYHIERARCHY]  DEFAULT ((0)) FOR [CATEGORYHIERARCHY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_CHANGESTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_CHANGESTATUS]  DEFAULT ((0)) FOR [CHANGESTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_CODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_CODE]  DEFAULT ('') FOR [CODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_DEFAULTPROJECTGLOBALCATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_DEFAULTPROJECTGLOBALCATEGORY]  DEFAULT ((0)) FOR [DEFAULTPROJECTGLOBALCATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_ISACTIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_ISACTIVE]  DEFAULT ((0)) FOR [ISACTIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_ISCATEGORYATTRIBUTESINHERITED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_ISCATEGORYATTRIBUTESINHERITED]  DEFAULT ((0)) FOR [ISCATEGORYATTRIBUTESINHERITED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_ISTANGIBLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_ISTANGIBLE]  DEFAULT ((0)) FOR [ISTANGIBLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_NESTEDSETLEFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_NESTEDSETLEFT]  DEFAULT ((0)) FOR [NESTEDSETLEFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_NESTEDSETRIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_NESTEDSETRIGHT]  DEFAULT ((0)) FOR [NESTEDSETRIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_ORIGINID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_ORIGINID]  DEFAULT ((0)) FOR [ORIGINID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_ORIGININSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_ORIGININSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [ORIGININSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_PARENTCATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_PARENTCATEGORY]  DEFAULT ((0)) FOR [PARENTCATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORY_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORY] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORY_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBECORESCATEGORY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBECORESCATEGORYTRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION](
[RECID] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](1000) NOT NULL,
[FRIENDLYNAME] [nvarchar](254) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[ORIGINID] [bigint] NOT NULL,
[SEARCHTEXT] [nvarchar](254) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1633956436_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1633956436_-888948581] UNIQUE CLUSTERED 
(
[CHANNEL] ASC,
[CATEGORY] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORYTRANSLATION_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORYTRANSLATION_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORYTRANSLATION_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORYTRANSLATION_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORYTRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORYTRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORYTRANSLATION_FRIENDLYNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORYTRANSLATION_FRIENDLYNAME]  DEFAULT ('') FOR [FRIENDLYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORYTRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORYTRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORYTRANSLATION_ORIGINID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORYTRANSLATION_ORIGINID]  DEFAULT ((0)) FOR [ORIGINID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBECORESCATEGORYTRANSLATION_SEARCHTEXT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBECORESCATEGORYTRANSLATION] ADD  CONSTRAINT [DF_RETAILPUBECORESCATEGORYTRANSLATION_SEARCHTEXT]  DEFAULT ('') FOR [SEARCHTEXT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBECORESCATEGORYTRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP](
[RECID] [bigint] NOT NULL,
[ATTRIBUTEGROUP] [bigint] NOT NULL,
[INTERNALORGANIZATION] [bigint] NOT NULL,
[MODIFIER] [int] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[ORIGINRECVERSION] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1409114826_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1409114826_52244696] UNIQUE CLUSTERED 
(
[INTERNALORGANIZATION] ASC,
[MODIFIER] ASC,
[ATTRIBUTEGROUP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_ATTRIBUTEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP] ADD  CONSTRAINT [DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_ATTRIBUTEGROUP]  DEFAULT ((0)) FOR [ATTRIBUTEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_INTERNALORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP] ADD  CONSTRAINT [DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_INTERNALORGANIZATION]  DEFAULT ((0)) FOR [INTERNALORGANIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_MODIFIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP] ADD  CONSTRAINT [DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_MODIFIER]  DEFAULT ((0)) FOR [MODIFIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP] ADD  CONSTRAINT [DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_ORIGINRECVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP] ADD  CONSTRAINT [DF_RETAILPUBINTERNALORGATTRIBUTEGROUP_ORIGINRECVERSION]  DEFAULT ((0)) FOR [ORIGINRECVERSION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBINTERNALORGATTRIBUTEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBINTORGINHERITANCEEXPLODED]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED](
[RECID] [bigint] NOT NULL,
[ANCESTORINTERNALORG] [bigint] NOT NULL,
[DISTANCE] [int] NOT NULL,
[INTERNALORGANIZATION] [bigint] NOT NULL,
[VALIDFROM] [datetime] NOT NULL,
[VALIDFROMTZID] [int] NOT NULL,
[VALIDTO] [datetime] NOT NULL,
[VALIDTOTZID] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1617694060_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1617694060_-824416454] UNIQUE NONCLUSTERED 
(
[VALIDFROM] ASC,
[VALIDTO] ASC,
[INTERNALORGANIZATION] ASC,
[ANCESTORINTERNALORG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTORGINHERITANCEEXPLODED_ANCESTORINTERNALORG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] ADD  CONSTRAINT [DF_RETAILPUBINTORGINHERITANCEEXPLODED_ANCESTORINTERNALORG]  DEFAULT ((0)) FOR [ANCESTORINTERNALORG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTORGINHERITANCEEXPLODED_DISTANCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] ADD  CONSTRAINT [DF_RETAILPUBINTORGINHERITANCEEXPLODED_DISTANCE]  DEFAULT ((0)) FOR [DISTANCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTORGINHERITANCEEXPLODED_INTERNALORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] ADD  CONSTRAINT [DF_RETAILPUBINTORGINHERITANCEEXPLODED_INTERNALORGANIZATION]  DEFAULT ((0)) FOR [INTERNALORGANIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] ADD  CONSTRAINT [DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDFROM]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDFROMTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] ADD  CONSTRAINT [DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDFROMTZID]  DEFAULT ((37001)) FOR [VALIDFROMTZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] ADD  CONSTRAINT [DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDTO]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDTOTZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] ADD  CONSTRAINT [DF_RETAILPUBINTORGINHERITANCEEXPLODED_VALIDTOTZID]  DEFAULT ((37001)) FOR [VALIDTOTZID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBINTORGINHERITANCEEXPLODED] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[ATTRIBUTERELATIONTYPE] [int] NOT NULL,
[DATATYPE] [int] NOT NULL,
[HOSTCHANNEL] [bigint] NOT NULL,
[KEYNAME] [nvarchar](80) NOT NULL,
[METADATA] [nvarchar](max) NULL,
[METADATAVERSION] [int] NOT NULL,
[ORIGINID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1109106661_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1109106661_139093215] UNIQUE NONCLUSTERED 
(
[HOSTCHANNEL] ASC,
[KEYNAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1109106661_2083805687] UNIQUE NONCLUSTERED 
(
[HOSTCHANNEL] ASC,
[ATTRIBUTE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTERELATIONTYPE]  DEFAULT ((0)) FOR [ATTRIBUTERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_DATATYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_DATATYPE]  DEFAULT ((0)) FOR [DATATYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_HOSTCHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_HOSTCHANNEL]  DEFAULT ((0)) FOR [HOSTCHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_KEYNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_KEYNAME]  DEFAULT ('') FOR [KEYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_METADATAVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_METADATAVERSION]  DEFAULT ((0)) FOR [METADATAVERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_ORIGINID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA_ORIGINID]  DEFAULT ((0)) FOR [ORIGINID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBPRODUCTATTRIBUTEVALUE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[CATALOG] [bigint] NOT NULL,
[DATETIMEVALUE] [datetime] NOT NULL,
[DATETIMEVALUETZID] [int] NOT NULL,
[FLOATVALUE] [numeric](32, 16) NOT NULL,
[INTERNALORGANIZATION] [bigint] NOT NULL,
[INTVALUE] [int] NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[TEXTVALUE] [nvarchar](1999) NOT NULL,
[UNITOFMEASURE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2054803486_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2054803486_-1059221112] UNIQUE CLUSTERED 
(
[CATALOG] ASC,
[ATTRIBUTE] ASC,
[PRODUCT] ASC,
[INTERNALORGANIZATION] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_CATALOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_CATALOG]  DEFAULT ((0)) FOR [CATALOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_DATETIMEVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_DATETIMEVALUE]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DATETIMEVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_DATETIMEVALUETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_DATETIMEVALUETZID]  DEFAULT ((37001)) FOR [DATETIMEVALUETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_FLOATVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_FLOATVALUE]  DEFAULT ((0)) FOR [FLOATVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_INTERNALORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_INTERNALORGANIZATION]  DEFAULT ((0)) FOR [INTERNALORGANIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_INTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_INTVALUE]  DEFAULT ((0)) FOR [INTVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_TEXTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_TEXTVALUE]  DEFAULT ('') FOR [TEXTVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBPRODUCTATTRIBUTEVALUE_UNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] ADD  CONSTRAINT [DF_RETAILPUBPRODUCTATTRIBUTEVALUE_UNITOFMEASURE]  DEFAULT ((0)) FOR [UNITOFMEASURE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBRETAILCATALOGPRICEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBRETAILCATALOGPRICEGROUP](
[RECID] [bigint] NOT NULL,
[CATALOG] [bigint] NOT NULL,
[ORIGIN] [bigint] NOT NULL,
[ORIGINRECVERSION] [int] NOT NULL,
[PRICEDISCGROUP] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-191513906_RECID] PRIMARY KEY NONCLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-191513906_1077282324] UNIQUE CLUSTERED 
(
[CATALOG] ASC,
[PRICEDISCGROUP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-191513906_-162312163] UNIQUE NONCLUSTERED 
(
[ORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCATALOGPRICEGROUP_CATALOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCATALOGPRICEGROUP] ADD  CONSTRAINT [DF_RETAILPUBRETAILCATALOGPRICEGROUP_CATALOG]  DEFAULT ((0)) FOR [CATALOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCATALOGPRICEGROUP_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCATALOGPRICEGROUP] ADD  CONSTRAINT [DF_RETAILPUBRETAILCATALOGPRICEGROUP_ORIGIN]  DEFAULT ((0)) FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCATALOGPRICEGROUP_ORIGINRECVERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCATALOGPRICEGROUP] ADD  CONSTRAINT [DF_RETAILPUBRETAILCATALOGPRICEGROUP_ORIGINRECVERSION]  DEFAULT ((0)) FOR [ORIGINRECVERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCATALOGPRICEGROUP_PRICEDISCGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCATALOGPRICEGROUP] ADD  CONSTRAINT [DF_RETAILPUBRETAILCATALOGPRICEGROUP_PRICEDISCGROUP]  DEFAULT ((0)) FOR [PRICEDISCGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBRETAILCATALOGPRICEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[ATTRIBUTEVALUE] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[HOSTCHANNEL] [bigint] NOT NULL,
[KEYNAME] [nvarchar](80) NOT NULL,
[ORIGINID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1690411622_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1690411622_-379952457] UNIQUE NONCLUSTERED 
(
[HOSTCHANNEL] ASC,
[CATEGORY] ASC,
[KEYNAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1690411622_-975995985] UNIQUE NONCLUSTERED 
(
[HOSTCHANNEL] ASC,
[CATEGORY] ASC,
[ATTRIBUTE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_ATTRIBUTEVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_ATTRIBUTEVALUE]  DEFAULT ((0)) FOR [ATTRIBUTEVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_HOSTCHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_HOSTCHANNEL]  DEFAULT ((0)) FOR [HOSTCHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_KEYNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_KEYNAME]  DEFAULT ('') FOR [KEYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_ORIGINID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE_ORIGINID]  DEFAULT ((0)) FOR [ORIGINID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBRETAILCHANNELTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBRETAILCHANNELTABLE](
[RECID] [bigint] NOT NULL,
[CATEGORYHIERARCHY] [bigint] NOT NULL,
[CHANNELTYPE] [int] NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[DEFAULTCUSTACCOUNT] [nvarchar](20) NOT NULL,
[DEFAULTCUSTDATAAREAID] [nvarchar](4) NOT NULL,
[INSTANCERELATIONTYPE] [bigint] NOT NULL,
[INTERNALORGANIZATION] [bigint] NOT NULL,
[INVENTLOCATION] [nvarchar](10) NOT NULL,
[INVENTLOCATIONDATAAREAID] [nvarchar](4) NOT NULL,
[OMOPERATINGUNITID] [bigint] NOT NULL,
[ORIGINID] [bigint] NOT NULL,
[ORIGININSTANCERELATIONTYPE] [bigint] NOT NULL,
[PRICEINCLUDESSALESTAX] [int] NOT NULL,
[TRANSACTIONSERVICEPROFILE] [nvarchar](10) NOT NULL,
[RELATIONTYPE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1526824446_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1526824446_-1636812754] UNIQUE NONCLUSTERED 
(
[OMOPERATINGUNITID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1526824446_-1962010936] UNIQUE NONCLUSTERED 
(
[ORIGINID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_CATEGORYHIERARCHY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_CATEGORYHIERARCHY]  DEFAULT ((0)) FOR [CATEGORYHIERARCHY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_CHANNELTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_CHANNELTYPE]  DEFAULT ((0)) FOR [CHANNELTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_DEFAULTCUSTACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_DEFAULTCUSTACCOUNT]  DEFAULT ('') FOR [DEFAULTCUSTACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_DEFAULTCUSTDATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_DEFAULTCUSTDATAAREAID]  DEFAULT ('') FOR [DEFAULTCUSTDATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_INSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_INSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [INSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_INTERNALORGANIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_INTERNALORGANIZATION]  DEFAULT ((0)) FOR [INTERNALORGANIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_INVENTLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_INVENTLOCATION]  DEFAULT ('') FOR [INVENTLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_INVENTLOCATIONDATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_INVENTLOCATIONDATAAREAID]  DEFAULT ('') FOR [INVENTLOCATIONDATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_OMOPERATINGUNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_OMOPERATINGUNITID]  DEFAULT ((0)) FOR [OMOPERATINGUNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_ORIGINID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_ORIGINID]  DEFAULT ((0)) FOR [ORIGINID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_ORIGININSTANCERELATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_ORIGININSTANCERELATIONTYPE]  DEFAULT ((0)) FOR [ORIGININSTANCERELATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_PRICEINCLUDESSALESTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_PRICEINCLUDESSALESTAX]  DEFAULT ((0)) FOR [PRICEINCLUDESSALESTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILCHANNELTABLE_TRANSACTIONSERVICEPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILCHANNELTABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILCHANNELTABLE_TRANSACTIONSERVICEPROFILE]  DEFAULT ('') FOR [TRANSACTIONSERVICEPROFILE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBRETAILCHANNELTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES](
[RECID] [bigint] NOT NULL,
[ISDEFAULT] [int] NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[ONLINECHANNEL] [bigint] NOT NULL,
[ORIGINID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2045024010_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_2045024010_985177417] UNIQUE NONCLUSTERED 
(
[LANGUAGEID] ASC,
[ONLINECHANNEL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_ISDEFAULT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES] ADD  CONSTRAINT [DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_ISDEFAULT]  DEFAULT ((0)) FOR [ISDEFAULT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES] ADD  CONSTRAINT [DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_ONLINECHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES] ADD  CONSTRAINT [DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_ONLINECHANNEL]  DEFAULT ((0)) FOR [ONLINECHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_ORIGINID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES] ADD  CONSTRAINT [DF_RETAILPUBRETAILONLINECHANNELLANGUAGES_ORIGINID]  DEFAULT ((0)) FOR [ORIGINID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBRETAILONLINECHANNELTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBRETAILONLINECHANNELTABLE](
[RECID] [bigint] NOT NULL,
[ONLINECHANNELORIGINID] [bigint] NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-709636459_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBRETAILONLINECHANNELTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILPUBRETAILSTORETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILPUBRETAILSTORETABLE](
[RECID] [bigint] NOT NULL,
[CLOSINGMETHOD] [int] NULL,
[CREATELABELSFORZEROPRICE] [int] NULL,
[CULTURENAME] [nvarchar](7) NULL,
[FUNCTIONALITYPROFILE] [nvarchar](10) NULL,
[HIDETRAININGMODE] [int] NULL,
[INVENTLOCATIONIDFORCUSTOMERORDER] [nvarchar](10) NULL,
[INVENTORYLOOKUP] [int] NULL,
[ITEMIDONRECEIPT] [int] NULL,
[LAYOUTID] [nvarchar](10) NULL,
[MAXIMUMPOSTINGDIFFERENCE] [numeric](32, 16) NULL,
[MAXIMUMTEXTLENGTHONRECEIPT] [int] NULL,
[MAXROUNDINGAMOUNT] [numeric](32, 16) NULL,
[MAXROUNDINGTAXAMOUNT] [numeric](32, 16) NULL,
[MAXSHIFTDIFFERENCEAMOUNT] [numeric](32, 16) NULL,
[MAXTRANSACTIONDIFFERENCEAMOUNT] [numeric](32, 16) NULL,
[NUMBEROFTOPORBOTTOMLINES] [int] NULL,
[OFFLINEPROFILE] [bigint] NULL,
[ONESTATEMENTPERDAY] [int] NULL,
[OPENFROM] [int] NULL,
[OPENTO] [int] NULL,
[PHONE] [nvarchar](20) NULL,
[REMOVEADDTENDER] [nvarchar](10) NULL,
[REPLICATIONCOUNTER] [int] NULL,
[ROUNDINGTAXACCOUNT] [nvarchar](20) NULL,
[SERVICECHARGEPCT] [numeric](32, 16) NULL,
[SERVICECHARGEPROMPT] [nvarchar](30) NULL,
[STATEMENTMETHOD] [int] NULL,
[STORENUMBER] [nvarchar](10) NOT NULL,
[STOREORIGINID] [bigint] NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXGROUPDATAAREAID] [nvarchar](4) NULL,
[TAXIDENTIFICATIONNUMBER] [nvarchar](25) NULL,
[TAXOVERRIDEGROUP] [bigint] NULL,
[TENDERDECLARATIONCALCULATION] [int] NULL,
[USECUSTOMERBASEDTAX] [int] NULL,
[USEDEFAULTCUSTACCOUNT] [int] NULL,
[USEDESTINATIONBASEDTAX] [int] NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_764396596_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILSTORETABLE_STORENUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILSTORETABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILSTORETABLE_STORENUMBER]  DEFAULT ('') FOR [STORENUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILPUBRETAILSTORETABLE_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILPUBRETAILSTORETABLE] ADD  CONSTRAINT [DF_RETAILPUBRETAILSTORETABLE_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILPUBRETAILSTORETABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILRECEIPTMASKS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILRECEIPTMASKS](
[RECID] [bigint] NOT NULL,
[FUNCPROFILEID] [nvarchar](10) NOT NULL,
[ISINDEPENDENT] [int] NOT NULL,
[MASK] [nvarchar](18) NOT NULL,
[RECEIPTTRANSTYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1819627460_-1375636276] PRIMARY KEY CLUSTERED 
(
[FUNCPROFILEID] ASC,
[RECEIPTTRANSTYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTMASKS_FUNCPROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTMASKS] ADD  CONSTRAINT [DF_RETAILRECEIPTMASKS_FUNCPROFILEID]  DEFAULT ('') FOR [FUNCPROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTMASKS_ISINDEPENDENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTMASKS] ADD  CONSTRAINT [DF_RETAILRECEIPTMASKS_ISINDEPENDENT]  DEFAULT ((0)) FOR [ISINDEPENDENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTMASKS_MASK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTMASKS] ADD  CONSTRAINT [DF_RETAILRECEIPTMASKS_MASK]  DEFAULT ('') FOR [MASK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTMASKS_RECEIPTTRANSTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTMASKS] ADD  CONSTRAINT [DF_RETAILRECEIPTMASKS_RECEIPTTRANSTYPE]  DEFAULT ((0)) FOR [RECEIPTTRANSTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILRECEIPTMASKS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILRECEIPTPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILRECEIPTPROFILE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[PROFILEID] [nvarchar](10) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-254036412_1714895286] PRIMARY KEY CLUSTERED 
(
[PROFILEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTPROFILE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTPROFILE] ADD  CONSTRAINT [DF_RETAILRECEIPTPROFILE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTPROFILE_PROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTPROFILE] ADD  CONSTRAINT [DF_RETAILRECEIPTPROFILE_PROFILEID]  DEFAULT ('') FOR [PROFILEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILRECEIPTPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILRECEIPTPROFILELINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILRECEIPTPROFILELINE](
[RECID] [bigint] NOT NULL,
[FORMLAYOUTID] [nvarchar](10) NOT NULL,
[PROFILEID] [nvarchar](10) NOT NULL,
[RECEIPTTYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1297941798_-1375636276] PRIMARY KEY CLUSTERED 
(
[PROFILEID] ASC,
[RECEIPTTYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTPROFILELINE_FORMLAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTPROFILELINE] ADD  CONSTRAINT [DF_RETAILRECEIPTPROFILELINE_FORMLAYOUTID]  DEFAULT ('') FOR [FORMLAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTPROFILELINE_PROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTPROFILELINE] ADD  CONSTRAINT [DF_RETAILRECEIPTPROFILELINE_PROFILEID]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILRECEIPTPROFILELINE_RECEIPTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILRECEIPTPROFILELINE] ADD  CONSTRAINT [DF_RETAILRECEIPTPROFILELINE_RECEIPTTYPE]  DEFAULT ((0)) FOR [RECEIPTTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILRECEIPTPROFILELINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILREPORTLOCALIZEDSTRING]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILREPORTLOCALIZEDSTRING](
[RECID] [bigint] NOT NULL,
[LOCALECODE] [nvarchar](7) NOT NULL,
[STRINGID] [nvarchar](100) NOT NULL,
[STRINGVALUE] [nvarchar](400) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1485736813_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1485736813_-566285944] UNIQUE NONCLUSTERED 
(
[LOCALECODE] ASC,
[STRINGID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILREPORTLOCALIZEDSTRING_LOCALECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILREPORTLOCALIZEDSTRING] ADD  CONSTRAINT [DF_RETAILREPORTLOCALIZEDSTRING_LOCALECODE]  DEFAULT ('') FOR [LOCALECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILREPORTLOCALIZEDSTRING_STRINGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILREPORTLOCALIZEDSTRING] ADD  CONSTRAINT [DF_RETAILREPORTLOCALIZEDSTRING_STRINGID]  DEFAULT ('') FOR [STRINGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILREPORTLOCALIZEDSTRING_STRINGVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILREPORTLOCALIZEDSTRING] ADD  CONSTRAINT [DF_RETAILREPORTLOCALIZEDSTRING_STRINGVALUE]  DEFAULT ('') FOR [STRINGVALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILREPORTLOCALIZEDSTRING] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILREPORTPERMISSIONGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILREPORTPERMISSIONGROUP](
[RECID] [bigint] NOT NULL,
[RETAILCHANNELREPORTRECID] [bigint] NOT NULL,
[RETAILPOSPERMISSIONGROUPRECID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1465487581_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1465487581_-738656301] UNIQUE NONCLUSTERED 
(
[RETAILPOSPERMISSIONGROUPRECID] ASC,
[RETAILCHANNELREPORTRECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILREPORTPERMISSIONGROUP_RETAILCHANNELREPORTRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILREPORTPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILREPORTPERMISSIONGROUP_RETAILCHANNELREPORTRECID]  DEFAULT ((0)) FOR [RETAILCHANNELREPORTRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILREPORTPERMISSIONGROUP_RETAILPOSPERMISSIONGROUPRECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILREPORTPERMISSIONGROUP] ADD  CONSTRAINT [DF_RETAILREPORTPERMISSIONGROUP_RETAILPOSPERMISSIONGROUPRECID]  DEFAULT ((0)) FOR [RETAILPOSPERMISSIONGROUPRECID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILREPORTPERMISSIONGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSALESTAXOVERRIDE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSALESTAXOVERRIDE](
[RECID] [bigint] NOT NULL,
[ADDITIONALDESCRIPTION] [nvarchar](60) NOT NULL,
[CODE] [nvarchar](25) NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[DESTINATIONITEMTAXGROUP] [nvarchar](10) NOT NULL,
[DESTINATIONTAXGROUP] [nvarchar](10) NOT NULL,
[OVERRIDEBY] [int] NOT NULL,
[OVERRIDEFROM] [int] NOT NULL,
[OVERRIDETO] [int] NOT NULL,
[OVERRIDETYPE] [int] NOT NULL,
[SOURCEITEMTAXGROUP] [nvarchar](10) NOT NULL,
[SOURCETAXGROUP] [nvarchar](10) NOT NULL,
[STATUS] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1829403140_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1829403140_776425418] UNIQUE NONCLUSTERED 
(
[CODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_ADDITIONALDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_ADDITIONALDESCRIPTION]  DEFAULT ('') FOR [ADDITIONALDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_CODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_CODE]  DEFAULT ('') FOR [CODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_DESTINATIONITEMTAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_DESTINATIONITEMTAXGROUP]  DEFAULT ('') FOR [DESTINATIONITEMTAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_DESTINATIONTAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_DESTINATIONTAXGROUP]  DEFAULT ('') FOR [DESTINATIONTAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_OVERRIDEBY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_OVERRIDEBY]  DEFAULT ((0)) FOR [OVERRIDEBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_OVERRIDEFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_OVERRIDEFROM]  DEFAULT ((0)) FOR [OVERRIDEFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_OVERRIDETO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_OVERRIDETO]  DEFAULT ((0)) FOR [OVERRIDETO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_OVERRIDETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_OVERRIDETYPE]  DEFAULT ((0)) FOR [OVERRIDETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_SOURCEITEMTAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_SOURCEITEMTAXGROUP]  DEFAULT ('') FOR [SOURCEITEMTAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_SOURCETAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_SOURCETAXGROUP]  DEFAULT ('') FOR [SOURCETAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDE_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDE] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDE_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSALESTAXOVERRIDE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSALESTAXOVERRIDEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSALESTAXOVERRIDEGROUP](
[RECID] [bigint] NOT NULL,
[CODE] [nvarchar](25) NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1275102027_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1275102027_776425418] UNIQUE NONCLUSTERED 
(
[CODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDEGROUP_CODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDEGROUP] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDEGROUP_CODE]  DEFAULT ('') FOR [CODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDEGROUP_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDEGROUP] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDEGROUP_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSALESTAXOVERRIDEGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSALESTAXOVERRIDEGROUPMEMBER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSALESTAXOVERRIDEGROUPMEMBER](
[RECID] [bigint] NOT NULL,
[RBOSALESTAXOVERRIDECODE] [nvarchar](25) NOT NULL,
[RBOSALESTAXOVERRIDEGROUPCODE] [nvarchar](25) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1138682687_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1138682687_-1481761435] UNIQUE NONCLUSTERED 
(
[RBOSALESTAXOVERRIDEGROUPCODE] ASC,
[RBOSALESTAXOVERRIDECODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDEGROUPMEMBER_RBOSALESTAXOVERRIDECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDEGROUPMEMBER] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDEGROUPMEMBER_RBOSALESTAXOVERRIDECODE]  DEFAULT ('') FOR [RBOSALESTAXOVERRIDECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSALESTAXOVERRIDEGROUPMEMBER_RBOSALESTAXOVERRIDEGROUPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSALESTAXOVERRIDEGROUPMEMBER] ADD  CONSTRAINT [DF_RETAILSALESTAXOVERRIDEGROUPMEMBER_RBOSALESTAXOVERRIDEGROUPCODE]  DEFAULT ('') FOR [RBOSALESTAXOVERRIDEGROUPCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSALESTAXOVERRIDEGROUPMEMBER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSHAREDBINGPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSHAREDBINGPARAMETERS](
[RECID] [bigint] NOT NULL,
[APIKEY] [nvarchar](128) NOT NULL,
[KEY] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1544392866_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1544392866_2053804616] UNIQUE NONCLUSTERED 
(
[KEY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDBINGPARAMETERS_APIKEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDBINGPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDBINGPARAMETERS_APIKEY]  DEFAULT ('') FOR [APIKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDBINGPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDBINGPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDBINGPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSHAREDBINGPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSHAREDPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSHAREDPARAMETERS](
[RECID] [bigint] NOT NULL,
[CATALOGDEFAULTATTRIBUTEGROUP] [bigint] NOT NULL,
[CUSTOMERDEFAULTATTRIBUTEGROUP] [bigint] NOT NULL,
[DEVICETOKENALGORITHM] [nvarchar](25) NOT NULL,
[EARNLOYALTYOFFLINE] [int] NOT NULL,
[EFTPASSWORDENCRYPTION] [nvarchar](25) NOT NULL,
[EXCHANGERATETYPE] [bigint] NOT NULL,
[IMAGESATTRIBUTETYPE] [bigint] NOT NULL,
[KEY] [int] NOT NULL,
[LOCALSTOREID] [nvarchar](10) NOT NULL,
[PRODUCTDEFAULTATTRIBUTEGROUP] [bigint] NOT NULL,
[STAFFPASSWORDHASH] [nvarchar](25) NOT NULL,
[TRANSACTIONSERVICEPROFILE] [nvarchar](10) NOT NULL,
[TSPASSWORDENCRYPTION] [nvarchar](25) NOT NULL,
[VIDEOSATTRIBUTETYPE] [bigint] NOT NULL,
[WORKERDEFAULTATTRIBUTEGROUP] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-820738956_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-820738956_2053804616] UNIQUE NONCLUSTERED 
(
[KEY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_CATALOGDEFAULTATTRIBUTEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_CATALOGDEFAULTATTRIBUTEGROUP]  DEFAULT ((0)) FOR [CATALOGDEFAULTATTRIBUTEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_CUSTOMERDEFAULTATTRIBUTEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_CUSTOMERDEFAULTATTRIBUTEGROUP]  DEFAULT ((0)) FOR [CUSTOMERDEFAULTATTRIBUTEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_DEVICETOKENALGORITHM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_DEVICETOKENALGORITHM]  DEFAULT ('') FOR [DEVICETOKENALGORITHM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_EARNLOYALTYOFFLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_EARNLOYALTYOFFLINE]  DEFAULT ((0)) FOR [EARNLOYALTYOFFLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_EFTPASSWORDENCRYPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_EFTPASSWORDENCRYPTION]  DEFAULT ('') FOR [EFTPASSWORDENCRYPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_EXCHANGERATETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_EXCHANGERATETYPE]  DEFAULT ((0)) FOR [EXCHANGERATETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_IMAGESATTRIBUTETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_IMAGESATTRIBUTETYPE]  DEFAULT ((0)) FOR [IMAGESATTRIBUTETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_LOCALSTOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_LOCALSTOREID]  DEFAULT ('') FOR [LOCALSTOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_PRODUCTDEFAULTATTRIBUTEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_PRODUCTDEFAULTATTRIBUTEGROUP]  DEFAULT ((0)) FOR [PRODUCTDEFAULTATTRIBUTEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_STAFFPASSWORDHASH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_STAFFPASSWORDHASH]  DEFAULT ('') FOR [STAFFPASSWORDHASH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_TRANSACTIONSERVICEPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_TRANSACTIONSERVICEPROFILE]  DEFAULT ('') FOR [TRANSACTIONSERVICEPROFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_TSPASSWORDENCRYPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_TSPASSWORDENCRYPTION]  DEFAULT ('') FOR [TSPASSWORDENCRYPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_VIDEOSATTRIBUTETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_VIDEOSATTRIBUTETYPE]  DEFAULT ((0)) FOR [VIDEOSATTRIBUTETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHAREDPARAMETERS_WORKERDEFAULTATTRIBUTEGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHAREDPARAMETERS] ADD  CONSTRAINT [DF_RETAILSHAREDPARAMETERS_WORKERDEFAULTATTRIBUTEGROUP]  DEFAULT ((0)) FOR [WORKERDEFAULTATTRIBUTEGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSHAREDPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSHIPCARRIERACCOUNTCONFIGURATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSHIPCARRIERACCOUNTCONFIGURATION](
[RECID] [bigint] NOT NULL,
[PROPERTYKEY] [nvarchar](60) NOT NULL,
[SHIPCARRIERCOMPANYACCOUNTS] [bigint] NOT NULL,
[VALUE] [nvarchar](60) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_340920594_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_340920594_1680135326] UNIQUE NONCLUSTERED 
(
[PROPERTYKEY] ASC,
[SHIPCARRIERCOMPANYACCOUNTS] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHIPCARRIERACCOUNTCONFIGURATION_PROPERTYKEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHIPCARRIERACCOUNTCONFIGURATION] ADD  CONSTRAINT [DF_RETAILSHIPCARRIERACCOUNTCONFIGURATION_PROPERTYKEY]  DEFAULT ('') FOR [PROPERTYKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHIPCARRIERACCOUNTCONFIGURATION_SHIPCARRIERCOMPANYACCOUNTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHIPCARRIERACCOUNTCONFIGURATION] ADD  CONSTRAINT [DF_RETAILSHIPCARRIERACCOUNTCONFIGURATION_SHIPCARRIERCOMPANYACCOUNTS]  DEFAULT ((0)) FOR [SHIPCARRIERCOMPANYACCOUNTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHIPCARRIERACCOUNTCONFIGURATION_VALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHIPCARRIERACCOUNTCONFIGURATION] ADD  CONSTRAINT [DF_RETAILSHIPCARRIERACCOUNTCONFIGURATION_VALUE]  DEFAULT ('') FOR [VALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSHIPCARRIERACCOUNTCONFIGURATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSHIPCARRIERINTERFACE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSHIPCARRIERINTERFACE](
[RECID] [bigint] NOT NULL,
[CARRIERADAPTERID] [nvarchar](10) NOT NULL,
[DESCRIPTION] [nvarchar](255) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1914349796_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1914349796_1679934773] UNIQUE NONCLUSTERED 
(
[CARRIERADAPTERID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHIPCARRIERINTERFACE_CARRIERADAPTERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHIPCARRIERINTERFACE] ADD  CONSTRAINT [DF_RETAILSHIPCARRIERINTERFACE_CARRIERADAPTERID]  DEFAULT ('') FOR [CARRIERADAPTERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSHIPCARRIERINTERFACE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSHIPCARRIERINTERFACE] ADD  CONSTRAINT [DF_RETAILSHIPCARRIERINTERFACE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSHIPCARRIERINTERFACE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSPECIALCATEGORYMEMBER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSPECIALCATEGORYMEMBER](
[RECID] [bigint] NOT NULL,
[CATEGORY] [bigint] NOT NULL,
[RETAILGROUPMEMBER] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-689542890_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-689542890_191182833] UNIQUE NONCLUSTERED 
(
[RETAILGROUPMEMBER] ASC,
[CATEGORY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSPECIALCATEGORYMEMBER_CATEGORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSPECIALCATEGORYMEMBER] ADD  CONSTRAINT [DF_RETAILSPECIALCATEGORYMEMBER_CATEGORY]  DEFAULT ((0)) FOR [CATEGORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSPECIALCATEGORYMEMBER_RETAILGROUPMEMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSPECIALCATEGORYMEMBER] ADD  CONSTRAINT [DF_RETAILSPECIALCATEGORYMEMBER_RETAILGROUPMEMBER]  DEFAULT ((0)) FOR [RETAILGROUPMEMBER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSPECIALCATEGORYMEMBER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTAFFEXTENDEDLOGON]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTAFFEXTENDEDLOGON](
[RECID] [bigint] NOT NULL,
[EXTRADATA] [varbinary](max) NULL,
[LOGONKEY] [nvarchar](256) NOT NULL,
[LOGONTYPE] [int] NOT NULL,
[STAFF] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-635492541_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-635492541_-1099356344] UNIQUE NONCLUSTERED 
(
[LOGONKEY] ASC,
[LOGONTYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFEXTENDEDLOGON_LOGONKEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFEXTENDEDLOGON] ADD  CONSTRAINT [DF_RETAILSTAFFEXTENDEDLOGON_LOGONKEY]  DEFAULT ('') FOR [LOGONKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFEXTENDEDLOGON_LOGONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFEXTENDEDLOGON] ADD  CONSTRAINT [DF_RETAILSTAFFEXTENDEDLOGON_LOGONTYPE]  DEFAULT ((0)) FOR [LOGONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFEXTENDEDLOGON_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFEXTENDEDLOGON] ADD  CONSTRAINT [DF_RETAILSTAFFEXTENDEDLOGON_STAFF]  DEFAULT ((0)) FOR [STAFF]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTAFFEXTENDEDLOGON] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTAFFTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTAFFTABLE](
[RECID] [bigint] NOT NULL,
[BLOCKED] [int] NOT NULL,
[CHANGEPASSWORD] [int] NOT NULL,
[CONTINUEONTSERRORS] [int] NOT NULL,
[CULTURENAME] [nvarchar](7) NOT NULL,
[EMPLOYMENTTYPE] [int] NOT NULL,
[IMAGE] [nvarchar](1999) NOT NULL,
[NAMEONRECEIPT] [nvarchar](15) NOT NULL,
[PASSWORD] [nvarchar](32) NOT NULL,
[PASSWORDDATA] [nvarchar](128) NOT NULL,
[STAFFID] [nvarchar](25) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1254821775_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1254821775_1463232915] UNIQUE NONCLUSTERED 
(
[STAFFID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_BLOCKED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_BLOCKED]  DEFAULT ((0)) FOR [BLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_CHANGEPASSWORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_CHANGEPASSWORD]  DEFAULT ((0)) FOR [CHANGEPASSWORD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_CONTINUEONTSERRORS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_CONTINUEONTSERRORS]  DEFAULT ((0)) FOR [CONTINUEONTSERRORS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_CULTURENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_CULTURENAME]  DEFAULT ('') FOR [CULTURENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_EMPLOYMENTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_EMPLOYMENTTYPE]  DEFAULT ((0)) FOR [EMPLOYMENTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_IMAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_IMAGE]  DEFAULT ('') FOR [IMAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_NAMEONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_NAMEONRECEIPT]  DEFAULT ('') FOR [NAMEONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_PASSWORD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_PASSWORD]  DEFAULT ('') FOR [PASSWORD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_PASSWORDDATA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_PASSWORDDATA]  DEFAULT ('') FOR [PASSWORDDATA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_STAFFID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_STAFFID]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTAFFTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTAFFTABLE] ADD  CONSTRAINT [DF_RETAILSTAFFTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTAFFTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTANDARDATTRIBUTE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTANDARDATTRIBUTE](
[RECID] [bigint] NOT NULL,
[ATTRIBUTE] [bigint] NOT NULL,
[STANDARDATTRIBUTEID] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1439487436_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1439487436_-1724774169] UNIQUE NONCLUSTERED 
(
[STANDARDATTRIBUTEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1439487436_1757139105] UNIQUE NONCLUSTERED 
(
[ATTRIBUTE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTANDARDATTRIBUTE_ATTRIBUTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTANDARDATTRIBUTE] ADD  CONSTRAINT [DF_RETAILSTANDARDATTRIBUTE_ATTRIBUTE]  DEFAULT ((0)) FOR [ATTRIBUTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTANDARDATTRIBUTE_STANDARDATTRIBUTEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTANDARDATTRIBUTE] ADD  CONSTRAINT [DF_RETAILSTANDARDATTRIBUTE_STANDARDATTRIBUTEID]  DEFAULT ((0)) FOR [STANDARDATTRIBUTEID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTANDARDATTRIBUTE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTOREADDRESSBOOK]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTOREADDRESSBOOK](
[RECID] [bigint] NOT NULL,
[ADDRESSBOOK] [bigint] NOT NULL,
[ADDRESSBOOKTYPE] [int] NOT NULL,
[STORERECID] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1210059239_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTOREADDRESSBOOK_ADDRESSBOOK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTOREADDRESSBOOK] ADD  CONSTRAINT [DF_RETAILSTOREADDRESSBOOK_ADDRESSBOOK]  DEFAULT ((0)) FOR [ADDRESSBOOK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTOREADDRESSBOOK_ADDRESSBOOKTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTOREADDRESSBOOK] ADD  CONSTRAINT [DF_RETAILSTOREADDRESSBOOK_ADDRESSBOOKTYPE]  DEFAULT ((0)) FOR [ADDRESSBOOKTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTOREADDRESSBOOK_STORERECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTOREADDRESSBOOK] ADD  CONSTRAINT [DF_RETAILSTOREADDRESSBOOK_STORERECID]  DEFAULT ((0)) FOR [STORERECID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTOREADDRESSBOOK] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORECASHDECLARATIONTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORECASHDECLARATIONTABLE](
[RECID] [bigint] NOT NULL,
[AMOUNT] [numeric](32, 16) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-293880745_1360347954] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[CURRENCY] ASC,
[TYPE] ASC,
[AMOUNT] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORECASHDECLARATIONTABLE_AMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORECASHDECLARATIONTABLE] ADD  CONSTRAINT [DF_RETAILSTORECASHDECLARATIONTABLE_AMOUNT]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORECASHDECLARATIONTABLE_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORECASHDECLARATIONTABLE] ADD  CONSTRAINT [DF_RETAILSTORECASHDECLARATIONTABLE_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORECASHDECLARATIONTABLE_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORECASHDECLARATIONTABLE] ADD  CONSTRAINT [DF_RETAILSTORECASHDECLARATIONTABLE_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORECASHDECLARATIONTABLE_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORECASHDECLARATIONTABLE] ADD  CONSTRAINT [DF_RETAILSTORECASHDECLARATIONTABLE_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORECASHDECLARATIONTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORELOCATORGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORELOCATORGROUP](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[NAME] [nvarchar](25) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-660604317_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-660604317_-1966747349] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORELOCATORGROUP_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORELOCATORGROUP] ADD  CONSTRAINT [DF_RETAILSTORELOCATORGROUP_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORELOCATORGROUP_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORELOCATORGROUP] ADD  CONSTRAINT [DF_RETAILSTORELOCATORGROUP_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORELOCATORGROUP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORELOCATORGROUPMEMBER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORELOCATORGROUPMEMBER](
[RECID] [bigint] NOT NULL,
[LOCATORGROUP] [bigint] NOT NULL,
[STORE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-319812993_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-319812993_-276372453] UNIQUE NONCLUSTERED 
(
[LOCATORGROUP] ASC,
[STORE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORELOCATORGROUPMEMBER_LOCATORGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORELOCATORGROUPMEMBER] ADD  CONSTRAINT [DF_RETAILSTORELOCATORGROUPMEMBER_LOCATORGROUP]  DEFAULT ((0)) FOR [LOCATORGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORELOCATORGROUPMEMBER_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORELOCATORGROUPMEMBER] ADD  CONSTRAINT [DF_RETAILSTORELOCATORGROUPMEMBER_STORE]  DEFAULT ((0)) FOR [STORE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORELOCATORGROUPMEMBER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORELOCATORGROUPOWNER]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORELOCATORGROUPOWNER](
[RECID] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[LOCATORGROUP] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2009456858_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2009456858_-276372453] UNIQUE NONCLUSTERED 
(
[CHANNEL] ASC,
[LOCATORGROUP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORELOCATORGROUPOWNER_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORELOCATORGROUPOWNER] ADD  CONSTRAINT [DF_RETAILSTORELOCATORGROUPOWNER_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORELOCATORGROUPOWNER_LOCATORGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORELOCATORGROUPOWNER] ADD  CONSTRAINT [DF_RETAILSTORELOCATORGROUPOWNER_LOCATORGROUP]  DEFAULT ((0)) FOR [LOCATORGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORELOCATORGROUPOWNER] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORETABLE](
[RECID] [bigint] NOT NULL,
[CLOSINGMETHOD] [int] NULL,
[CREATELABELSFORZEROPRICE] [int] NULL,
[CULTURENAME] [nvarchar](7) NULL,
[DATABASENAME] [nvarchar](50) NULL,
[FUNCTIONALITYPROFILE] [nvarchar](10) NULL,
[HIDETRAININGMODE] [int] NULL,
[INVENTLOCATIONIDFORCUSTOMERORDER] [nvarchar](10) NULL,
[INVENTORYLOOKUP] [int] NULL,
[ITEMIDONRECEIPT] [int] NULL,
[MAXIMUMPOSTINGDIFFERENCE] [numeric](32, 16) NULL,
[MAXIMUMTEXTLENGTHONRECEIPT] [int] NULL,
[MAXROUNDINGAMOUNT] [numeric](32, 16) NULL,
[MAXROUNDINGTAXAMOUNT] [numeric](32, 16) NULL,
[MAXSHIFTDIFFERENCEAMOUNT] [numeric](32, 16) NULL,
[MAXTRANSACTIONDIFFERENCEAMOUNT] [numeric](32, 16) NULL,
[NUMBEROFTOPORBOTTOMLINES] [int] NULL,
[OFFLINEPROFILE] [bigint] NULL,
[ONESTATEMENTPERDAY] [int] NULL,
[OPENFROM] [int] NULL,
[OPENTO] [int] NULL,
[PASSWORD] [nvarchar](50) NULL,
[PHONE] [nvarchar](20) NULL,
[REMOVEADDTENDER] [nvarchar](10) NULL,
[REPLICATIONCOUNTER] [int] NULL,
[ROUNDINGTAXACCOUNT] [nvarchar](20) NULL,
[SERVICECHARGEPCT] [numeric](32, 16) NULL,
[SERVICECHARGEPROMPT] [nvarchar](30) NULL,
[SQLSERVERNAME] [nvarchar](80) NULL,
[STATEMENTMETHOD] [int] NULL,
[STMTCALCBATCHENDTIME] [int] NULL,
[STMTPOSTASBUSINESSDAY] [int] NULL,
[STORENUMBER] [nvarchar](10) NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXGROUPDATAAREAID] [nvarchar](4) NULL,
[TAXIDENTIFICATIONNUMBER] [nvarchar](25) NULL,
[TAXOVERRIDEGROUP] [bigint] NULL,
[TENDERDECLARATIONCALCULATION] [int] NULL,
[USECUSTOMERBASEDTAX] [int] NULL,
[USEDEFAULTCUSTACCOUNT] [int] NULL,
[USEDESTINATIONBASEDTAX] [int] NULL,
[USERNAME] [nvarchar](50) NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-355920874_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-355920874_-94122868] UNIQUE NONCLUSTERED 
(
[STORENUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETABLE_STORENUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETABLE] ADD  CONSTRAINT [DF_RETAILSTORETABLE_STORENUMBER]  DEFAULT ('') FOR [STORENUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETABLE_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETABLE] ADD  CONSTRAINT [DF_RETAILSTORETABLE_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORETABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORETABLE_IN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORETABLE_IN](
[RECID] [bigint] NOT NULL,
[RETAILSTORETABLE] [bigint] NOT NULL,
[SALESTAXFORMTYPES] [bigint] NOT NULL,
[SHOWTAXONTAX] [int] NOT NULL,
[TAXDETAILSTYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1889058460_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1889058460_-1306246117] UNIQUE NONCLUSTERED 
(
[RETAILSTORETABLE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETABLE_IN_RETAILSTORETABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETABLE_IN] ADD  CONSTRAINT [DF_RETAILSTORETABLE_IN_RETAILSTORETABLE]  DEFAULT ((0)) FOR [RETAILSTORETABLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETABLE_IN_SALESTAXFORMTYPES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETABLE_IN] ADD  CONSTRAINT [DF_RETAILSTORETABLE_IN_SALESTAXFORMTYPES]  DEFAULT ((0)) FOR [SALESTAXFORMTYPES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETABLE_IN_SHOWTAXONTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETABLE_IN] ADD  CONSTRAINT [DF_RETAILSTORETABLE_IN_SHOWTAXONTAX]  DEFAULT ((0)) FOR [SHOWTAXONTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETABLE_IN_TAXDETAILSTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETABLE_IN] ADD  CONSTRAINT [DF_RETAILSTORETABLE_IN_TAXDETAILSTYPE]  DEFAULT ((0)) FOR [TAXDETAILSTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORETABLE_IN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORETENDERTYPECARDTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE](
[RECID] [bigint] NOT NULL,
[ACCOUNTTYPE] [int] NOT NULL,
[ALLOWMANUALINPUT] [int] NOT NULL,
[CARDFEE] [numeric](32, 16) NOT NULL,
[CARDNUMBERSWIPED] [int] NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[CASHBACKLIMIT] [numeric](32, 16) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CHECKEXPIREDDATE] [int] NOT NULL,
[CHECKMODULUS] [int] NOT NULL,
[COUNTINGREQUIRED] [int] NOT NULL,
[ENTERFLEETINFO] [int] NOT NULL,
[MANUALAUTHORIZATION] [int] NOT NULL,
[MAXNORMALDIFFERENCEAMOUNT] [numeric](32, 16) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PROCESSLOCALLY] [int] NOT NULL,
[SAMECARDALLOWED] [int] NOT NULL,
[TENDERTYPEID] [nvarchar](10) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1457976754_939570618] PRIMARY KEY CLUSTERED 
(
[CHANNEL] ASC,
[TENDERTYPEID] ASC,
[CARDTYPEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_ACCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_ACCOUNTTYPE]  DEFAULT ((0)) FOR [ACCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_ALLOWMANUALINPUT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_ALLOWMANUALINPUT]  DEFAULT ((0)) FOR [ALLOWMANUALINPUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_CARDFEE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_CARDFEE]  DEFAULT ((0)) FOR [CARDFEE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_CARDNUMBERSWIPED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_CARDNUMBERSWIPED]  DEFAULT ((0)) FOR [CARDNUMBERSWIPED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_CARDTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_CARDTYPEID]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_CASHBACKLIMIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_CASHBACKLIMIT]  DEFAULT ((0)) FOR [CASHBACKLIMIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_CHECKEXPIREDDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_CHECKEXPIREDDATE]  DEFAULT ((0)) FOR [CHECKEXPIREDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_CHECKMODULUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_CHECKMODULUS]  DEFAULT ((0)) FOR [CHECKMODULUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_COUNTINGREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_COUNTINGREQUIRED]  DEFAULT ((0)) FOR [COUNTINGREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_ENTERFLEETINFO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_ENTERFLEETINFO]  DEFAULT ((0)) FOR [ENTERFLEETINFO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_MANUALAUTHORIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_MANUALAUTHORIZATION]  DEFAULT ((0)) FOR [MANUALAUTHORIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_MAXNORMALDIFFERENCEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_MAXNORMALDIFFERENCEAMOUNT]  DEFAULT ((0)) FOR [MAXNORMALDIFFERENCEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_PROCESSLOCALLY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_PROCESSLOCALLY]  DEFAULT ((0)) FOR [PROCESSLOCALLY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_SAMECARDALLOWED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_SAMECARDALLOWED]  DEFAULT ((0)) FOR [SAMECARDALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_TENDERTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_TENDERTYPEID]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPECARDTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPECARDTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORETENDERTYPECARDTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILSTORETENDERTYPETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILSTORETENDERTYPETABLE](
[RECID] [bigint] NOT NULL,
[ABOVEMINIMUMTENDERID] [nvarchar](10) NOT NULL,
[ACCOUNTTYPE] [int] NOT NULL,
[ALLOWFLOAT] [int] NOT NULL,
[ALLOWOVERTENDER] [int] NOT NULL,
[ALLOWRETURNNEGATIVE] [int] NOT NULL,
[ALLOWUNDERTENDER] [int] NOT NULL,
[ASKFORDATE] [int] NOT NULL,
[CHANGELINEONRECEIPT] [nvarchar](20) NOT NULL,
[CHANGETENDERID] [nvarchar](10) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CHECKPAYEE] [nvarchar](40) NOT NULL,
[COMPRESSPAYMENTENTRIES] [int] NOT NULL,
[COUNTINGREQUIRED] [int] NOT NULL,
[ENDORSECHECK] [int] NOT NULL,
[ENDORSMENTLINE1] [nvarchar](40) NOT NULL,
[ENDORSMENTLINE2] [nvarchar](40) NOT NULL,
[FISCALPRINTERTENDERTYPE_BR] [nvarchar](20) NOT NULL,
[FRONTOFCHECK] [int] NOT NULL,
[FUNCTION] [int] NOT NULL,
[LINENUMINTRANSACTION] [nvarchar](10) NOT NULL,
[MAXCOUNTINGDIFFERENCE] [numeric](32, 16) NOT NULL,
[MAXIMUMAMOUNTALLOWED] [numeric](32, 16) NOT NULL,
[MAXIMUMAMOUNTENTERED] [numeric](32, 16) NOT NULL,
[MAXIMUMOVERTENDERAMOUNT] [numeric](32, 16) NOT NULL,
[MAXRECOUNT] [int] NOT NULL,
[MINIMUMAMOUNTALLOWED] [numeric](32, 16) NOT NULL,
[MINIMUMAMOUNTENTERED] [numeric](32, 16) NOT NULL,
[MINIMUMCHANGEAMOUNT] [numeric](32, 16) NOT NULL,
[MULTIPLYINTENDEROPERATIONS] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[OPENDRAWER] [int] NOT NULL,
[PAYACCOUNTBILL] [int] NOT NULL,
[POSCOUNTENTRIES] [int] NOT NULL,
[POSOPERATION] [int] NOT NULL,
[ROUNDING] [numeric](32, 16) NOT NULL,
[ROUNDINGMETHOD] [int] NOT NULL,
[SEEKAUTHORIZATION] [int] NOT NULL,
[SIGCAPENABLED] [int] NOT NULL,
[SIGCAPMINAMOUNT] [numeric](32, 16) NOT NULL,
[SLIPBACKINPRINTER] [nvarchar](20) NOT NULL,
[SLIPFRONTINPRINTER] [nvarchar](20) NOT NULL,
[TAKENTOBANK] [int] NOT NULL,
[TAKENTOSAFE] [int] NOT NULL,
[TENDERTYPEID] [nvarchar](10) NOT NULL,
[UNDERTENDERAMOUNT] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1697922944_-828827534] PRIMARY KEY CLUSTERED 
(
[CHANNEL] ASC,
[TENDERTYPEID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ABOVEMINIMUMTENDERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ABOVEMINIMUMTENDERID]  DEFAULT ('') FOR [ABOVEMINIMUMTENDERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ACCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ACCOUNTTYPE]  DEFAULT ((0)) FOR [ACCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ALLOWFLOAT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ALLOWFLOAT]  DEFAULT ((0)) FOR [ALLOWFLOAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ALLOWOVERTENDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ALLOWOVERTENDER]  DEFAULT ((0)) FOR [ALLOWOVERTENDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ALLOWRETURNNEGATIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ALLOWRETURNNEGATIVE]  DEFAULT ((0)) FOR [ALLOWRETURNNEGATIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ALLOWUNDERTENDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ALLOWUNDERTENDER]  DEFAULT ((0)) FOR [ALLOWUNDERTENDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ASKFORDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ASKFORDATE]  DEFAULT ((0)) FOR [ASKFORDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_CHANGELINEONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_CHANGELINEONRECEIPT]  DEFAULT ('') FOR [CHANGELINEONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_CHANGETENDERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_CHANGETENDERID]  DEFAULT ('') FOR [CHANGETENDERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_CHECKPAYEE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_CHECKPAYEE]  DEFAULT ('') FOR [CHECKPAYEE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_COMPRESSPAYMENTENTRIES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_COMPRESSPAYMENTENTRIES]  DEFAULT ((0)) FOR [COMPRESSPAYMENTENTRIES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_COUNTINGREQUIRED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_COUNTINGREQUIRED]  DEFAULT ((0)) FOR [COUNTINGREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ENDORSECHECK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ENDORSECHECK]  DEFAULT ((0)) FOR [ENDORSECHECK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ENDORSMENTLINE1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ENDORSMENTLINE1]  DEFAULT ('') FOR [ENDORSMENTLINE1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ENDORSMENTLINE2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ENDORSMENTLINE2]  DEFAULT ('') FOR [ENDORSMENTLINE2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_FISCALPRINTERTENDERTYPE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_FISCALPRINTERTENDERTYPE_BR]  DEFAULT ('') FOR [FISCALPRINTERTENDERTYPE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_FRONTOFCHECK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_FRONTOFCHECK]  DEFAULT ((0)) FOR [FRONTOFCHECK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_FUNCTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_FUNCTION]  DEFAULT ((0)) FOR [FUNCTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_LINENUMINTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_LINENUMINTRANSACTION]  DEFAULT ('') FOR [LINENUMINTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MAXCOUNTINGDIFFERENCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MAXCOUNTINGDIFFERENCE]  DEFAULT ((0)) FOR [MAXCOUNTINGDIFFERENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MAXIMUMAMOUNTALLOWED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MAXIMUMAMOUNTALLOWED]  DEFAULT ((0)) FOR [MAXIMUMAMOUNTALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MAXIMUMAMOUNTENTERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MAXIMUMAMOUNTENTERED]  DEFAULT ((0)) FOR [MAXIMUMAMOUNTENTERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MAXIMUMOVERTENDERAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MAXIMUMOVERTENDERAMOUNT]  DEFAULT ((0)) FOR [MAXIMUMOVERTENDERAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MAXRECOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MAXRECOUNT]  DEFAULT ((0)) FOR [MAXRECOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MINIMUMAMOUNTALLOWED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MINIMUMAMOUNTALLOWED]  DEFAULT ((0)) FOR [MINIMUMAMOUNTALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MINIMUMAMOUNTENTERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MINIMUMAMOUNTENTERED]  DEFAULT ((0)) FOR [MINIMUMAMOUNTENTERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MINIMUMCHANGEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MINIMUMCHANGEAMOUNT]  DEFAULT ((0)) FOR [MINIMUMCHANGEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_MULTIPLYINTENDEROPERATIONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_MULTIPLYINTENDEROPERATIONS]  DEFAULT ((0)) FOR [MULTIPLYINTENDEROPERATIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_OPENDRAWER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_OPENDRAWER]  DEFAULT ((0)) FOR [OPENDRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_PAYACCOUNTBILL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_PAYACCOUNTBILL]  DEFAULT ((0)) FOR [PAYACCOUNTBILL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_POSCOUNTENTRIES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_POSCOUNTENTRIES]  DEFAULT ((0)) FOR [POSCOUNTENTRIES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_POSOPERATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_POSOPERATION]  DEFAULT ((0)) FOR [POSOPERATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ROUNDING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ROUNDING]  DEFAULT ((0)) FOR [ROUNDING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_ROUNDINGMETHOD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_ROUNDINGMETHOD]  DEFAULT ((0)) FOR [ROUNDINGMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_SEEKAUTHORIZATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_SEEKAUTHORIZATION]  DEFAULT ((0)) FOR [SEEKAUTHORIZATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_SIGCAPENABLED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_SIGCAPENABLED]  DEFAULT ((0)) FOR [SIGCAPENABLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_SIGCAPMINAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_SIGCAPMINAMOUNT]  DEFAULT ((0)) FOR [SIGCAPMINAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_SLIPBACKINPRINTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_SLIPBACKINPRINTER]  DEFAULT ('') FOR [SLIPBACKINPRINTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_SLIPFRONTINPRINTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_SLIPFRONTINPRINTER]  DEFAULT ('') FOR [SLIPFRONTINPRINTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_TAKENTOBANK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_TAKENTOBANK]  DEFAULT ((0)) FOR [TAKENTOBANK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_TAKENTOSAFE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_TAKENTOSAFE]  DEFAULT ((0)) FOR [TAKENTOSAFE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_TENDERTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_TENDERTYPEID]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILSTORETENDERTYPETABLE_UNDERTENDERAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILSTORETENDERTYPETABLE] ADD  CONSTRAINT [DF_RETAILSTORETENDERTYPETABLE_UNDERTENDERAMOUNT]  DEFAULT ((0)) FOR [UNDERTENDERAMOUNT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILSTORETENDERTYPETABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTAXFILTERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTAXFILTERS](
[RECID] [bigint] NOT NULL,
[CITY] [bigint] NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[COUNTYID] [nvarchar](10) NOT NULL,
[DISTRICT] [bigint] NOT NULL,
[STATEID] [nvarchar](10) NOT NULL,
[TAXGROUPHEADING] [nvarchar](10) NOT NULL,
[ZIPCODE] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-491764871_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-491764871_-845285617] UNIQUE NONCLUSTERED 
(
[DISTRICT] ASC,
[ZIPCODE] ASC,
[CITY] ASC,
[COUNTYID] ASC,
[STATEID] ASC,
[COUNTRYREGIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTAXFILTERS_CITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTAXFILTERS] ADD  CONSTRAINT [DF_RETAILTAXFILTERS_CITY]  DEFAULT ((0)) FOR [CITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTAXFILTERS_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTAXFILTERS] ADD  CONSTRAINT [DF_RETAILTAXFILTERS_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTAXFILTERS_COUNTYID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTAXFILTERS] ADD  CONSTRAINT [DF_RETAILTAXFILTERS_COUNTYID]  DEFAULT ('') FOR [COUNTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTAXFILTERS_DISTRICT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTAXFILTERS] ADD  CONSTRAINT [DF_RETAILTAXFILTERS_DISTRICT]  DEFAULT ((0)) FOR [DISTRICT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTAXFILTERS_STATEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTAXFILTERS] ADD  CONSTRAINT [DF_RETAILTAXFILTERS_STATEID]  DEFAULT ('') FOR [STATEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTAXFILTERS_TAXGROUPHEADING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTAXFILTERS] ADD  CONSTRAINT [DF_RETAILTAXFILTERS_TAXGROUPHEADING]  DEFAULT ('') FOR [TAXGROUPHEADING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTAXFILTERS_ZIPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTAXFILTERS] ADD  CONSTRAINT [DF_RETAILTAXFILTERS_ZIPCODE]  DEFAULT ((0)) FOR [ZIPCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTAXFILTERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTENDERTYPECARDNUMBERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTENDERTYPECARDNUMBERS](
[RECID] [bigint] NOT NULL,
[CARDNUMBERFROM] [nvarchar](30) NOT NULL,
[CARDNUMBERLENGTH] [int] NOT NULL,
[CARDNUMBERTO] [nvarchar](30) NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2117254335_1729673423] PRIMARY KEY CLUSTERED 
(
[CARDTYPEID] ASC,
[CARDNUMBERFROM] ASC,
[CARDNUMBERTO] ASC,
[CARDNUMBERLENGTH] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDNUMBERS_CARDNUMBERFROM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDNUMBERS] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDNUMBERS_CARDNUMBERFROM]  DEFAULT ('') FOR [CARDNUMBERFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDNUMBERS_CARDNUMBERLENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDNUMBERS] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDNUMBERS_CARDNUMBERLENGTH]  DEFAULT ((0)) FOR [CARDNUMBERLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDNUMBERS_CARDNUMBERTO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDNUMBERS] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDNUMBERS_CARDNUMBERTO]  DEFAULT ('') FOR [CARDNUMBERTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDNUMBERS_CARDTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDNUMBERS] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDNUMBERS_CARDTYPEID]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDNUMBERS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDNUMBERS] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDNUMBERS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTENDERTYPECARDNUMBERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTENDERTYPECARDTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTENDERTYPECARDTABLE](
[RECID] [bigint] NOT NULL,
[CARDISSUER] [nvarchar](60) NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[CARDTYPES] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1446778053_-1743312871] PRIMARY KEY CLUSTERED 
(
[CARDTYPEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDTABLE_CARDISSUER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDTABLE_CARDISSUER]  DEFAULT ('') FOR [CARDISSUER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDTABLE_CARDTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDTABLE_CARDTYPEID]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDTABLE_CARDTYPES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDTABLE_CARDTYPES]  DEFAULT ((0)) FOR [CARDTYPES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTENDERTYPECARDTABLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTENDERTYPECARDTABLE] ADD  CONSTRAINT [DF_RETAILTENDERTYPECARDTABLE_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTENDERTYPECARDTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTERMINALCUSTOMFIELD]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTERMINALCUSTOMFIELD](
[RECID] [bigint] NOT NULL,
[CAPTIONTEXTID] [int] NOT NULL,
[NAME] [nvarchar](50) NOT NULL,
[TYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2146898594_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_2146898594_1555050992] UNIQUE NONCLUSTERED 
(
[NAME] ASC,
[TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALCUSTOMFIELD_CAPTIONTEXTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALCUSTOMFIELD] ADD  CONSTRAINT [DF_RETAILTERMINALCUSTOMFIELD_CAPTIONTEXTID]  DEFAULT ((0)) FOR [CAPTIONTEXTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALCUSTOMFIELD_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALCUSTOMFIELD] ADD  CONSTRAINT [DF_RETAILTERMINALCUSTOMFIELD_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALCUSTOMFIELD_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALCUSTOMFIELD] ADD  CONSTRAINT [DF_RETAILTERMINALCUSTOMFIELD_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTERMINALCUSTOMFIELD] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTERMINALDEVICE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTERMINALDEVICE](
[RECID] [bigint] NOT NULL,
[DEVICE] [bigint] NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1106247877_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1106247877_1900032017] UNIQUE NONCLUSTERED 
(
[TERMINALID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1106247877_-34442163] UNIQUE NONCLUSTERED 
(
[DEVICE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALDEVICE_DEVICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALDEVICE] ADD  CONSTRAINT [DF_RETAILTERMINALDEVICE_DEVICE]  DEFAULT ((0)) FOR [DEVICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALDEVICE_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALDEVICE] ADD  CONSTRAINT [DF_RETAILTERMINALDEVICE_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALDEVICE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALDEVICE] ADD  CONSTRAINT [DF_RETAILTERMINALDEVICE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTERMINALDEVICE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTERMINALTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTERMINALTABLE](
[RECID] [bigint] NOT NULL,
[AUTOLOGOFFTIMEOUT] [int] NOT NULL,
[CLOSINGSTATUS] [int] NOT NULL,
[CUSTOMERDISPLAYTEXT1] [nvarchar](40) NOT NULL,
[CUSTOMERDISPLAYTEXT2] [nvarchar](40) NOT NULL,
[EFTSTORERECID] [bigint] NOT NULL,
[EFTTENDERTYPEIDDEFAULT] [nvarchar](10) NOT NULL,
[EFTTERMINALID] [nvarchar](10) NOT NULL,
[EXITAFTEREACHTRANSACTION] [int] NOT NULL,
[HARDWAREPROFILE] [nvarchar](10) NOT NULL,
[IPADDRESS] [nvarchar](255) NOT NULL,
[ITEMIDONRECEIPT] [int] NOT NULL,
[LAYOUTID] [nvarchar](10) NOT NULL,
[LOCATION] [nvarchar](60) NOT NULL,
[MANAGERKEYONRETURN] [int] NOT NULL,
[MAXDISPLAYTEXTLENGTH] [int] NOT NULL,
[MAXRECEIPTTEXTLENGTH] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[NOTACTIVE] [int] NOT NULL,
[NUMBEROFTOPBOTTOMLINES] [int] NOT NULL,
[ONLYTOTALINSUSPENDEDTRANSACTION] [int] NOT NULL,
[OPENDRAWERATLILO] [int] NOT NULL,
[PRINTVATREFUNDCHECKS] [int] NOT NULL,
[RECEIPTBARCODE] [int] NOT NULL,
[RECEIPTPRINTINGDEFAULTOFF] [int] NOT NULL,
[RECEIPTSETUPLOCATION] [int] NOT NULL,
[RETURNINTRANSACTION] [int] NOT NULL,
[SLIPIFRETURN] [int] NOT NULL,
[STANDALONE] [int] NOT NULL,
[STATEMENTMETHOD] [int] NOT NULL,
[STORERECID] [bigint] NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TERMINALSTATEMENT] [int] NOT NULL,
[UPDATESERVICEPORT] [int] NOT NULL,
[VISUALPROFILE] [nvarchar](10) NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1485945225_417776753] PRIMARY KEY CLUSTERED 
(
[TERMINALID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_AUTOLOGOFFTIMEOUT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_AUTOLOGOFFTIMEOUT]  DEFAULT ((0)) FOR [AUTOLOGOFFTIMEOUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_CLOSINGSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_CLOSINGSTATUS]  DEFAULT ((0)) FOR [CLOSINGSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_CUSTOMERDISPLAYTEXT1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_CUSTOMERDISPLAYTEXT1]  DEFAULT ('') FOR [CUSTOMERDISPLAYTEXT1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_CUSTOMERDISPLAYTEXT2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_CUSTOMERDISPLAYTEXT2]  DEFAULT ('') FOR [CUSTOMERDISPLAYTEXT2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_EFTSTORERECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_EFTSTORERECID]  DEFAULT ((0)) FOR [EFTSTORERECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_EFTTENDERTYPEIDDEFAULT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_EFTTENDERTYPEIDDEFAULT]  DEFAULT ('') FOR [EFTTENDERTYPEIDDEFAULT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_EFTTERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_EFTTERMINALID]  DEFAULT ('') FOR [EFTTERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_EXITAFTEREACHTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_EXITAFTEREACHTRANSACTION]  DEFAULT ((0)) FOR [EXITAFTEREACHTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_HARDWAREPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_HARDWAREPROFILE]  DEFAULT ('') FOR [HARDWAREPROFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_IPADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_IPADDRESS]  DEFAULT ('') FOR [IPADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_ITEMIDONRECEIPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_ITEMIDONRECEIPT]  DEFAULT ((0)) FOR [ITEMIDONRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_LAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_LAYOUTID]  DEFAULT ('') FOR [LAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_LOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_LOCATION]  DEFAULT ('') FOR [LOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_MANAGERKEYONRETURN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_MANAGERKEYONRETURN]  DEFAULT ((0)) FOR [MANAGERKEYONRETURN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_MAXDISPLAYTEXTLENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_MAXDISPLAYTEXTLENGTH]  DEFAULT ((0)) FOR [MAXDISPLAYTEXTLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_MAXRECEIPTTEXTLENGTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_MAXRECEIPTTEXTLENGTH]  DEFAULT ((0)) FOR [MAXRECEIPTTEXTLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_NOTACTIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_NOTACTIVE]  DEFAULT ((0)) FOR [NOTACTIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_NUMBEROFTOPBOTTOMLINES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_NUMBEROFTOPBOTTOMLINES]  DEFAULT ((0)) FOR [NUMBEROFTOPBOTTOMLINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_ONLYTOTALINSUSPENDEDTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_ONLYTOTALINSUSPENDEDTRANSACTION]  DEFAULT ((0)) FOR [ONLYTOTALINSUSPENDEDTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_OPENDRAWERATLILO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_OPENDRAWERATLILO]  DEFAULT ((0)) FOR [OPENDRAWERATLILO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_PRINTVATREFUNDCHECKS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_PRINTVATREFUNDCHECKS]  DEFAULT ((0)) FOR [PRINTVATREFUNDCHECKS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_RECEIPTBARCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_RECEIPTBARCODE]  DEFAULT ((0)) FOR [RECEIPTBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_RECEIPTPRINTINGDEFAULTOFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_RECEIPTPRINTINGDEFAULTOFF]  DEFAULT ((0)) FOR [RECEIPTPRINTINGDEFAULTOFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_RECEIPTSETUPLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_RECEIPTSETUPLOCATION]  DEFAULT ((0)) FOR [RECEIPTSETUPLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_RETURNINTRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_RETURNINTRANSACTION]  DEFAULT ((0)) FOR [RETURNINTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_SLIPIFRETURN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_SLIPIFRETURN]  DEFAULT ((0)) FOR [SLIPIFRETURN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_STANDALONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_STANDALONE]  DEFAULT ((0)) FOR [STANDALONE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_STATEMENTMETHOD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_STATEMENTMETHOD]  DEFAULT ((0)) FOR [STATEMENTMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_STORERECID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_STORERECID]  DEFAULT ((0)) FOR [STORERECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_TERMINALSTATEMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_TERMINALSTATEMENT]  DEFAULT ((0)) FOR [TERMINALSTATEMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_UPDATESERVICEPORT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_UPDATESERVICEPORT]  DEFAULT ((0)) FOR [UPDATESERVICEPORT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_VISUALPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_VISUALPROFILE]  DEFAULT ('') FOR [VISUALPROFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTERMINALTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTERMINALTABLE] ADD  CONSTRAINT [DF_RETAILTERMINALTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTERMINALTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTHEMEACCENT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTHEMEACCENT](
[RECID] [bigint] NOT NULL,
[ACCENTID] [nvarchar](20) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-428006304_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTHEMEACCENT_ACCENTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTHEMEACCENT] ADD  CONSTRAINT [DF_RETAILTHEMEACCENT_ACCENTID]  DEFAULT ('') FOR [ACCENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTHEMEACCENT_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTHEMEACCENT] ADD  CONSTRAINT [DF_RETAILTHEMEACCENT_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTHEMEACCENT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTHEMEACCENTCOLOR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTHEMEACCENTCOLOR](
[RECID] [bigint] NOT NULL,
[ACCENT] [bigint] NOT NULL,
[COLOR] [int] NOT NULL,
[PALLET] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1375997065_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1375997065_1327556950] UNIQUE NONCLUSTERED 
(
[PALLET] ASC,
[ACCENT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTHEMEACCENTCOLOR_ACCENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTHEMEACCENTCOLOR] ADD  CONSTRAINT [DF_RETAILTHEMEACCENTCOLOR_ACCENT]  DEFAULT ((0)) FOR [ACCENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTHEMEACCENTCOLOR_COLOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTHEMEACCENTCOLOR] ADD  CONSTRAINT [DF_RETAILTHEMEACCENTCOLOR_COLOR]  DEFAULT ((0)) FOR [COLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTHEMEACCENTCOLOR_PALLET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTHEMEACCENTCOLOR] ADD  CONSTRAINT [DF_RETAILTHEMEACCENTCOLOR_PALLET]  DEFAULT ((0)) FOR [PALLET]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTHEMEACCENTCOLOR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTHEMEPALLET]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTHEMEPALLET](
[RECID] [bigint] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1830151484_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTHEMEPALLET_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTHEMEPALLET] ADD  CONSTRAINT [DF_RETAILTHEMEPALLET_NAME]  DEFAULT ('') FOR [NAME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTHEMEPALLET] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUT](
[RECID] [bigint] NOT NULL,
[CASHCHANGERLAYOUTXML] [nvarchar](max) NULL,
[CUSTOMERLAYOUTID] [nvarchar](10) NOT NULL,
[CUSTOMERLAYOUTXML] [nvarchar](max) NULL,
[DEVICETYPE] [bigint] NOT NULL,
[HEIGHT] [int] NOT NULL,
[IMG_CASHCHANGERLAYOUTXML] [varbinary](max) NULL,
[LAYOUTID] [nvarchar](10) NOT NULL,
[LAYOUTXML] [nvarchar](max) NULL,
[NAME] [nvarchar](50) NOT NULL,
[RECEIPTID] [nvarchar](10) NOT NULL,
[RECEIPTITEMSLAYOUTXML] [nvarchar](max) NULL,
[RECEIPTPAYMENTLAYOUTXML] [nvarchar](max) NULL,
[TOTALID] [nvarchar](10) NOT NULL,
[TOTALSLAYOUTXML] [nvarchar](max) NULL,
[WIDTH] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1652157140_1814737115] PRIMARY KEY CLUSTERED 
(
[LAYOUTID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_CUSTOMERLAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_CUSTOMERLAYOUTID]  DEFAULT ('') FOR [CUSTOMERLAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_DEVICETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_DEVICETYPE]  DEFAULT ((0)) FOR [DEVICETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_HEIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_HEIGHT]  DEFAULT ((0)) FOR [HEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_LAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_LAYOUTID]  DEFAULT ('') FOR [LAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_TOTALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_TOTALID]  DEFAULT ('') FOR [TOTALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUT_WIDTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUT] ADD  CONSTRAINT [DF_RETAILTILLLAYOUT_WIDTH]  DEFAULT ((0)) FOR [WIDTH]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUTBUTTONGRIDZONE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUTBUTTONGRIDZONE](
[RECID] [bigint] NOT NULL,
[BUTTONGRIDID] [nvarchar](10) NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-611258122_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUTBUTTONGRIDZONE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUTIMAGEZONE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUTIMAGEZONE](
[RECID] [bigint] NOT NULL,
[PICTUREID] [int] NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1321184049_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUTIMAGEZONE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUTREPORTZONE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUTREPORTZONE](
[RECID] [bigint] NOT NULL,
[REPORT] [bigint] NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1408251020_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUTREPORTZONE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUTSTAFF]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUTSTAFF](
[RECID] [bigint] NOT NULL,
[LAYOUTID] [nvarchar](10) NOT NULL,
[STAFF] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1600860122_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1600860122_-519367667] UNIQUE NONCLUSTERED 
(
[LAYOUTID] ASC,
[STAFF] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTSTAFF_LAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTSTAFF] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTSTAFF_LAYOUTID]  DEFAULT ('') FOR [LAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTSTAFF_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTSTAFF] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTSTAFF_STAFF]  DEFAULT ((0)) FOR [STAFF]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUTSTAFF] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUTSTORE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUTSTORE](
[RECID] [bigint] NOT NULL,
[LAYOUTID] [nvarchar](10) NOT NULL,
[STORE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-343952049_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-343952049_1504114108] UNIQUE NONCLUSTERED 
(
[STORE] ASC,
[LAYOUTID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTSTORE_LAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTSTORE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTSTORE_LAYOUTID]  DEFAULT ('') FOR [LAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTSTORE_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTSTORE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTSTORE_STORE]  DEFAULT ((0)) FOR [STORE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUTSTORE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUTZONE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUTZONE](
[RECID] [bigint] NOT NULL,
[DEVICETYPE] [bigint] NOT NULL,
[ZONEID] [nvarchar](20) NOT NULL,
[ZONENAME] [nvarchar](60) NOT NULL,
[ZONETYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1703816734_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTZONE_DEVICETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTZONE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTZONE_DEVICETYPE]  DEFAULT ((0)) FOR [DEVICETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTZONE_ZONEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTZONE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTZONE_ZONEID]  DEFAULT ('') FOR [ZONEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTZONE_ZONENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTZONE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTZONE_ZONENAME]  DEFAULT ('') FOR [ZONENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTZONE_ZONETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTZONE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTZONE_ZONETYPE]  DEFAULT ((0)) FOR [ZONETYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUTZONE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTILLLAYOUTZONEREFERENCE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTILLLAYOUTZONEREFERENCE](
[RECID] [bigint] NOT NULL,
[LAYOUTID] [nvarchar](10) NOT NULL,
[ZONE] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1413176897_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1413176897_-199417707] UNIQUE NONCLUSTERED 
(
[ZONE] ASC,
[LAYOUTID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTZONEREFERENCE_LAYOUTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTZONEREFERENCE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTZONEREFERENCE_LAYOUTID]  DEFAULT ('') FOR [LAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTILLLAYOUTZONEREFERENCE_ZONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTILLLAYOUTZONEREFERENCE] ADD  CONSTRAINT [DF_RETAILTILLLAYOUTZONEREFERENCE_ZONE]  DEFAULT ((0)) FOR [ZONE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTILLLAYOUTZONEREFERENCE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONADDRESSTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS](
[CHANNEL] [bigint] NOT NULL,
[CITY] [nvarchar](60) NOT NULL,
[COUNTRYREGIONID] [nvarchar](10) NOT NULL,
[COUNTY] [nvarchar](10) NOT NULL,
[DELIVERYNAME] [nvarchar](100) NOT NULL,
[DISTRICTNAME] [nvarchar](60) NOT NULL,
[EMAIL] [nvarchar](80) NOT NULL,
[EMAILCONTENT] [nvarchar](400) NOT NULL,
[PHONE] [nvarchar](20) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SALELINENUM] [numeric](32, 16) NOT NULL,
[SALESNAME] [nvarchar](60) NOT NULL,
[STATE] [nvarchar](10) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[STREET] [nvarchar](250) NOT NULL,
[STREETNUMBER] [nvarchar](20) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[ZIPCODE] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2016080543_-1586875080] PRIMARY KEY CLUSTERED 
(
[TRANSACTIONID] ASC,
[TERMINAL] ASC,
[STORE] ASC,
[SALELINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONADDRESSTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_CITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_CITY]  DEFAULT ('') FOR [CITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_COUNTRYREGIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_COUNTRYREGIONID]  DEFAULT ('') FOR [COUNTRYREGIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_COUNTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_COUNTY]  DEFAULT ('') FOR [COUNTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_DELIVERYNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_DELIVERYNAME]  DEFAULT ('') FOR [DELIVERYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_DISTRICTNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_DISTRICTNAME]  DEFAULT ('') FOR [DISTRICTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_EMAIL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_EMAIL]  DEFAULT ('') FOR [EMAIL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_EMAILCONTENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_EMAILCONTENT]  DEFAULT ('') FOR [EMAILCONTENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_PHONE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_PHONE]  DEFAULT ('') FOR [PHONE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_SALELINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_SALELINENUM]  DEFAULT ((0)) FOR [SALELINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_SALESNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_SALESNAME]  DEFAULT ('') FOR [SALESNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_STATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_STATE]  DEFAULT ('') FOR [STATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_STREET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_STREET]  DEFAULT ('') FOR [STREET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_STREETNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_STREETNUMBER]  DEFAULT ('') FOR [STREETNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONADDRESSTRANS_ZIPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONADDRESSTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONADDRESSTRANS_ZIPCODE]  DEFAULT ('') FOR [ZIPCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONADDRESSTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONAFFILIATIONTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS](
[AFFILIATION] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[LOYALTYTIER] [bigint] NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STAFFID] [nvarchar](25) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[CREATEDTRANSACTIONID] [bigint] NOT NULL,
[MODIFIEDTRANSACTIONID] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_290532277_-1746289153] PRIMARY KEY CLUSTERED 
(
[AFFILIATION] ASC,
[LOYALTYTIER] ASC,
[CHANNEL] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONAFFILIATIONTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_AFFILIATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_AFFILIATION]  DEFAULT ((0)) FOR [AFFILIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_LOYALTYTIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_LOYALTYTIER]  DEFAULT ((0)) FOR [LOYALTYTIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_STAFFID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_STAFFID]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_CREATEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_CREATEDTRANSACTIONID]  DEFAULT ((0)) FOR [CREATEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONAFFILIATIONTRANS_MODIFIEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONAFFILIATIONTRANS_MODIFIEDTRANSACTIONID]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONAFFILIATIONTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONATTRIBUTETRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONATTRIBUTETRANS](
[CHANNEL] [bigint] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TEXTVALUE] [nvarchar](1999) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1620058971_-2013298691] PRIMARY KEY CLUSTERED 
(
[NAME] ASC,
[TRANSACTIONID] ASC,
[TERMINAL] ASC,
[STORE] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONATTRIBUTETRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONATTRIBUTETRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONATTRIBUTETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONATTRIBUTETRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONATTRIBUTETRANS_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONATTRIBUTETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONATTRIBUTETRANS_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONATTRIBUTETRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONATTRIBUTETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONATTRIBUTETRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONATTRIBUTETRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONATTRIBUTETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONATTRIBUTETRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONATTRIBUTETRANS_TEXTVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONATTRIBUTETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONATTRIBUTETRANS_TEXTVALUE]  DEFAULT ('') FOR [TEXTVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONATTRIBUTETRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONATTRIBUTETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONATTRIBUTETRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONATTRIBUTETRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONBANKEDTENDERTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS](
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[AMOUNTCURPOS] [numeric](32, 16) NOT NULL,
[AMOUNTMST] [numeric](32, 16) NOT NULL,
[AMOUNTMSTPOS] [numeric](32, 16) NOT NULL,
[AMOUNTTENDERED] [numeric](32, 16) NOT NULL,
[AMOUNTTENDEREDPOS] [numeric](32, 16) NOT NULL,
[BANKBAGNO] [nvarchar](30) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CARDORACCOUNT] [nvarchar](30) NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[CHANGELINE] [int] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[COUNTER] [numeric](32, 16) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[EXCHRATE] [numeric](32, 16) NOT NULL,
[EXCHRATEMST] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[MANAGERSKEYLIVE] [int] NOT NULL,
[MESSAGENUM] [int] NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STATUSTYPE] [int] NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TENDERTYPE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[CREATEDTRANSACTIONID] [bigint] NOT NULL,
[MODIFIEDTRANSACTIONID] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_85947504_133413727] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONBANKEDTENDERTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTCUR]  DEFAULT ((0)) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTCURPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTCURPOS]  DEFAULT ((0)) FOR [AMOUNTCURPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTMST]  DEFAULT ((0)) FOR [AMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTMSTPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTMSTPOS]  DEFAULT ((0)) FOR [AMOUNTMSTPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTTENDERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTTENDERED]  DEFAULT ((0)) FOR [AMOUNTTENDERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTTENDEREDPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_AMOUNTTENDEREDPOS]  DEFAULT ((0)) FOR [AMOUNTTENDEREDPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_BANKBAGNO]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_BANKBAGNO]  DEFAULT ('') FOR [BANKBAGNO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CARDORACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CARDORACCOUNT]  DEFAULT ('') FOR [CARDORACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CARDTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CARDTYPEID]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CHANGELINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CHANGELINE]  DEFAULT ((0)) FOR [CHANGELINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_COUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_COUNTER]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_EXCHRATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_EXCHRATE]  DEFAULT ((0)) FOR [EXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_EXCHRATEMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_EXCHRATEMST]  DEFAULT ((0)) FOR [EXCHRATEMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MANAGERSKEYLIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MANAGERSKEYLIVE]  DEFAULT ((0)) FOR [MANAGERSKEYLIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MESSAGENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MESSAGENUM]  DEFAULT ((0)) FOR [MESSAGENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_SHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_SHIFT]  DEFAULT ('') FOR [SHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_SHIFTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_SHIFTDATE]  DEFAULT ('1900-01-01') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STAFF]  DEFAULT ('') FOR [STAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STATUSTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STATUSTYPE]  DEFAULT ((0)) FOR [STATUSTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TENDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TENDERTYPE]  DEFAULT ('') FOR [TENDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CREATEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_CREATEDTRANSACTIONID]  DEFAULT ((0)) FOR [CREATEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MODIFIEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONBANKEDTENDERTRANS_MODIFIEDTRANSACTIONID]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONDISCOUNTTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS](
[AMOUNT] [numeric](32, 16) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CUSTOMERDISCOUNTTYPE] [int] NOT NULL,
[DEALPRICE] [numeric](32, 16) NOT NULL,
[DISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[DISCOUNTCODE] [nvarchar](15) NOT NULL,
[DISCOUNTORIGINTYPE] [int] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[MANUALDISCOUNTTYPE] [int] NOT NULL,
[PERCENTAGE] [numeric](32, 16) NOT NULL,
[PERIODICDISCOUNTOFFERID] [nvarchar](20) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SALELINENUM] [numeric](32, 16) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-363309914_372431339] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[SALELINENUM] ASC,
[CHANNEL] ASC,
[LINENUM] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONDISCOUNTTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_AMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_AMOUNT]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_CUSTOMERDISCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_CUSTOMERDISCOUNTTYPE]  DEFAULT ((0)) FOR [CUSTOMERDISCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_DEALPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_DEALPRICE]  DEFAULT ((0)) FOR [DEALPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_DISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_DISCOUNTAMOUNT]  DEFAULT ((0)) FOR [DISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_DISCOUNTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_DISCOUNTCODE]  DEFAULT ('') FOR [DISCOUNTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_DISCOUNTORIGINTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_DISCOUNTORIGINTYPE]  DEFAULT ((0)) FOR [DISCOUNTORIGINTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_MANUALDISCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_MANUALDISCOUNTTYPE]  DEFAULT ((0)) FOR [MANUALDISCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_PERCENTAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_PERCENTAGE]  DEFAULT ((0)) FOR [PERCENTAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_PERIODICDISCOUNTOFFERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_PERIODICDISCOUNTOFFERID]  DEFAULT ('') FOR [PERIODICDISCOUNTOFFERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_SALELINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_SALELINENUM]  DEFAULT ((0)) FOR [SALELINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONDISCOUNTTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONDISCOUNTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONDISCOUNTTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONDISCOUNTTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS](
[ACCOUNTTYPE] [int] NOT NULL,
[AMOUNT] [numeric](32, 16) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[COUNTER] [int] NOT NULL,
[INCOMEEXEPENSEACCOUNT] [nvarchar](10) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1072989706_133413727] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONINCOMEEXPENSETRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_ACCOUNTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_ACCOUNTTYPE]  DEFAULT ((0)) FOR [ACCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_AMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_AMOUNT]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_COUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_COUNTER]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_INCOMEEXEPENSEACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_INCOMEEXEPENSEACCOUNT]  DEFAULT ('') FOR [INCOMEEXEPENSEACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_SHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_SHIFT]  DEFAULT ('') FOR [SHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_SHIFTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_SHIFTDATE]  DEFAULT ('1900-01-01') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_STAFF]  DEFAULT ('') FOR [STAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINCOMEEXPENSETRANS_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONINFOCODETRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS](
[AMOUNT] [numeric](32, 16) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[COUNTER] [int] NOT NULL,
[INFOAMOUNT] [numeric](32, 16) NOT NULL,
[INFOCODEID] [nvarchar](10) NOT NULL,
[INFORMATION] [nvarchar](100) NOT NULL,
[INPUTTYPE] [int] NOT NULL,
[ITEMTENDER] [nvarchar](10) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[PARENTLINENUM] [numeric](32, 16) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SOURCECODE] [nvarchar](20) NOT NULL,
[SOURCECODE2] [nvarchar](20) NOT NULL,
[SOURCECODE3] [nvarchar](20) NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[SUBINFOCODEID] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[TYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1348077048_-1126114694] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TYPE] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[INFOCODEID] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONINFOCODETRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_AMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_AMOUNT]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_COUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_COUNTER]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_INFOAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_INFOAMOUNT]  DEFAULT ((0)) FOR [INFOAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_INFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_INFOCODEID]  DEFAULT ('') FOR [INFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_INFORMATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_INFORMATION]  DEFAULT ('') FOR [INFORMATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_INPUTTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_INPUTTYPE]  DEFAULT ((0)) FOR [INPUTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_ITEMTENDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_ITEMTENDER]  DEFAULT ('') FOR [ITEMTENDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_PARENTLINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_PARENTLINENUM]  DEFAULT ((0)) FOR [PARENTLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_SOURCECODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_SOURCECODE]  DEFAULT ('') FOR [SOURCECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_SOURCECODE2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_SOURCECODE2]  DEFAULT ('') FOR [SOURCECODE2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_SOURCECODE3]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_SOURCECODE3]  DEFAULT ('') FOR [SOURCECODE3]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_STAFF]  DEFAULT ('') FOR [STAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_SUBINFOCODEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_SUBINFOCODEID]  DEFAULT ('') FOR [SUBINFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONINFOCODETRANS_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONINFOCODETRANS_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONINFOCODETRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS](
[CHANNEL] [bigint] NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTER] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[VARIANTID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-773381400_324085071] PRIMARY KEY CLUSTERED 
(
[LINENUM] ASC,
[CHANNEL] ASC,
[TERMINALID] ASC,
[STOREID] ASC,
[TRANSACTIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_REPLICATIONCOUNTER] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_VARIANTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONKITSDISASSEMBLYTRANS_VARIANTID]  DEFAULT ('') FOR [VARIANTID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONMARKUPTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS](
[CALCULATEDAMOUNT] [numeric](32, 16) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[MARKUPCODE] [nvarchar](10) NOT NULL,
[MARKUPLINENUM] [numeric](32, 16) NOT NULL,
[METHOD] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SALELINENUM] [numeric](32, 16) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TAXAMOUNT] [numeric](32, 16) NOT NULL,
[TAXAMOUNTEXCLUSIVE] [numeric](32, 16) NOT NULL,
[TAXAMOUNTINCLUSIVE] [numeric](32, 16) NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[VALUE] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_620503057_-984473184] PRIMARY KEY CLUSTERED 
(
[SALELINENUM] ASC,
[TRANSACTIONID] ASC,
[TERMINALID] ASC,
[STORE] ASC,
[MARKUPLINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONMARKUPTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_CALCULATEDAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_CALCULATEDAMOUNT]  DEFAULT ((0)) FOR [CALCULATEDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_MARKUPCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_MARKUPCODE]  DEFAULT ('') FOR [MARKUPCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_MARKUPLINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_MARKUPLINENUM]  DEFAULT ((0)) FOR [MARKUPLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_METHOD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_METHOD]  DEFAULT ((0)) FOR [METHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_SALELINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_SALELINENUM]  DEFAULT ((0)) FOR [SALELINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_TAXAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_TAXAMOUNT]  DEFAULT ((0)) FOR [TAXAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_TAXAMOUNTEXCLUSIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_TAXAMOUNTEXCLUSIVE]  DEFAULT ((0)) FOR [TAXAMOUNTEXCLUSIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_TAXAMOUNTINCLUSIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_TAXAMOUNTINCLUSIVE]  DEFAULT ((0)) FOR [TAXAMOUNTINCLUSIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONMARKUPTRANS_VALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONMARKUPTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONMARKUPTRANS_VALUE]  DEFAULT ((0)) FOR [VALUE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONMARKUPTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONORDERINVOICETRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS](
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[INVOICEID] [nvarchar](20) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SALESID] [nvarchar](20) NOT NULL,
[SALESORDERINVOICETYPE] [int] NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_751503198_133413727] PRIMARY KEY CLUSTERED 
(
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONORDERINVOICETRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_AMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_AMOUNTCUR]  DEFAULT ((0)) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_INVOICEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_INVOICEID]  DEFAULT ('') FOR [INVOICEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_SALESID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_SALESID]  DEFAULT ('') FOR [SALESID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_SALESORDERINVOICETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_SALESORDERINVOICETYPE]  DEFAULT ((0)) FOR [SALESORDERINVOICETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERINVOICETRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERINVOICETRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERINVOICETRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONORDERINVOICETRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONORDERSTATUS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONORDERSTATUS](
[RECID] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[ERRORDETAIL] [nvarchar](1024) NOT NULL,
[LASTINVENTTRANS] [bigint] NOT NULL,
[RETRYCOUNT] [int] NOT NULL,
[SALESID] [nvarchar](20) NOT NULL,
[STATUS] [int] NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-832777827_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-832777827_-915363680] UNIQUE NONCLUSTERED 
(
[TRANSACTIONID] ASC,
[TERMINAL] ASC,
[STORE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_ERRORDETAIL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_ERRORDETAIL]  DEFAULT ('') FOR [ERRORDETAIL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_LASTINVENTTRANS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_LASTINVENTTRANS]  DEFAULT ((0)) FOR [LASTINVENTTRANS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_RETRYCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_RETRYCOUNT]  DEFAULT ((0)) FOR [RETRYCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_SALESID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_SALESID]  DEFAULT ('') FOR [SALESID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_STATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_STATUS]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONORDERSTATUS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONORDERSTATUS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONORDERSTATUS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONORDERSTATUS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONPAYMENTTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS](
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[AMOUNTMST] [numeric](32, 16) NOT NULL,
[AMOUNTTENDERED] [numeric](32, 16) NOT NULL,
[AUTHENTICATIONCODE] [nvarchar](20) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CARDORACCOUNT] [nvarchar](30) NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[CASHDOCID_RU] [nvarchar](20) NOT NULL,
[CHANGELINE] [int] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[COUNTER] [int] NOT NULL,
[CREDITVOUCHERID] [nvarchar](30) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[EXCHRATE] [numeric](32, 16) NOT NULL,
[EXCHRATEMST] [numeric](32, 16) NOT NULL,
[GIFTCARDID] [nvarchar](30) NOT NULL,
[ISPREPAYMENT] [int] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[LOYALTYCARDID] [nvarchar](30) NOT NULL,
[MANAGERKEYLIVE] [int] NOT NULL,
[MESSAGENUM] [int] NOT NULL,
[PAYMENTAUTHORIZATION] [nvarchar](max) NULL,
[QTY] [numeric](32, 16) NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[SIGCAPDATA] [nvarchar](max) NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TENDERTYPE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_371784663_133413727] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONPAYMENTTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_AMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_AMOUNTCUR]  DEFAULT ((0)) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_AMOUNTMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_AMOUNTMST]  DEFAULT ((0)) FOR [AMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_AMOUNTTENDERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_AMOUNTTENDERED]  DEFAULT ((0)) FOR [AMOUNTTENDERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_AUTHENTICATIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_AUTHENTICATIONCODE]  DEFAULT ('') FOR [AUTHENTICATIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CARDORACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CARDORACCOUNT]  DEFAULT ('') FOR [CARDORACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CARDTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CARDTYPEID]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CASHDOCID_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CASHDOCID_RU]  DEFAULT ('') FOR [CASHDOCID_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CHANGELINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CHANGELINE]  DEFAULT ((0)) FOR [CHANGELINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_COUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_COUNTER]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CREDITVOUCHERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CREDITVOUCHERID]  DEFAULT ('') FOR [CREDITVOUCHERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_EXCHRATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_EXCHRATE]  DEFAULT ((0)) FOR [EXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_EXCHRATEMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_EXCHRATEMST]  DEFAULT ((0)) FOR [EXCHRATEMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_GIFTCARDID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_GIFTCARDID]  DEFAULT ('') FOR [GIFTCARDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_ISPREPAYMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_ISPREPAYMENT]  DEFAULT ((0)) FOR [ISPREPAYMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_LOYALTYCARDID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_LOYALTYCARDID]  DEFAULT ('') FOR [LOYALTYCARDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_MANAGERKEYLIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_MANAGERKEYLIVE]  DEFAULT ((0)) FOR [MANAGERKEYLIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_MESSAGENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_MESSAGENUM]  DEFAULT ((0)) FOR [MESSAGENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_SHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_SHIFT]  DEFAULT ('') FOR [SHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_SHIFTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_SHIFTDATE]  DEFAULT ('1900-01-01') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_STAFF]  DEFAULT ('') FOR [STAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_TENDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_TENDERTYPE]  DEFAULT ('') FOR [TENDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONPAYMENTTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONPAYMENTTRANS_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR](
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[AMOUNTTENDERED] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TENDERTYPE] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_818850008_-1103390687] PRIMARY KEY CLUSTERED 
(
[LINENUM] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONPAYMENTTRANS_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_AMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_AMOUNTCUR]  DEFAULT ((0)) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_AMOUNTTENDERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_AMOUNTTENDERED]  DEFAULT ((0)) FOR [AMOUNTTENDERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TENDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TENDERTYPE]  DEFAULT ('') FOR [TENDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] ADD  CONSTRAINT [DF_RETAILTRANSACTIONPAYMENTTRANS_BR_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONSAFETENDERTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS](
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[AMOUNTCURPOS] [numeric](32, 16) NOT NULL,
[AMOUNTMST] [numeric](32, 16) NOT NULL,
[AMOUNTMSTPOS] [numeric](32, 16) NOT NULL,
[AMOUNTTENDERED] [numeric](32, 16) NOT NULL,
[AMOUNTTENDEREDPOS] [numeric](32, 16) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CARDORACCOUNT] [nvarchar](30) NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[CHANGELINE] [int] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[COUNTER] [numeric](32, 16) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[EXCHRATE] [numeric](32, 16) NOT NULL,
[EXCHRATEMST] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[MANAGERSKEYLIVE] [int] NOT NULL,
[MESSAGENUM] [int] NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STATEMENTID] [nvarchar](20) NOT NULL,
[STATUSTYPE] [int] NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TENDERTYPE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[CREATEDTRANSACTIONID] [bigint] NOT NULL,
[MODIFIEDTRANSACTIONID] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2051633402_133413727] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[STATEMENTID] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONSAFETENDERTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTCUR]  DEFAULT ((0)) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTCURPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTCURPOS]  DEFAULT ((0)) FOR [AMOUNTCURPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTMST]  DEFAULT ((0)) FOR [AMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTMSTPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTMSTPOS]  DEFAULT ((0)) FOR [AMOUNTMSTPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTTENDERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTTENDERED]  DEFAULT ((0)) FOR [AMOUNTTENDERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTTENDEREDPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_AMOUNTTENDEREDPOS]  DEFAULT ((0)) FOR [AMOUNTTENDEREDPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_CARDORACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_CARDORACCOUNT]  DEFAULT ('') FOR [CARDORACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_CARDTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_CARDTYPEID]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_CHANGELINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_CHANGELINE]  DEFAULT ((0)) FOR [CHANGELINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_COUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_COUNTER]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_EXCHRATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_EXCHRATE]  DEFAULT ((0)) FOR [EXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_EXCHRATEMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_EXCHRATEMST]  DEFAULT ((0)) FOR [EXCHRATEMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_MANAGERSKEYLIVE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_MANAGERSKEYLIVE]  DEFAULT ((0)) FOR [MANAGERSKEYLIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_MESSAGENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_MESSAGENUM]  DEFAULT ((0)) FOR [MESSAGENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_SHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_SHIFT]  DEFAULT ('') FOR [SHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_SHIFTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_SHIFTDATE]  DEFAULT ('1900-01-01') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_STAFF]  DEFAULT ('') FOR [STAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_STATEMENTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_STATEMENTID]  DEFAULT ('') FOR [STATEMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_STATUSTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_STATUSTYPE]  DEFAULT ((0)) FOR [STATUSTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_TENDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_TENDERTYPE]  DEFAULT ('') FOR [TENDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_CREATEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_CREATEDTRANSACTIONID]  DEFAULT ((0)) FOR [CREATEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSAFETENDERTRANS_MODIFIEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSAFETENDERTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSAFETENDERTRANS_MODIFIEDTRANSACTIONID]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONSAFETENDERTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONSALESTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONSALESTRANS](
[BARCODE] [nvarchar](80) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CATALOG] [bigint] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[COMMENT] [nvarchar](60) NOT NULL,
[COSTAMOUNT] [numeric](32, 16) NOT NULL,
[COUNTER] [int] NOT NULL,
[CUSTACCOUNT] [nvarchar](20) NOT NULL,
[CUSTDISCAMOUNT] [numeric](32, 16) NOT NULL,
[CUSTINVOICEDISCAMOUNT] [numeric](32, 16) NOT NULL,
[DISCAMOUNT] [numeric](32, 16) NOT NULL,
[DISCAMOUNTFROMSTDPRICE] [numeric](32, 16) NOT NULL,
[DISCGROUPID] [nvarchar](10) NOT NULL,
[DISCOFFERID] [nvarchar](40) NOT NULL,
[DISCOUNTAMOUNTFORPRINTING] [numeric](32, 16) NOT NULL,
[DLVMODE] [nvarchar](10) NOT NULL,
[ELECTRONICDELIVERYEMAIL] [nvarchar](80) NOT NULL,
[ELECTRONICDELIVERYEMAILCONTENT] [nvarchar](400) NOT NULL,
[FILELOGID] [nvarchar](10) NOT NULL,
[GIFTCARD] [int] NOT NULL,
[INFOCODEDISCAMOUNT] [numeric](32, 16) NOT NULL,
[INVENTBATCHID] [nvarchar](20) NOT NULL,
[INVENTDIMID] [nvarchar](20) NOT NULL,
[INVENTLOCATIONID] [nvarchar](10) NOT NULL,
[INVENTSERIALID] [nvarchar](20) NOT NULL,
[INVENTSITEID] [nvarchar](10) NOT NULL,
[INVENTTRANSID] [nvarchar](20) NOT NULL,
[ITEMCORRECTEDLINE] [int] NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
[ITEMIDSCANNED] [int] NOT NULL,
[ITEMPOSTINGGROUP] [nvarchar](20) NOT NULL,
[KEYBOARDITEMENTRY] [int] NOT NULL,
[LINEDSCAMOUNT] [numeric](32, 16) NOT NULL,
[LINEMANUALDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[LINEMANUALDISCOUNTPERCENTAGE] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[LINEWASDISCOUNTED] [int] NOT NULL,
[LINKEDITEMNOTORIGINAL] [int] NOT NULL,
[LISTINGID] [nvarchar](50) NOT NULL,
[LOGISTICSPOSTALADDRESS] [bigint] NOT NULL,
[LOYALTYDISCAMOUNT_RU] [numeric](32, 16) NOT NULL,
[LOYALTYDISCPCT_RU] [numeric](32, 16) NOT NULL,
[NETAMOUNT] [numeric](32, 16) NOT NULL,
[NETAMOUNTINCLTAX] [numeric](32, 16) NOT NULL,
[NETPRICE] [numeric](32, 16) NOT NULL,
[ORIGINALOFLINKEDITEMLIST] [int] NOT NULL,
[ORIGINALPRICE] [numeric](32, 16) NOT NULL,
[ORIGINALTAXGROUP] [nvarchar](10) NOT NULL,
[ORIGINALTAXITEMGROUP] [nvarchar](10) NOT NULL,
[PERIODICDISCAMOUNT] [numeric](32, 16) NOT NULL,
[PERIODICDISCGROUP] [nvarchar](10) NOT NULL,
[PERIODICDISCTYPE] [int] NOT NULL,
[PERIODICPERCENTAGEDISCOUNT] [numeric](32, 16) NOT NULL,
[PRESCRIPTIONID] [nvarchar](10) NOT NULL,
[PRICE] [numeric](32, 16) NOT NULL,
[PRICECHANGE] [int] NOT NULL,
[PRICEINBARCODE] [int] NOT NULL,
[PURCHID] [nvarchar](20) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[RECEIPTDATEREQUESTED] [date] NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[RETURNLINENUM] [numeric](32, 16) NOT NULL,
[RETURNNOSALE] [int] NOT NULL,
[RETURNQTY] [numeric](32, 16) NOT NULL,
[RETURNSTORE] [nvarchar](10) NOT NULL,
[RETURNTERMINALID] [nvarchar](10) NOT NULL,
[RETURNTRANSACTIONID] [nvarchar](44) NOT NULL,
[RFIDTAGID] [nvarchar](24) NOT NULL,
[SCALEITEM] [int] NOT NULL,
[SECTION] [nvarchar](10) NOT NULL,
[SHELF] [nvarchar](10) NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[SHIPPINGDATEREQUESTED] [date] NOT NULL,
[STAFFID] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STDNETPRICE] [numeric](32, 16) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TAXAMOUNT] [numeric](32, 16) NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TOTALDISCAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALDISCINFOCODELINENUM] [numeric](32, 16) NOT NULL,
[TOTALDISCPCT] [numeric](32, 16) NOT NULL,
[TOTALROUNDEDAMOUNT] [numeric](32, 16) NOT NULL,
[TRANSACTIONCODE] [int] NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[UNIT] [nvarchar](10) NOT NULL,
[UNITPRICE] [numeric](32, 16) NOT NULL,
[UNITQTY] [numeric](32, 16) NOT NULL,
[VARIANTID] [nvarchar](10) NOT NULL,
[WEIGHTITEM] [int] NOT NULL,
[WEIGHTMANUALLYENTERED] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[CREATEDTRANSACTIONID] [bigint] NOT NULL,
[MODIFIEDTRANSACTIONID] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-351364655_133413727] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONSALESTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_BARCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_BARCODE]  DEFAULT ('') FOR [BARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_CATALOG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_CATALOG]  DEFAULT ((0)) FOR [CATALOG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_COMMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_COMMENT]  DEFAULT ('') FOR [COMMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_COSTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_COSTAMOUNT]  DEFAULT ((0)) FOR [COSTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_COUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_COUNTER]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_CUSTACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_CUSTACCOUNT]  DEFAULT ('') FOR [CUSTACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_CUSTDISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_CUSTDISCAMOUNT]  DEFAULT ((0)) FOR [CUSTDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_CUSTINVOICEDISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_CUSTINVOICEDISCAMOUNT]  DEFAULT ((0)) FOR [CUSTINVOICEDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_DISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_DISCAMOUNT]  DEFAULT ((0)) FOR [DISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_DISCAMOUNTFROMSTDPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_DISCAMOUNTFROMSTDPRICE]  DEFAULT ((0)) FOR [DISCAMOUNTFROMSTDPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_DISCGROUPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_DISCGROUPID]  DEFAULT ('') FOR [DISCGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_DISCOFFERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_DISCOFFERID]  DEFAULT ('') FOR [DISCOFFERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_DISCOUNTAMOUNTFORPRINTING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_DISCOUNTAMOUNTFORPRINTING]  DEFAULT ((0)) FOR [DISCOUNTAMOUNTFORPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_DLVMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_DLVMODE]  DEFAULT ('') FOR [DLVMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ELECTRONICDELIVERYEMAIL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ELECTRONICDELIVERYEMAIL]  DEFAULT ('') FOR [ELECTRONICDELIVERYEMAIL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ELECTRONICDELIVERYEMAILCONTENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ELECTRONICDELIVERYEMAILCONTENT]  DEFAULT ('') FOR [ELECTRONICDELIVERYEMAILCONTENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_FILELOGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_FILELOGID]  DEFAULT ('') FOR [FILELOGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_GIFTCARD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_GIFTCARD]  DEFAULT ((0)) FOR [GIFTCARD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_INFOCODEDISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_INFOCODEDISCAMOUNT]  DEFAULT ((0)) FOR [INFOCODEDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_INVENTBATCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_INVENTBATCHID]  DEFAULT ('') FOR [INVENTBATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_INVENTDIMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_INVENTDIMID]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_INVENTLOCATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_INVENTLOCATIONID]  DEFAULT ('') FOR [INVENTLOCATIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_INVENTSERIALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_INVENTSERIALID]  DEFAULT ('') FOR [INVENTSERIALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_INVENTSITEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_INVENTSITEID]  DEFAULT ('') FOR [INVENTSITEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_INVENTTRANSID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_INVENTTRANSID]  DEFAULT ('') FOR [INVENTTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ITEMCORRECTEDLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ITEMCORRECTEDLINE]  DEFAULT ((0)) FOR [ITEMCORRECTEDLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ITEMID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ITEMID]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ITEMIDSCANNED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ITEMIDSCANNED]  DEFAULT ((0)) FOR [ITEMIDSCANNED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ITEMPOSTINGGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ITEMPOSTINGGROUP]  DEFAULT ('') FOR [ITEMPOSTINGGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_KEYBOARDITEMENTRY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_KEYBOARDITEMENTRY]  DEFAULT ((0)) FOR [KEYBOARDITEMENTRY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LINEDSCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LINEDSCAMOUNT]  DEFAULT ((0)) FOR [LINEDSCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LINEMANUALDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LINEMANUALDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [LINEMANUALDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LINEMANUALDISCOUNTPERCENTAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LINEMANUALDISCOUNTPERCENTAGE]  DEFAULT ((0)) FOR [LINEMANUALDISCOUNTPERCENTAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LINEWASDISCOUNTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LINEWASDISCOUNTED]  DEFAULT ((0)) FOR [LINEWASDISCOUNTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LINKEDITEMNOTORIGINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LINKEDITEMNOTORIGINAL]  DEFAULT ((0)) FOR [LINKEDITEMNOTORIGINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LISTINGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LISTINGID]  DEFAULT ('') FOR [LISTINGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LOGISTICSPOSTALADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LOGISTICSPOSTALADDRESS]  DEFAULT ((0)) FOR [LOGISTICSPOSTALADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LOYALTYDISCAMOUNT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LOYALTYDISCAMOUNT_RU]  DEFAULT ((0)) FOR [LOYALTYDISCAMOUNT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_LOYALTYDISCPCT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_LOYALTYDISCPCT_RU]  DEFAULT ((0)) FOR [LOYALTYDISCPCT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_NETAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_NETAMOUNT]  DEFAULT ((0)) FOR [NETAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_NETAMOUNTINCLTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_NETAMOUNTINCLTAX]  DEFAULT ((0)) FOR [NETAMOUNTINCLTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_NETPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_NETPRICE]  DEFAULT ((0)) FOR [NETPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ORIGINALOFLINKEDITEMLIST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ORIGINALOFLINKEDITEMLIST]  DEFAULT ((0)) FOR [ORIGINALOFLINKEDITEMLIST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ORIGINALPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ORIGINALPRICE]  DEFAULT ((0)) FOR [ORIGINALPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ORIGINALTAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ORIGINALTAXGROUP]  DEFAULT ('') FOR [ORIGINALTAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_ORIGINALTAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_ORIGINALTAXITEMGROUP]  DEFAULT ('') FOR [ORIGINALTAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PERIODICDISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PERIODICDISCAMOUNT]  DEFAULT ((0)) FOR [PERIODICDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PERIODICDISCGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PERIODICDISCGROUP]  DEFAULT ('') FOR [PERIODICDISCGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PERIODICDISCTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PERIODICDISCTYPE]  DEFAULT ((0)) FOR [PERIODICDISCTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PERIODICPERCENTAGEDISCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PERIODICPERCENTAGEDISCOUNT]  DEFAULT ((0)) FOR [PERIODICPERCENTAGEDISCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PRESCRIPTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PRESCRIPTIONID]  DEFAULT ('') FOR [PRESCRIPTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PRICE]  DEFAULT ((0)) FOR [PRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PRICECHANGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PRICECHANGE]  DEFAULT ((0)) FOR [PRICECHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PRICEINBARCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PRICEINBARCODE]  DEFAULT ((0)) FOR [PRICEINBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_PURCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_PURCHID]  DEFAULT ('') FOR [PURCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RECEIPTDATEREQUESTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RECEIPTDATEREQUESTED]  DEFAULT ('1900-01-01') FOR [RECEIPTDATEREQUESTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RETURNLINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RETURNLINENUM]  DEFAULT ((0)) FOR [RETURNLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RETURNNOSALE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RETURNNOSALE]  DEFAULT ((0)) FOR [RETURNNOSALE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RETURNQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RETURNQTY]  DEFAULT ((0)) FOR [RETURNQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RETURNSTORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RETURNSTORE]  DEFAULT ('') FOR [RETURNSTORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RETURNTERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RETURNTERMINALID]  DEFAULT ('') FOR [RETURNTERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RETURNTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RETURNTRANSACTIONID]  DEFAULT ('') FOR [RETURNTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_RFIDTAGID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_RFIDTAGID]  DEFAULT ('') FOR [RFIDTAGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_SCALEITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_SCALEITEM]  DEFAULT ((0)) FOR [SCALEITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_SECTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_SECTION]  DEFAULT ('') FOR [SECTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_SHELF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_SHELF]  DEFAULT ('') FOR [SHELF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_SHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_SHIFT]  DEFAULT ('') FOR [SHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_SHIFTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_SHIFTDATE]  DEFAULT ('1900-01-01') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_SHIPPINGDATEREQUESTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_SHIPPINGDATEREQUESTED]  DEFAULT ('1900-01-01') FOR [SHIPPINGDATEREQUESTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_STAFFID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_STAFFID]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_STDNETPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_STDNETPRICE]  DEFAULT ((0)) FOR [STDNETPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TAXAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TAXAMOUNT]  DEFAULT ((0)) FOR [TAXAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TOTALDISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TOTALDISCAMOUNT]  DEFAULT ((0)) FOR [TOTALDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TOTALDISCINFOCODELINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TOTALDISCINFOCODELINENUM]  DEFAULT ((0)) FOR [TOTALDISCINFOCODELINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TOTALDISCPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TOTALDISCPCT]  DEFAULT ((0)) FOR [TOTALDISCPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TOTALROUNDEDAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TOTALROUNDEDAMOUNT]  DEFAULT ((0)) FOR [TOTALROUNDEDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TRANSACTIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TRANSACTIONCODE]  DEFAULT ((0)) FOR [TRANSACTIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_UNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_UNIT]  DEFAULT ('') FOR [UNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_UNITPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_UNITPRICE]  DEFAULT ((0)) FOR [UNITPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_UNITQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_UNITQTY]  DEFAULT ((0)) FOR [UNITQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_VARIANTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_VARIANTID]  DEFAULT ('') FOR [VARIANTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_WEIGHTITEM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_WEIGHTITEM]  DEFAULT ((0)) FOR [WEIGHTITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_WEIGHTMANUALLYENTERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_WEIGHTMANUALLYENTERED]  DEFAULT ((0)) FOR [WEIGHTMANUALLYENTERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_CREATEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_CREATEDTRANSACTIONID]  DEFAULT ((0)) FOR [CREATEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSALESTRANS_MODIFIEDTRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSALESTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSALESTRANS_MODIFIEDTRANSACTIONID]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONSALESTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONSERVICEPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE](
[RECID] [bigint] NOT NULL,
[CENTRALTABLESERVER] [nvarchar](256) NOT NULL,
[CENTRALTABLESERVERPORT] [nvarchar](10) NOT NULL,
[LANGUAGE] [nvarchar](7) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PROFILEID] [nvarchar](10) NOT NULL,
[PROTOCOL] [int] NOT NULL,
[RETAILTSDATA] [nvarchar](256) NOT NULL,
[SECURITYOFF] [int] NOT NULL,
[SERVERCERTIFICATEDNS] [nvarchar](255) NOT NULL,
[SERVERSERVICENAME] [nvarchar](50) NOT NULL,
[TSSTAFF] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-439203455_-2102841330] PRIMARY KEY CLUSTERED 
(
[PROFILEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_CENTRALTABLESERVER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_CENTRALTABLESERVER]  DEFAULT ('') FOR [CENTRALTABLESERVER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_CENTRALTABLESERVERPORT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_CENTRALTABLESERVERPORT]  DEFAULT ('') FOR [CENTRALTABLESERVERPORT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_LANGUAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_LANGUAGE]  DEFAULT ('') FOR [LANGUAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_PROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_PROFILEID]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_PROTOCOL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_PROTOCOL]  DEFAULT ((0)) FOR [PROTOCOL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_RETAILTSDATA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_RETAILTSDATA]  DEFAULT ('') FOR [RETAILTSDATA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_SECURITYOFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_SECURITYOFF]  DEFAULT ((0)) FOR [SECURITYOFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_SERVERCERTIFICATEDNS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_SERVERCERTIFICATEDNS]  DEFAULT ('') FOR [SERVERCERTIFICATEDNS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_SERVERSERVICENAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_SERVERSERVICENAME]  DEFAULT ('') FOR [SERVERSERVICENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONSERVICEPROFILE_TSSTAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONSERVICEPROFILE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONSERVICEPROFILE_TSSTAFF]  DEFAULT ((0)) FOR [TSSTAFF]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONSERVICEPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONTABLE](
[AMOUNTTOACCOUNT] [numeric](32, 16) NOT NULL,
[BATCHID] [bigint] NOT NULL,
[BATCHTERMINALID] [nvarchar](10) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CHANNELREFERENCEID] [nvarchar](50) NOT NULL,
[COMMENT] [nvarchar](60) NOT NULL,
[COSTAMOUNT] [numeric](32, 16) NOT NULL,
[COUNTER] [int] NOT NULL,
[CREATEDOFFLINE] [int] NOT NULL,
[CREATEDONPOSTERMINAL] [nvarchar](10) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[CUSTACCOUNT] [nvarchar](20) NOT NULL,
[CUSTDISCAMOUNT] [numeric](32, 16) NOT NULL,
[CUSTPURCHASEORDER] [nvarchar](20) NOT NULL,
[DESCRIPTION] [nvarchar](150) NOT NULL,
[DISCAMOUNT] [numeric](32, 16) NOT NULL,
[DLVMODE] [nvarchar](10) NOT NULL,
[ENTRYSTATUS] [int] NOT NULL,
[EXCHRATE] [numeric](32, 16) NOT NULL,
[FISCALDOCUMENTID] [nvarchar](80) NOT NULL,
[FISCALSERIALID] [nvarchar](80) NOT NULL,
[GROSSAMOUNT] [numeric](32, 16) NOT NULL,
[INCLUDEDINSTATISTICS] [int] NOT NULL,
[INCOMEEXPENSEAMOUNT] [numeric](32, 16) NOT NULL,
[INFOCODEDISCGROUP] [nvarchar](10) NOT NULL,
[INVENTLOCATIONID] [nvarchar](10) NOT NULL,
[INVENTSITEID] [nvarchar](10) NOT NULL,
[INVOICECOMMENT] [nvarchar](60) NOT NULL,
[ITEMSPOSTED] [int] NOT NULL,
[LOGISTICSPOSTALADDRESS] [bigint] NOT NULL,
[LOYALTYCARDID] [nvarchar](30) NOT NULL,
[LOYALTYDISCAMOUNT_RU] [numeric](32, 16) NOT NULL,
[NETAMOUNT] [numeric](32, 16) NOT NULL,
[NUMBEROFINVOICES] [int] NOT NULL,
[NUMBEROFITEMLINES] [numeric](32, 16) NOT NULL,
[NUMBEROFITEMS] [numeric](32, 16) NOT NULL,
[NUMBEROFPAYMENTLINES] [int] NOT NULL,
[OPENDRAWER] [int] NOT NULL,
[PAYMENTAMOUNT] [numeric](32, 16) NOT NULL,
[POSTASSHIPMENT] [int] NOT NULL,
[RECEIPTDATEREQUESTED] [date] NOT NULL,
[RECEIPTEMAIL] [nvarchar](80) NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REFUNDRECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[RETRIEVEDFROMRECEIPTID] [nvarchar](18) NOT NULL,
[ROUNDEDAMOUNT] [numeric](32, 16) NOT NULL,
[SALEISRETURNSALE] [int] NOT NULL,
[SALESINVOICEAMOUNT] [numeric](32, 16) NOT NULL,
[SALESORDERAMOUNT] [numeric](32, 16) NOT NULL,
[SALESORDERID] [nvarchar](20) NOT NULL,
[SALESPAYMENTDIFFERENCE] [numeric](32, 16) NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[SHIPPINGDATEREQUESTED] [date] NOT NULL,
[SKIPAGGREGATION] [int] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TIMEWHENTOTALPRESSED] [int] NOT NULL,
[TIMEWHENTRANSCLOSED] [int] NOT NULL,
[TOACCOUNT] [int] NOT NULL,
[TOTALDISCAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALMANUALDISCOUNTAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALMANUALDISCOUNTPERCENTAGE] [numeric](32, 16) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSCODE] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTABLEID] [int] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[TYPE] [int] NOT NULL,
[WRONGSHIFT] [int] NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1558077251_-1679712867] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONTABLE_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_AMOUNTTOACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_AMOUNTTOACCOUNT]  DEFAULT ((0)) FOR [AMOUNTTOACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_BATCHID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_BATCHID]  DEFAULT ((0)) FOR [BATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_BATCHTERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_BATCHTERMINALID]  DEFAULT ('') FOR [BATCHTERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CHANNELREFERENCEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CHANNELREFERENCEID]  DEFAULT ('') FOR [CHANNELREFERENCEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_COMMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_COMMENT]  DEFAULT ('') FOR [COMMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_COSTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_COSTAMOUNT]  DEFAULT ((0)) FOR [COSTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_COUNTER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_COUNTER]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CREATEDOFFLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CREATEDOFFLINE]  DEFAULT ((0)) FOR [CREATEDOFFLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CREATEDONPOSTERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CREATEDONPOSTERMINAL]  DEFAULT ('') FOR [CREATEDONPOSTERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CUSTACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CUSTACCOUNT]  DEFAULT ('') FOR [CUSTACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CUSTDISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CUSTDISCAMOUNT]  DEFAULT ((0)) FOR [CUSTDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CUSTPURCHASEORDER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CUSTPURCHASEORDER]  DEFAULT ('') FOR [CUSTPURCHASEORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_DISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_DISCAMOUNT]  DEFAULT ((0)) FOR [DISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_DLVMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_DLVMODE]  DEFAULT ('') FOR [DLVMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_ENTRYSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_ENTRYSTATUS]  DEFAULT ((0)) FOR [ENTRYSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_EXCHRATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_EXCHRATE]  DEFAULT ((0)) FOR [EXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_FISCALDOCUMENTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_FISCALDOCUMENTID]  DEFAULT ('') FOR [FISCALDOCUMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_FISCALSERIALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_FISCALSERIALID]  DEFAULT ('') FOR [FISCALSERIALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_GROSSAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_GROSSAMOUNT]  DEFAULT ((0)) FOR [GROSSAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_INCLUDEDINSTATISTICS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_INCLUDEDINSTATISTICS]  DEFAULT ((0)) FOR [INCLUDEDINSTATISTICS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_INCOMEEXPENSEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_INCOMEEXPENSEAMOUNT]  DEFAULT ((0)) FOR [INCOMEEXPENSEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_INFOCODEDISCGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_INFOCODEDISCGROUP]  DEFAULT ('') FOR [INFOCODEDISCGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_INVENTLOCATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_INVENTLOCATIONID]  DEFAULT ('') FOR [INVENTLOCATIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_INVENTSITEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_INVENTSITEID]  DEFAULT ('') FOR [INVENTSITEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_INVOICECOMMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_INVOICECOMMENT]  DEFAULT ('') FOR [INVOICECOMMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_ITEMSPOSTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_ITEMSPOSTED]  DEFAULT ((0)) FOR [ITEMSPOSTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_LOGISTICSPOSTALADDRESS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_LOGISTICSPOSTALADDRESS]  DEFAULT ((0)) FOR [LOGISTICSPOSTALADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_LOYALTYCARDID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_LOYALTYCARDID]  DEFAULT ('') FOR [LOYALTYCARDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_LOYALTYDISCAMOUNT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_LOYALTYDISCAMOUNT_RU]  DEFAULT ((0)) FOR [LOYALTYDISCAMOUNT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_NETAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_NETAMOUNT]  DEFAULT ((0)) FOR [NETAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_NUMBEROFINVOICES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_NUMBEROFINVOICES]  DEFAULT ((0)) FOR [NUMBEROFINVOICES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_NUMBEROFITEMLINES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_NUMBEROFITEMLINES]  DEFAULT ((0)) FOR [NUMBEROFITEMLINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_NUMBEROFITEMS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_NUMBEROFITEMS]  DEFAULT ((0)) FOR [NUMBEROFITEMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_NUMBEROFPAYMENTLINES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_NUMBEROFPAYMENTLINES]  DEFAULT ((0)) FOR [NUMBEROFPAYMENTLINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_OPENDRAWER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_OPENDRAWER]  DEFAULT ((0)) FOR [OPENDRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_PAYMENTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_PAYMENTAMOUNT]  DEFAULT ((0)) FOR [PAYMENTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_POSTASSHIPMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_POSTASSHIPMENT]  DEFAULT ((0)) FOR [POSTASSHIPMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RECEIPTDATEREQUESTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RECEIPTDATEREQUESTED]  DEFAULT ('1900-01-01') FOR [RECEIPTDATEREQUESTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RECEIPTEMAIL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RECEIPTEMAIL]  DEFAULT ('') FOR [RECEIPTEMAIL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_REFUNDRECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_REFUNDRECEIPTID]  DEFAULT ('') FOR [REFUNDRECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RETRIEVEDFROMRECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RETRIEVEDFROMRECEIPTID]  DEFAULT ('') FOR [RETRIEVEDFROMRECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_ROUNDEDAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_ROUNDEDAMOUNT]  DEFAULT ((0)) FOR [ROUNDEDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SALEISRETURNSALE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SALEISRETURNSALE]  DEFAULT ((0)) FOR [SALEISRETURNSALE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SALESINVOICEAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SALESINVOICEAMOUNT]  DEFAULT ((0)) FOR [SALESINVOICEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SALESORDERAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SALESORDERAMOUNT]  DEFAULT ((0)) FOR [SALESORDERAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SALESORDERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SALESORDERID]  DEFAULT ('') FOR [SALESORDERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SALESPAYMENTDIFFERENCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SALESPAYMENTDIFFERENCE]  DEFAULT ((0)) FOR [SALESPAYMENTDIFFERENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SHIFT]  DEFAULT ('') FOR [SHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SHIFTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SHIFTDATE]  DEFAULT ('1900-01-01') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SHIPPINGDATEREQUESTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SHIPPINGDATEREQUESTED]  DEFAULT ('1900-01-01') FOR [SHIPPINGDATEREQUESTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_SKIPAGGREGATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_SKIPAGGREGATION]  DEFAULT ((0)) FOR [SKIPAGGREGATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_STAFF]  DEFAULT ('') FOR [STAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TIMEWHENTOTALPRESSED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TIMEWHENTOTALPRESSED]  DEFAULT ((0)) FOR [TIMEWHENTOTALPRESSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TIMEWHENTRANSCLOSED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TIMEWHENTRANSCLOSED]  DEFAULT ((0)) FOR [TIMEWHENTRANSCLOSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TOACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TOACCOUNT]  DEFAULT ((0)) FOR [TOACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TOTALDISCAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TOTALDISCAMOUNT]  DEFAULT ((0)) FOR [TOTALDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TOTALMANUALDISCOUNTAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TOTALMANUALDISCOUNTAMOUNT]  DEFAULT ((0)) FOR [TOTALMANUALDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TOTALMANUALDISCOUNTPERCENTAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TOTALMANUALDISCOUNTPERCENTAGE]  DEFAULT ((0)) FOR [TOTALMANUALDISCOUNTPERCENTAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TRANSCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TRANSCODE]  DEFAULT ((0)) FOR [TRANSCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TRANSTABLEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TRANSTABLEID]  DEFAULT ((0)) FOR [TRANSTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_WRONGSHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_WRONGSHIFT]  DEFAULT ((0)) FOR [WRONGSHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONTABLE_RU]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONTABLE_RU](
[CHANNEL] [bigint] NOT NULL,
[EKLZSERIALNUMBER] [nvarchar](10) NOT NULL,
[FISCALDOCUMENTSERIALNUMBER] [nvarchar](10) NOT NULL,
[FISCALPRINTERSERIALNUMBER] [nvarchar](20) NOT NULL,
[FISCALPRINTERSHIFTID] [nvarchar](5) NOT NULL,
[KPKNUMBER] [nvarchar](8) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1458006241_-1679712867] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONTABLE_RU_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_EKLZSERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_EKLZSERIALNUMBER]  DEFAULT ('') FOR [EKLZSERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_FISCALDOCUMENTSERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_FISCALDOCUMENTSERIALNUMBER]  DEFAULT ('') FOR [FISCALDOCUMENTSERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_FISCALPRINTERSERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_FISCALPRINTERSERIALNUMBER]  DEFAULT ('') FOR [FISCALPRINTERSERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_FISCALPRINTERSHIFTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_FISCALPRINTERSHIFTID]  DEFAULT ('') FOR [FISCALPRINTERSHIFTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_KPKNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_KPKNUMBER]  DEFAULT ('') FOR [KPKNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_CREATEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_CREATEDDATETIME]  DEFAULT (getutcdate()) FOR [CREATEDDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTABLE_RU_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTABLE_RU] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTABLE_RU_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONTABLE_RU] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONTAXTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONTAXTRANS](
[AMOUNT] [numeric](32, 16) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[ISINCLUDEDINPRICE] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SALELINENUM] [numeric](32, 16) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-304018762_-36691966] PRIMARY KEY CLUSTERED 
(
[TERMINALID] ASC,
[STOREID] ASC,
[TRANSACTIONID] ASC,
[SALELINENUM] ASC,
[TAXCODE] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONTAXTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_AMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_AMOUNT]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_ISINCLUDEDINPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_ISINCLUDEDINPRICE]  DEFAULT ((0)) FOR [ISINCLUDEDINPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_SALELINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_SALELINENUM]  DEFAULT ((0)) FOR [SALELINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONTAXTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONTAXTRANS_IN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN](
[CHANNEL] [bigint] NOT NULL,
[ISTAXONTAX] [int] NOT NULL,
[SALELINENUM] [numeric](32, 16) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TAXBASIS] [numeric](32, 16) NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXCOMPONENT] [nvarchar](15) NOT NULL,
[TAXFORMULA] [nvarchar](1000) NOT NULL,
[TAXISEXEMPT] [int] NOT NULL,
[TAXISINCLUDEDINPRICE] [int] NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[TAXPERCENTAGE] [numeric](32, 16) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-606328328_-36691966] UNIQUE CLUSTERED 
(
[CHANNEL] ASC,
[SALELINENUM] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[TAXCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_ISTAXONTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_ISTAXONTAX]  DEFAULT ((0)) FOR [ISTAXONTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_SALELINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_SALELINENUM]  DEFAULT ((0)) FOR [SALELINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXBASIS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXBASIS]  DEFAULT ((0)) FOR [TAXBASIS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXCOMPONENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXCOMPONENT]  DEFAULT ('') FOR [TAXCOMPONENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXFORMULA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXFORMULA]  DEFAULT ('') FOR [TAXFORMULA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXISEXEMPT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXISEXEMPT]  DEFAULT ((0)) FOR [TAXISEXEMPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXISINCLUDEDINPRICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXISINCLUDEDINPRICE]  DEFAULT ((0)) FOR [TAXISINCLUDEDINPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TAXPERCENTAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TAXPERCENTAGE]  DEFAULT ((0)) FOR [TAXPERCENTAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTAXTRANS_IN_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTAXTRANS_IN] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTAXTRANS_IN_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONTAXTRANS_IN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS](
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[AMOUNTMST] [numeric](32, 16) NOT NULL,
[AMOUNTTENDERED] [numeric](32, 16) NOT NULL,
[BUSINESSDATE] [date] NOT NULL,
[CARDID] [nvarchar](10) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[EXCHRATE] [numeric](32, 16) NOT NULL,
[EXCHRATEMST] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[POSCURRENCY] [nvarchar](3) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATED] [int] NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TENDERTYPE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1233709243_133413727] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[LINENUM] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONTENDERDECLARATIONTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_AMOUNTCUR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_AMOUNTCUR]  DEFAULT ((0)) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_AMOUNTMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_AMOUNTMST]  DEFAULT ((0)) FOR [AMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_AMOUNTTENDERED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_AMOUNTTENDERED]  DEFAULT ((0)) FOR [AMOUNTTENDERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_BUSINESSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_BUSINESSDATE]  DEFAULT ('1900-01-01') FOR [BUSINESSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_CARDID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_CARDID]  DEFAULT ('') FOR [CARDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_CURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_CURRENCY]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_EXCHRATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_EXCHRATE]  DEFAULT ((0)) FOR [EXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_EXCHRATEMST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_EXCHRATEMST]  DEFAULT ((0)) FOR [EXCHRATEMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_POSCURRENCY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_POSCURRENCY]  DEFAULT ('') FOR [POSCURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_QTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_QTY]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_REPLICATED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_REPLICATED]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_SHIFT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_SHIFT]  DEFAULT ('') FOR [SHIFT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_SHIFTDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_SHIFTDATE]  DEFAULT ('1900-01-01') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_STAFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_STAFF]  DEFAULT ('') FOR [STAFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_STATEMENTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_STATEMENTCODE]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_STORE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TENDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TENDERTYPE]  DEFAULT ('') FOR [TENDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TERMINAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSACTIONSTATUS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSACTIONSTATUS]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSDATE]  DEFAULT ('1900-01-01') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONTENDERDECLARATIONTRANS_TRANSTIME]  DEFAULT ((0)) FOR [TRANSTIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILUNIT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILUNIT](
[RECID] [bigint] NOT NULL,
[MINDENOMINATOR] [numeric](32, 16) NOT NULL,
[UNITID] [nvarchar](10) NOT NULL,
[WEIGHTUNITOFMEASURE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-720078487_-36816785] PRIMARY KEY CLUSTERED 
(
[UNITID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILUNIT_MINDENOMINATOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILUNIT] ADD  CONSTRAINT [DF_RETAILUNIT_MINDENOMINATOR]  DEFAULT ((0)) FOR [MINDENOMINATOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILUNIT_UNITID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILUNIT] ADD  CONSTRAINT [DF_RETAILUNIT_UNITID]  DEFAULT ('') FOR [UNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILUNIT_WEIGHTUNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILUNIT] ADD  CONSTRAINT [DF_RETAILUNIT_WEIGHTUNITOFMEASURE]  DEFAULT ((0)) FOR [WEIGHTUNITOFMEASURE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILUNIT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILVISUALPROFILE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILVISUALPROFILE](
[RECID] [bigint] NOT NULL,
[BACKGROUNDPICTUREID] [int] NOT NULL,
[DESIGNALLOWEDONPOS] [int] NOT NULL,
[FONTSCHEME] [int] NOT NULL,
[FULLSCREENMODE] [int] NOT NULL,
[HIDECURSOR] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PALLET] [nvarchar](60) NOT NULL,
[PICTUREID] [int] NOT NULL,
[POSSKINNAME] [nvarchar](100) NOT NULL,
[PROFILEID] [nvarchar](10) NOT NULL,
[SCREENHEIGHT] [int] NOT NULL,
[SCREENWIDTH] [int] NOT NULL,
[SKINFILE] [varbinary](max) NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_660123670_-2102841330] PRIMARY KEY CLUSTERED 
(
[PROFILEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_BACKGROUNDPICTUREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_BACKGROUNDPICTUREID]  DEFAULT ((0)) FOR [BACKGROUNDPICTUREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_DESIGNALLOWEDONPOS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_DESIGNALLOWEDONPOS]  DEFAULT ((0)) FOR [DESIGNALLOWEDONPOS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_FONTSCHEME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_FONTSCHEME]  DEFAULT ((0)) FOR [FONTSCHEME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_FULLSCREENMODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_FULLSCREENMODE]  DEFAULT ((0)) FOR [FULLSCREENMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_HIDECURSOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_HIDECURSOR]  DEFAULT ((0)) FOR [HIDECURSOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_PALLET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_PALLET]  DEFAULT ('') FOR [PALLET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_PICTUREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_PICTUREID]  DEFAULT ((0)) FOR [PICTUREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_POSSKINNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_POSSKINNAME]  DEFAULT ('') FOR [POSSKINNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_PROFILEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_PROFILEID]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_SCREENHEIGHT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_SCREENHEIGHT]  DEFAULT ((0)) FOR [SCREENHEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_SCREENWIDTH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_SCREENWIDTH]  DEFAULT ((0)) FOR [SCREENWIDTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILVISUALPROFILE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILVISUALPROFILE] ADD  CONSTRAINT [DF_RETAILVISUALPROFILE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILVISUALPROFILE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILZREPORT_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILZREPORT_BR](
[ACCOUNTINGDATE] [date] NOT NULL,
[ADDITIONALFISCALMEMORYINDEX] [int] NOT NULL,
[COFINSAMOUNT] [numeric](32, 16) NOT NULL,
[FINALGRANDTOTALAMOUNT] [numeric](32, 16) NOT NULL,
[FIRSTRECEIPTNUMBER] [int] NOT NULL,
[FISCALESTABLISHMENT] [nvarchar](10) NOT NULL,
[FISCALPRINTERSERIALNUMBER] [nvarchar](20) NOT NULL,
[FISCALRECEIPTMODEL] [nvarchar](3) NOT NULL,
[GROSSDAILYSALE] [numeric](32, 16) NOT NULL,
[INITIALGRANDTOTALAMOUNT] [numeric](32, 16) NOT NULL,
[ISSDISCOUNT] [int] NOT NULL,
[LASTRECEIPTNUMBER] [int] NOT NULL,
[NETAMOUNT] [numeric](32, 16) NOT NULL,
[PISAMOUNT] [numeric](32, 16) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[RESTARTOPERATIONNUMBER] [int] NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TERMINALNUMBER] [int] NOT NULL,
[VERSION] [int] NOT NULL,
[ZREPORTDATETIME] [datetime] NOT NULL,
[ZREPORTDATETIMETZID] [int] NOT NULL,
[ZREPORTNUMBER] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-535303524_311289610] PRIMARY KEY CLUSTERED 
(
[FISCALPRINTERSERIALNUMBER] ASC,
[ADDITIONALFISCALMEMORYINDEX] ASC,
[ZREPORTNUMBER] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[RESTARTOPERATIONNUMBER] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILZREPORT_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_ACCOUNTINGDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_ACCOUNTINGDATE]  DEFAULT ('1900-01-01') FOR [ACCOUNTINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_ADDITIONALFISCALMEMORYINDEX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_ADDITIONALFISCALMEMORYINDEX]  DEFAULT ((0)) FOR [ADDITIONALFISCALMEMORYINDEX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_COFINSAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_COFINSAMOUNT]  DEFAULT ((0)) FOR [COFINSAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_FINALGRANDTOTALAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_FINALGRANDTOTALAMOUNT]  DEFAULT ((0)) FOR [FINALGRANDTOTALAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_FIRSTRECEIPTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_FIRSTRECEIPTNUMBER]  DEFAULT ((0)) FOR [FIRSTRECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_FISCALESTABLISHMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_FISCALESTABLISHMENT]  DEFAULT ('') FOR [FISCALESTABLISHMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_FISCALPRINTERSERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_FISCALPRINTERSERIALNUMBER]  DEFAULT ('') FOR [FISCALPRINTERSERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_FISCALRECEIPTMODEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_FISCALRECEIPTMODEL]  DEFAULT ('') FOR [FISCALRECEIPTMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_GROSSDAILYSALE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_GROSSDAILYSALE]  DEFAULT ((0)) FOR [GROSSDAILYSALE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_INITIALGRANDTOTALAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_INITIALGRANDTOTALAMOUNT]  DEFAULT ((0)) FOR [INITIALGRANDTOTALAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_ISSDISCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_ISSDISCOUNT]  DEFAULT ((0)) FOR [ISSDISCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_LASTRECEIPTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_LASTRECEIPTNUMBER]  DEFAULT ((0)) FOR [LASTRECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_NETAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_NETAMOUNT]  DEFAULT ((0)) FOR [NETAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_PISAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_PISAMOUNT]  DEFAULT ((0)) FOR [PISAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_RESTARTOPERATIONNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_RESTARTOPERATIONNUMBER]  DEFAULT ((0)) FOR [RESTARTOPERATIONNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_TERMINALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_TERMINALNUMBER]  DEFAULT ((0)) FOR [TERMINALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_VERSION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_VERSION]  DEFAULT ((0)) FOR [VERSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_ZREPORTDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_ZREPORTDATETIME]  DEFAULT ('1900-01-01 00:00:00.000') FOR [ZREPORTDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_ZREPORTDATETIMETZID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_ZREPORTDATETIMETZID]  DEFAULT ((37001)) FOR [ZREPORTDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORT_BR_ZREPORTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORT_BR] ADD  CONSTRAINT [DF_RETAILZREPORT_BR_ZREPORTNUMBER]  DEFAULT ((0)) FOR [ZREPORTNUMBER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILZREPORT_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILZREPORTTOTALIZER_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILZREPORTTOTALIZER_BR](
[ADDITIONALFISCALMEMORYINDEX] [int] NOT NULL,
[FISCALPRINTERSERIALNUMBER] [nvarchar](20) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TOTALIZERAMOUNT] [numeric](32, 16) NOT NULL,
[TOTALIZERNAME] [nvarchar](10) NOT NULL,
[TOTALIZERSINTEGRANAME] [nvarchar](10) NOT NULL,
[ZREPORTNUMBER] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1519526632_1172547349] PRIMARY KEY CLUSTERED 
(
[FISCALPRINTERSERIALNUMBER] ASC,
[ADDITIONALFISCALMEMORYINDEX] ASC,
[ZREPORTNUMBER] ASC,
[TOTALIZERNAME] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILZREPORTTOTALIZER_BR_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_ADDITIONALFISCALMEMORYINDEX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_ADDITIONALFISCALMEMORYINDEX]  DEFAULT ((0)) FOR [ADDITIONALFISCALMEMORYINDEX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_FISCALPRINTERSERIALNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_FISCALPRINTERSERIALNUMBER]  DEFAULT ('') FOR [FISCALPRINTERSERIALNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_TOTALIZERAMOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_TOTALIZERAMOUNT]  DEFAULT ((0)) FOR [TOTALIZERAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_TOTALIZERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_TOTALIZERNAME]  DEFAULT ('') FOR [TOTALIZERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_TOTALIZERSINTEGRANAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_TOTALIZERSINTEGRANAME]  DEFAULT ('') FOR [TOTALIZERSINTEGRANAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILZREPORTTOTALIZER_BR_ZREPORTNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILZREPORTTOTALIZER_BR] ADD  CONSTRAINT [DF_RETAILZREPORTTOTALIZER_BR_ZREPORTNUMBER]  DEFAULT ((0)) FOR [ZREPORTNUMBER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILZREPORTTOTALIZER_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS](
[AFFILIATION] [bigint] NOT NULL,
[CARDNUMBER] [nvarchar](30) NOT NULL,
[CHANNEL] [bigint] NOT NULL,
[CUSTACCOUNT] [nvarchar](20) NOT NULL,
[ENTRYDATE] [date] NOT NULL,
[ENTRYTIME] [int] NOT NULL,
[ENTRYTYPE] [int] NOT NULL,
[EXPIRATIONDATE] [date] NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[LOYALTYTIER] [bigint] NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATIONCOUNTERFROMORIGIN] [int] IDENTITY(1,1) NOT NULL,
[REWARDPOINT] [bigint] NOT NULL,
[REWARDPOINTAMOUNTQTY] [numeric](32, 16) NOT NULL,
[STAFFID] [nvarchar](25) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1316415024_2094676863] PRIMARY KEY CLUSTERED 
(
[CHANNEL] ASC,
[LINENUM] ASC,
[STOREID] ASC,
[TERMINALID] ASC,
[TRANSACTIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_REPLICATIONCOUNTERFROMORIGIN] UNIQUE NONCLUSTERED 
(
[REPLICATIONCOUNTERFROMORIGIN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_AFFILIATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_AFFILIATION]  DEFAULT ((0)) FOR [AFFILIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_CARDNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_CARDNUMBER]  DEFAULT ('') FOR [CARDNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_CHANNEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_CHANNEL]  DEFAULT ((0)) FOR [CHANNEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_CUSTACCOUNT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_CUSTACCOUNT]  DEFAULT ('') FOR [CUSTACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_ENTRYDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_ENTRYDATE]  DEFAULT ('1900-01-01') FOR [ENTRYDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_ENTRYTIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_ENTRYTIME]  DEFAULT ((0)) FOR [ENTRYTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_ENTRYTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_ENTRYTYPE]  DEFAULT ((0)) FOR [ENTRYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_EXPIRATIONDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_EXPIRATIONDATE]  DEFAULT ('1900-01-01') FOR [EXPIRATIONDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_LINENUM]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_LINENUM]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_LOYALTYTIER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_LOYALTYTIER]  DEFAULT ((0)) FOR [LOYALTYTIER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_RECEIPTID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_RECEIPTID]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_REWARDPOINT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_REWARDPOINT]  DEFAULT ((0)) FOR [REWARDPOINT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_REWARDPOINTAMOUNTQTY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_REWARDPOINTAMOUNTQTY]  DEFAULT ((0)) FOR [REWARDPOINTAMOUNTQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_STAFFID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_STAFFID]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_STOREID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_STOREID]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_TERMINALID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_TERMINALID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_TRANSACTIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] ADD  CONSTRAINT [DF_RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SALESPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SALESPARAMETERS](
[RECID] [bigint] NOT NULL,
[ACCESLEVELINVOICED] [int] NOT NULL,
[BILLOFLADING] [int] NOT NULL,
[BOLCARRIERNAME] [nvarchar](140) NOT NULL,
[BOLFREIGHTCHARGETERMS] [int] NOT NULL,
[BOLFREIGHTCOUNTED] [int] NOT NULL,
[BOLFREIGHTEDBY] [int] NOT NULL,
[BOLLANGUAGEID] [nvarchar](7) NOT NULL,
[BOLTRAILERLOADED] [int] NOT NULL,
[CANCELSALES] [int] NOT NULL,
[CUSTQUOTATIONTYPEID] [nvarchar](20) NOT NULL,
[DELETEHEADING] [int] NOT NULL,
[DELETELINE] [int] NOT NULL,
[DELIVERY2INVOICE] [nvarchar](10) NOT NULL,
[DISC] [int] NOT NULL,
[KEY] [int] NOT NULL,
[LEADTIMESALESDEFAULT] [int] NOT NULL,
[MARKUPHEADING] [int] NOT NULL,
[MARKUPLINE] [int] NOT NULL,
[ORDERENTRYSTATISTICS] [int] NOT NULL,
[ORDERTYPE] [int] NOT NULL,
[OVERDELIVERY] [int] NOT NULL,
[PICKINGLISTDEFAULTLANGUAGE] [int] NOT NULL,
[POSTPACKINGSLIP] [int] NOT NULL,
[PREPRINTLEVELSHIPPINGLABEL] [int] NOT NULL,
[PROMPTTRANSFER] [int] NOT NULL,
[QUOTATIONNUMOFDAYSEXPIRYDATE] [int] NOT NULL,
[QUOTATIONNUMOFDAYSFOLLOWUPDATE] [int] NOT NULL,
[REDUCEINVOICE] [int] NOT NULL,
[REDUCEPACKINGSLIP] [int] NOT NULL,
[REDUCEPICKINGLIST] [int] NOT NULL,
[RESERVATION] [int] NOT NULL,
[SALESORIGINID] [nvarchar](10) NOT NULL,
[SALESPOOLID] [nvarchar](10) NOT NULL,
[SETTLEVOUCHER] [int] NOT NULL,
[SHIPPINGSTAT] [int] NOT NULL,
[SPLITDELIVERYCONFIRMATION] [int] NOT NULL,
[SPLITDELIVERYINVOICE] [int] NOT NULL,
[SPLITDELIVERYPACKINGSLIP] [int] NOT NULL,
[SPLITDELIVERYPICKINGLIST] [int] NOT NULL,
[SUBDELIVERY] [int] NOT NULL,
[SUMMARYERRORTOLERANCE] [int] NOT NULL,
[SUMMARYUPDATEBY] [int] NOT NULL,
[USESETTLEEXCHRATE] [int] NOT NULL,
[VALIDDAYS] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_782353986_-1273337705] PRIMARY KEY CLUSTERED 
(
[KEY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_ACCESLEVELINVOICED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_ACCESLEVELINVOICED]  DEFAULT ((0)) FOR [ACCESLEVELINVOICED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_BILLOFLADING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_BILLOFLADING]  DEFAULT ((0)) FOR [BILLOFLADING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_BOLCARRIERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_BOLCARRIERNAME]  DEFAULT ('') FOR [BOLCARRIERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_BOLFREIGHTCHARGETERMS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_BOLFREIGHTCHARGETERMS]  DEFAULT ((0)) FOR [BOLFREIGHTCHARGETERMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_BOLFREIGHTCOUNTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_BOLFREIGHTCOUNTED]  DEFAULT ((0)) FOR [BOLFREIGHTCOUNTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_BOLFREIGHTEDBY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_BOLFREIGHTEDBY]  DEFAULT ((0)) FOR [BOLFREIGHTEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_BOLLANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_BOLLANGUAGEID]  DEFAULT ('') FOR [BOLLANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_BOLTRAILERLOADED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_BOLTRAILERLOADED]  DEFAULT ((0)) FOR [BOLTRAILERLOADED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_CANCELSALES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_CANCELSALES]  DEFAULT ((0)) FOR [CANCELSALES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_CUSTQUOTATIONTYPEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_CUSTQUOTATIONTYPEID]  DEFAULT ('') FOR [CUSTQUOTATIONTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_DELETEHEADING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_DELETEHEADING]  DEFAULT ((0)) FOR [DELETEHEADING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_DELETELINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_DELETELINE]  DEFAULT ((0)) FOR [DELETELINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_DELIVERY2INVOICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_DELIVERY2INVOICE]  DEFAULT ('') FOR [DELIVERY2INVOICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_DISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_DISC]  DEFAULT ((0)) FOR [DISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_LEADTIMESALESDEFAULT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_LEADTIMESALESDEFAULT]  DEFAULT ((0)) FOR [LEADTIMESALESDEFAULT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_MARKUPHEADING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_MARKUPHEADING]  DEFAULT ((0)) FOR [MARKUPHEADING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_MARKUPLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_MARKUPLINE]  DEFAULT ((0)) FOR [MARKUPLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_ORDERENTRYSTATISTICS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_ORDERENTRYSTATISTICS]  DEFAULT ((0)) FOR [ORDERENTRYSTATISTICS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_ORDERTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_ORDERTYPE]  DEFAULT ((0)) FOR [ORDERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_OVERDELIVERY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_OVERDELIVERY]  DEFAULT ((0)) FOR [OVERDELIVERY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_PICKINGLISTDEFAULTLANGUAGE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_PICKINGLISTDEFAULTLANGUAGE]  DEFAULT ((0)) FOR [PICKINGLISTDEFAULTLANGUAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_POSTPACKINGSLIP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_POSTPACKINGSLIP]  DEFAULT ((0)) FOR [POSTPACKINGSLIP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_PREPRINTLEVELSHIPPINGLABEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_PREPRINTLEVELSHIPPINGLABEL]  DEFAULT ((0)) FOR [PREPRINTLEVELSHIPPINGLABEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_PROMPTTRANSFER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_PROMPTTRANSFER]  DEFAULT ((0)) FOR [PROMPTTRANSFER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_QUOTATIONNUMOFDAYSEXPIRYDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_QUOTATIONNUMOFDAYSEXPIRYDATE]  DEFAULT ((0)) FOR [QUOTATIONNUMOFDAYSEXPIRYDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_QUOTATIONNUMOFDAYSFOLLOWUPDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_QUOTATIONNUMOFDAYSFOLLOWUPDATE]  DEFAULT ((0)) FOR [QUOTATIONNUMOFDAYSFOLLOWUPDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_REDUCEINVOICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_REDUCEINVOICE]  DEFAULT ((0)) FOR [REDUCEINVOICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_REDUCEPACKINGSLIP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_REDUCEPACKINGSLIP]  DEFAULT ((0)) FOR [REDUCEPACKINGSLIP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_REDUCEPICKINGLIST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_REDUCEPICKINGLIST]  DEFAULT ((0)) FOR [REDUCEPICKINGLIST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_RESERVATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_RESERVATION]  DEFAULT ((0)) FOR [RESERVATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SALESORIGINID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SALESORIGINID]  DEFAULT ('') FOR [SALESORIGINID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SALESPOOLID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SALESPOOLID]  DEFAULT ('') FOR [SALESPOOLID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SETTLEVOUCHER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SETTLEVOUCHER]  DEFAULT ((0)) FOR [SETTLEVOUCHER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SHIPPINGSTAT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SHIPPINGSTAT]  DEFAULT ((0)) FOR [SHIPPINGSTAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SPLITDELIVERYCONFIRMATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SPLITDELIVERYCONFIRMATION]  DEFAULT ((0)) FOR [SPLITDELIVERYCONFIRMATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SPLITDELIVERYINVOICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SPLITDELIVERYINVOICE]  DEFAULT ((0)) FOR [SPLITDELIVERYINVOICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SPLITDELIVERYPACKINGSLIP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SPLITDELIVERYPACKINGSLIP]  DEFAULT ((0)) FOR [SPLITDELIVERYPACKINGSLIP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SPLITDELIVERYPICKINGLIST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SPLITDELIVERYPICKINGLIST]  DEFAULT ((0)) FOR [SPLITDELIVERYPICKINGLIST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SUBDELIVERY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SUBDELIVERY]  DEFAULT ((0)) FOR [SUBDELIVERY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SUMMARYERRORTOLERANCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SUMMARYERRORTOLERANCE]  DEFAULT ((0)) FOR [SUMMARYERRORTOLERANCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_SUMMARYUPDATEBY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_SUMMARYUPDATEBY]  DEFAULT ((0)) FOR [SUMMARYUPDATEBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_USESETTLEEXCHRATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_USESETTLEEXCHRATE]  DEFAULT ((0)) FOR [USESETTLEEXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SALESPARAMETERS_VALIDDAYS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SALESPARAMETERS] ADD  CONSTRAINT [DF_SALESPARAMETERS_VALIDDAYS]  DEFAULT ((0)) FOR [VALIDDAYS]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SALESPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SHIPCARRIERCOMPANYACCOUNTS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SHIPCARRIERCOMPANYACCOUNTS](
[RECID] [bigint] NOT NULL,
[ACCOUNTCODE] [nvarchar](20) NOT NULL,
[CARRIERNAME] [nvarchar](20) NOT NULL,
[CURRENCYCODE] [nvarchar](3) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_36305795_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_36305795_1216394877] UNIQUE NONCLUSTERED 
(
[ACCOUNTCODE] ASC,
[CARRIERNAME] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERCOMPANYACCOUNTS_ACCOUNTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERCOMPANYACCOUNTS] ADD  CONSTRAINT [DF_SHIPCARRIERCOMPANYACCOUNTS_ACCOUNTCODE]  DEFAULT ('') FOR [ACCOUNTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERCOMPANYACCOUNTS_CARRIERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERCOMPANYACCOUNTS] ADD  CONSTRAINT [DF_SHIPCARRIERCOMPANYACCOUNTS_CARRIERNAME]  DEFAULT ('') FOR [CARRIERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERCOMPANYACCOUNTS_CURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERCOMPANYACCOUNTS] ADD  CONSTRAINT [DF_SHIPCARRIERCOMPANYACCOUNTS_CURRENCYCODE]  DEFAULT ('') FOR [CURRENCYCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SHIPCARRIERCOMPANYACCOUNTS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SHIPCARRIERSTAGING]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SHIPCARRIERSTAGING](
[RECID] [bigint] NOT NULL,
[PACKINGSLIPID] [nvarchar](20) NOT NULL,
[SHIPDATE] [date] NOT NULL,
[TRACKINGNUMBER] [nvarchar](30) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-548708197_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERSTAGING_PACKINGSLIPID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERSTAGING] ADD  CONSTRAINT [DF_SHIPCARRIERSTAGING_PACKINGSLIPID]  DEFAULT ('') FOR [PACKINGSLIPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERSTAGING_SHIPDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERSTAGING] ADD  CONSTRAINT [DF_SHIPCARRIERSTAGING_SHIPDATE]  DEFAULT ('1900-01-01') FOR [SHIPDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERSTAGING_TRACKINGNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERSTAGING] ADD  CONSTRAINT [DF_SHIPCARRIERSTAGING_TRACKINGNUMBER]  DEFAULT ('') FOR [TRACKINGNUMBER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SHIPCARRIERSTAGING] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SHIPCARRIERTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SHIPCARRIERTABLE](
[RECID] [bigint] NOT NULL,
[CARRIERID] [nvarchar](10) NOT NULL,
[CARRIERINTERFACEID] [int] NOT NULL,
[CARRIERNAME] [nvarchar](20) NOT NULL,
[CARRIERSERVICEDESCRIPTION] [nvarchar](60) NOT NULL,
[RETAILSHIPCARRIERINTERFACE] [bigint] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_725690128_-1275116490] PRIMARY KEY CLUSTERED 
(
[CARRIERID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERTABLE_CARRIERID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERTABLE] ADD  CONSTRAINT [DF_SHIPCARRIERTABLE_CARRIERID]  DEFAULT ('') FOR [CARRIERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERTABLE_CARRIERINTERFACEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERTABLE] ADD  CONSTRAINT [DF_SHIPCARRIERTABLE_CARRIERINTERFACEID]  DEFAULT ((0)) FOR [CARRIERINTERFACEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERTABLE_CARRIERNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERTABLE] ADD  CONSTRAINT [DF_SHIPCARRIERTABLE_CARRIERNAME]  DEFAULT ('') FOR [CARRIERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERTABLE_CARRIERSERVICEDESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERTABLE] ADD  CONSTRAINT [DF_SHIPCARRIERTABLE_CARRIERSERVICEDESCRIPTION]  DEFAULT ('') FOR [CARRIERSERVICEDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SHIPCARRIERTABLE_RETAILSHIPCARRIERINTERFACE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SHIPCARRIERTABLE] ADD  CONSTRAINT [DF_SHIPCARRIERTABLE_RETAILSHIPCARRIERINTERFACE]  DEFAULT ((0)) FOR [RETAILSHIPCARRIERINTERFACE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SHIPCARRIERTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SYSTASKRECORDERFRAMEWORK]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SYSTASKRECORDERFRAMEWORK](
[RECID] [bigint] NOT NULL,
[FRAMEWORKID] [nvarchar](30) NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[PUBLISHER] [nvarchar](60) NOT NULL,
[SYNCID] [uniqueidentifier] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-2131136272_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-2131136272_-201728307] UNIQUE NONCLUSTERED 
(
[FRAMEWORKID] ASC,
[PUBLISHER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORK_FRAMEWORKID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORK] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORK_FRAMEWORKID]  DEFAULT ('') FOR [FRAMEWORKID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORK_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORK] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORK_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORK_PUBLISHER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORK] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORK_PUBLISHER]  DEFAULT ('') FOR [PUBLISHER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORK_SYNCID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORK] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORK_SYNCID]  DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SYNCID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SYSTASKRECORDERFRAMEWORK] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP](
[RECID] [bigint] NOT NULL,
[FRAMEWORK] [bigint] NOT NULL,
[GENERATEPROCESSDATA] [int] NOT NULL,
[INDUSTRY] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_617825684_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_617825684_777265151] UNIQUE NONCLUSTERED 
(
[INDUSTRY] ASC,
[FRAMEWORK] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKINDUSTRYMAP_FRAMEWORK]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKINDUSTRYMAP_FRAMEWORK]  DEFAULT ((0)) FOR [FRAMEWORK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKINDUSTRYMAP_GENERATEPROCESSDATA]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKINDUSTRYMAP_GENERATEPROCESSDATA]  DEFAULT ((0)) FOR [GENERATEPROCESSDATA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKINDUSTRYMAP_INDUSTRY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKINDUSTRYMAP_INDUSTRY]  DEFAULT ((0)) FOR [INDUSTRY]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SYSTASKRECORDERFRAMEWORKLEVEL]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SYSTASKRECORDERFRAMEWORKLEVEL](
[RECID] [bigint] NOT NULL,
[ALLOWARTIFACTS] [int] NOT NULL,
[FRAMEWORKINDUSTRYMAP] [bigint] NOT NULL,
[FRAMEWORKLEVEL] [nvarchar](20) NOT NULL,
[SEQUENCE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-138047098_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-138047098_-1016042189] UNIQUE NONCLUSTERED 
(
[FRAMEWORKLEVEL] ASC,
[FRAMEWORKINDUSTRYMAP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-138047098_-781073241] UNIQUE NONCLUSTERED 
(
[FRAMEWORKINDUSTRYMAP] ASC,
[SEQUENCE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLEVEL_ALLOWARTIFACTS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLEVEL] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLEVEL_ALLOWARTIFACTS]  DEFAULT ((0)) FOR [ALLOWARTIFACTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLEVEL_FRAMEWORKINDUSTRYMAP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLEVEL] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLEVEL_FRAMEWORKINDUSTRYMAP]  DEFAULT ((0)) FOR [FRAMEWORKINDUSTRYMAP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLEVEL_FRAMEWORKLEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLEVEL] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLEVEL_FRAMEWORKLEVEL]  DEFAULT ('') FOR [FRAMEWORKLEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLEVEL_SEQUENCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLEVEL] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLEVEL_SEQUENCE]  DEFAULT ((0)) FOR [SEQUENCE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SYSTASKRECORDERFRAMEWORKLEVEL] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SYSTASKRECORDERFRAMEWORKLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](max) NULL,
[FRAMEWORKLEVEL] [bigint] NOT NULL,
[INDENTATIONLEVEL] [int] NOT NULL,
[ISSUPPORTED] [int] NOT NULL,
[MEASURES] [nvarchar](max) NULL,
[MODULE] [int] NOT NULL,
[NAME] [nvarchar](255) NOT NULL,
[ORIGIN] [nvarchar](10) NOT NULL,
[PARENTFRAMEWORKLINE] [bigint] NOT NULL,
[SEQUENCE] [int] NOT NULL,
[SYNCID] [uniqueidentifier] NOT NULL,
[TASKRECORDEROPERATIONGROUP] [int] NOT NULL,
[USAGEPROFILE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1149662658_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_FRAMEWORKLEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_FRAMEWORKLEVEL]  DEFAULT ((0)) FOR [FRAMEWORKLEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_INDENTATIONLEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_INDENTATIONLEVEL]  DEFAULT ((0)) FOR [INDENTATIONLEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_ISSUPPORTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_ISSUPPORTED]  DEFAULT ((0)) FOR [ISSUPPORTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_MODULE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_MODULE]  DEFAULT ((0)) FOR [MODULE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_ORIGIN]  DEFAULT ('') FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_PARENTFRAMEWORKLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_PARENTFRAMEWORKLINE]  DEFAULT ((0)) FOR [PARENTFRAMEWORKLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_SEQUENCE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_SEQUENCE]  DEFAULT ((0)) FOR [SEQUENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_SYNCID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_SYNCID]  DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SYNCID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_TASKRECORDEROPERATIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_TASKRECORDEROPERATIONGROUP]  DEFAULT ((0)) FOR [TASKRECORDEROPERATIONGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERFRAMEWORKLINE_USAGEPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_USAGEPROFILE]  DEFAULT ((0)) FOR [USAGEPROFILE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SYSTASKRECORDERFRAMEWORKLINE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SYSTASKRECORDERINDUSTRY]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SYSTASKRECORDERINDUSTRY](
[RECID] [bigint] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[SYSTASKRECORDERINDUSTRYCODE] [nvarchar](20) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-568159942_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-568159942_-693532912] UNIQUE NONCLUSTERED 
(
[SYSTASKRECORDERINDUSTRYCODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERINDUSTRY_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERINDUSTRY] ADD  CONSTRAINT [DF_SYSTASKRECORDERINDUSTRY_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERINDUSTRY_SYSTASKRECORDERINDUSTRYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERINDUSTRY] ADD  CONSTRAINT [DF_SYSTASKRECORDERINDUSTRY_SYSTASKRECORDERINDUSTRYCODE]  DEFAULT ('') FOR [SYSTASKRECORDERINDUSTRYCODE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SYSTASKRECORDERINDUSTRY] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SYSTASKRECORDERLINEARTIFACT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SYSTASKRECORDERLINEARTIFACT](
[RECID] [bigint] NOT NULL,
[FILEPATH] [nvarchar](259) NOT NULL,
[FRAMEWORKLINE] [bigint] NOT NULL,
[SOURCEXML] [nvarchar](max) NULL,
[TYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1788916388_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1788916388_-1400817003] UNIQUE NONCLUSTERED 
(
[FRAMEWORKLINE] ASC,
[TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERLINEARTIFACT_FILEPATH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERLINEARTIFACT] ADD  CONSTRAINT [DF_SYSTASKRECORDERLINEARTIFACT_FILEPATH]  DEFAULT ('') FOR [FILEPATH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERLINEARTIFACT_FRAMEWORKLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERLINEARTIFACT] ADD  CONSTRAINT [DF_SYSTASKRECORDERLINEARTIFACT_FRAMEWORKLINE]  DEFAULT ((0)) FOR [FRAMEWORKLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERLINEARTIFACT_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERLINEARTIFACT] ADD  CONSTRAINT [DF_SYSTASKRECORDERLINEARTIFACT_TYPE]  DEFAULT ((0)) FOR [TYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SYSTASKRECORDERLINEARTIFACT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[SYSTASKRECORDERPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[SYSTASKRECORDERPARAMETERS](
[RECID] [bigint] NOT NULL,
[FILEPATH] [nvarchar](259) NOT NULL,
[KEY] [int] NOT NULL,
[TEMPLATEPATH] [nvarchar](259) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-32377564_-1273337705] PRIMARY KEY CLUSTERED 
(
[KEY] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERPARAMETERS_FILEPATH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERPARAMETERS] ADD  CONSTRAINT [DF_SYSTASKRECORDERPARAMETERS_FILEPATH]  DEFAULT ('') FOR [FILEPATH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERPARAMETERS] ADD  CONSTRAINT [DF_SYSTASKRECORDERPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_SYSTASKRECORDERPARAMETERS_TEMPLATEPATH]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[SYSTASKRECORDERPARAMETERS] ADD  CONSTRAINT [DF_SYSTASKRECORDERPARAMETERS_TEMPLATEPATH]  DEFAULT ('') FOR [TEMPLATEPATH]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[SYSTASKRECORDERPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXATIONCODESETUP_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXATIONCODESETUP_BR](
[RECID] [bigint] NOT NULL,
[MANDATORY] [int] NOT NULL,
[TAXTYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_734124585_-2105670234] PRIMARY KEY CLUSTERED 
(
[TAXTYPE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODESETUP_BR_MANDATORY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODESETUP_BR] ADD  CONSTRAINT [DF_TAXATIONCODESETUP_BR_MANDATORY]  DEFAULT ((0)) FOR [MANDATORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODESETUP_BR_TAXTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODESETUP_BR] ADD  CONSTRAINT [DF_TAXATIONCODESETUP_BR_TAXTYPE]  DEFAULT ((0)) FOR [TAXTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXATIONCODESETUP_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXATIONCODETABLE_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXATIONCODETABLE_BR](
[RECID] [bigint] NOT NULL,
[ATOCOTEPETAXCODE] [nvarchar](3) NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[FISCALVALUE] [int] NOT NULL,
[FROMDATE] [date] NOT NULL,
[INPUTCODE] [nchar](1) NOT NULL,
[OUTPUTCODE] [nchar](1) NOT NULL,
[TAXATIONCODE] [nvarchar](3) NOT NULL,
[TAXTYPE] [int] NOT NULL,
[TODATE] [date] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1348432140_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1348432140_1249524576] UNIQUE NONCLUSTERED 
(
[TAXTYPE] ASC,
[TAXATIONCODE] ASC,
[FISCALVALUE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_ATOCOTEPETAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_ATOCOTEPETAXCODE]  DEFAULT ('') FOR [ATOCOTEPETAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_FISCALVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_FISCALVALUE]  DEFAULT ((0)) FOR [FISCALVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_FROMDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_FROMDATE]  DEFAULT ('1900-01-01') FOR [FROMDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_INPUTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_INPUTCODE]  DEFAULT ('') FOR [INPUTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_OUTPUTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_OUTPUTCODE]  DEFAULT ('') FOR [OUTPUTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_TAXATIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_TAXATIONCODE]  DEFAULT ('') FOR [TAXATIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_TAXTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_TAXTYPE]  DEFAULT ((0)) FOR [TAXTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXATIONCODETABLE_BR_TODATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXATIONCODETABLE_BR] ADD  CONSTRAINT [DF_TAXATIONCODETABLE_BR_TODATE]  DEFAULT ('1900-01-01') FOR [TODATE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXATIONCODETABLE_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXCOLLECTLIMIT]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXCOLLECTLIMIT](
[RECID] [bigint] NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXFROMDATE] [date] NOT NULL,
[TAXMAX] [numeric](32, 16) NOT NULL,
[TAXMIN] [numeric](32, 16) NOT NULL,
[TAXTODATE] [date] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-594010114_-1078995487] PRIMARY KEY CLUSTERED 
(
[TAXCODE] ASC,
[RECID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXCOLLECTLIMIT_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXCOLLECTLIMIT] ADD  CONSTRAINT [DF_TAXCOLLECTLIMIT_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXCOLLECTLIMIT_TAXFROMDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXCOLLECTLIMIT] ADD  CONSTRAINT [DF_TAXCOLLECTLIMIT_TAXFROMDATE]  DEFAULT ('1900-01-01') FOR [TAXFROMDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXCOLLECTLIMIT_TAXMAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXCOLLECTLIMIT] ADD  CONSTRAINT [DF_TAXCOLLECTLIMIT_TAXMAX]  DEFAULT ((0)) FOR [TAXMAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXCOLLECTLIMIT_TAXMIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXCOLLECTLIMIT] ADD  CONSTRAINT [DF_TAXCOLLECTLIMIT_TAXMIN]  DEFAULT ((0)) FOR [TAXMIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXCOLLECTLIMIT_TAXTODATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXCOLLECTLIMIT] ADD  CONSTRAINT [DF_TAXCOLLECTLIMIT_TAXTODATE]  DEFAULT ('1900-01-01') FOR [TAXTODATE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXCOLLECTLIMIT] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXCOMPONENTTABLE_IN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXCOMPONENTTABLE_IN](
[RECID] [bigint] NOT NULL,
[COMPONENT] [nvarchar](15) NOT NULL,
[TAXTYPE] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1073210900_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1073210900_1038721528] UNIQUE NONCLUSTERED 
(
[COMPONENT] ASC,
[TAXTYPE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXCOMPONENTTABLE_IN_COMPONENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXCOMPONENTTABLE_IN] ADD  CONSTRAINT [DF_TAXCOMPONENTTABLE_IN_COMPONENT]  DEFAULT ('') FOR [COMPONENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXCOMPONENTTABLE_IN_TAXTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXCOMPONENTTABLE_IN] ADD  CONSTRAINT [DF_TAXCOMPONENTTABLE_IN_TAXTYPE]  DEFAULT ((0)) FOR [TAXTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXCOMPONENTTABLE_IN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXDATA]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXDATA](
[RECID] [bigint] NOT NULL,
[SALESTAXFORMTYPES_IN] [bigint] NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXFROMDATE] [date] NOT NULL,
[TAXLIMITMAX] [numeric](32, 16) NOT NULL,
[TAXLIMITMIN] [numeric](32, 16) NOT NULL,
[TAXREDUCTIONPCT_BR] [numeric](32, 16) NOT NULL,
[TAXTODATE] [date] NOT NULL,
[TAXVALUE] [numeric](32, 16) NOT NULL,
[VATEXEMPTPCT] [numeric](32, 16) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1794926035_2112191097] PRIMARY KEY CLUSTERED 
(
[TAXCODE] ASC,
[TAXFROMDATE] ASC,
[TAXTODATE] ASC,
[TAXLIMITMIN] ASC,
[RECID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_SALESTAXFORMTYPES_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_SALESTAXFORMTYPES_IN]  DEFAULT ((0)) FOR [SALESTAXFORMTYPES_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_TAXFROMDATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_TAXFROMDATE]  DEFAULT ('1900-01-01') FOR [TAXFROMDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_TAXLIMITMAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_TAXLIMITMAX]  DEFAULT ((0)) FOR [TAXLIMITMAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_TAXLIMITMIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_TAXLIMITMIN]  DEFAULT ((0)) FOR [TAXLIMITMIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_TAXREDUCTIONPCT_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_TAXREDUCTIONPCT_BR]  DEFAULT ((0)) FOR [TAXREDUCTIONPCT_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_TAXTODATE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_TAXTODATE]  DEFAULT ('1900-01-01') FOR [TAXTODATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_TAXVALUE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_TAXVALUE]  DEFAULT ((0)) FOR [TAXVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXDATA_VATEXEMPTPCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXDATA] ADD  CONSTRAINT [DF_TAXDATA_VATEXEMPTPCT]  DEFAULT ((0)) FOR [VATEXEMPTPCT]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXDATA] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXFISCALCLASSIFICATION_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXFISCALCLASSIFICATION_BR](
[RECID] [bigint] NOT NULL,
[APPROXTAXVALUEIMPORTED] [numeric](32, 16) NOT NULL,
[APPROXTAXVALUENATIONAL] [numeric](32, 16) NOT NULL,
[FISCALCLASSIFICATIONID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1219540014_944565509] PRIMARY KEY CLUSTERED 
(
[FISCALCLASSIFICATIONID] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXFISCALCLASSIFICATION_BR_APPROXTAXVALUEIMPORTED]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXFISCALCLASSIFICATION_BR] ADD  CONSTRAINT [DF_TAXFISCALCLASSIFICATION_BR_APPROXTAXVALUEIMPORTED]  DEFAULT ((0)) FOR [APPROXTAXVALUEIMPORTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXFISCALCLASSIFICATION_BR_APPROXTAXVALUENATIONAL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXFISCALCLASSIFICATION_BR] ADD  CONSTRAINT [DF_TAXFISCALCLASSIFICATION_BR_APPROXTAXVALUENATIONAL]  DEFAULT ((0)) FOR [APPROXTAXVALUENATIONAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXFISCALCLASSIFICATION_BR_FISCALCLASSIFICATIONID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXFISCALCLASSIFICATION_BR] ADD  CONSTRAINT [DF_TAXFISCALCLASSIFICATION_BR_FISCALCLASSIFICATIONID]  DEFAULT ('') FOR [FISCALCLASSIFICATIONID]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXFISCALCLASSIFICATION_BR] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXGROUPDATA]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXGROUPDATA](
[RECID] [bigint] NOT NULL,
[EXEMPTTAX] [int] NOT NULL,
[TAXATIONCODETABLE_BR] [bigint] NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[USETAX] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-469848310_-1912629129] PRIMARY KEY CLUSTERED 
(
[TAXGROUP] ASC,
[TAXCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-469848310_-1078995487] UNIQUE NONCLUSTERED 
(
[TAXCODE] ASC,
[TAXGROUP] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPDATA_EXEMPTTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPDATA] ADD  CONSTRAINT [DF_TAXGROUPDATA_EXEMPTTAX]  DEFAULT ((0)) FOR [EXEMPTTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPDATA_TAXATIONCODETABLE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPDATA] ADD  CONSTRAINT [DF_TAXGROUPDATA_TAXATIONCODETABLE_BR]  DEFAULT ((0)) FOR [TAXATIONCODETABLE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPDATA_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPDATA] ADD  CONSTRAINT [DF_TAXGROUPDATA_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPDATA_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPDATA] ADD  CONSTRAINT [DF_TAXGROUPDATA_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPDATA_USETAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPDATA] ADD  CONSTRAINT [DF_TAXGROUPDATA_USETAX]  DEFAULT ((0)) FOR [USETAX]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXGROUPDATA] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXGROUPHEADING]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXGROUPHEADING](
[RECID] [bigint] NOT NULL,
[SEARCHFIELD1] [nvarchar](60) NOT NULL,
[SEARCHFIELD2] [nvarchar](60) NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXGROUPNAME] [nvarchar](60) NOT NULL,
[TAXGROUPROUNDING] [int] NOT NULL,
[TAXGROUPSETUP] [int] NOT NULL,
[TAXPRINTDETAIL] [int] NOT NULL,
[TAXREVERSEONCASHDISC] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-326351512_-1912629129] PRIMARY KEY CLUSTERED 
(
[TAXGROUP] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_SEARCHFIELD1]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_SEARCHFIELD1]  DEFAULT ('') FOR [SEARCHFIELD1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_SEARCHFIELD2]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_SEARCHFIELD2]  DEFAULT ('') FOR [SEARCHFIELD2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_TAXGROUPNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_TAXGROUPNAME]  DEFAULT ('') FOR [TAXGROUPNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_TAXGROUPROUNDING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_TAXGROUPROUNDING]  DEFAULT ((0)) FOR [TAXGROUPROUNDING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_TAXGROUPSETUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_TAXGROUPSETUP]  DEFAULT ((0)) FOR [TAXGROUPSETUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_TAXPRINTDETAIL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_TAXPRINTDETAIL]  DEFAULT ((0)) FOR [TAXPRINTDETAIL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXGROUPHEADING_TAXREVERSEONCASHDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXGROUPHEADING] ADD  CONSTRAINT [DF_TAXGROUPHEADING_TAXREVERSEONCASHDISC]  DEFAULT ((0)) FOR [TAXREVERSEONCASHDISC]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXGROUPHEADING] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXINFORMATION_IN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXINFORMATION_IN](
[RECID] [bigint] NOT NULL,
[ECCNUMBER] [bigint] NOT NULL,
[ISPRIMARY] [int] NOT NULL,
[NAME] [nvarchar](60) NOT NULL,
[REGISTRATIONLOCATION] [bigint] NOT NULL,
[STCREGISTRATIONNUMBERTABLE] [bigint] NOT NULL,
[TIN] [bigint] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1576999069_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1576999069_-1966747349] UNIQUE NONCLUSTERED 
(
[NAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATION_IN_ECCNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATION_IN] ADD  CONSTRAINT [DF_TAXINFORMATION_IN_ECCNUMBER]  DEFAULT ((0)) FOR [ECCNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATION_IN_ISPRIMARY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATION_IN] ADD  CONSTRAINT [DF_TAXINFORMATION_IN_ISPRIMARY]  DEFAULT ((0)) FOR [ISPRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATION_IN_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATION_IN] ADD  CONSTRAINT [DF_TAXINFORMATION_IN_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATION_IN_REGISTRATIONLOCATION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATION_IN] ADD  CONSTRAINT [DF_TAXINFORMATION_IN_REGISTRATIONLOCATION]  DEFAULT ((0)) FOR [REGISTRATIONLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATION_IN_STCREGISTRATIONNUMBERTABLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATION_IN] ADD  CONSTRAINT [DF_TAXINFORMATION_IN_STCREGISTRATIONNUMBERTABLE]  DEFAULT ((0)) FOR [STCREGISTRATIONNUMBERTABLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATION_IN_TIN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATION_IN] ADD  CONSTRAINT [DF_TAXINFORMATION_IN_TIN]  DEFAULT ((0)) FOR [TIN]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXINFORMATION_IN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXINFORMATIONLEGALENTITY_IN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXINFORMATIONLEGALENTITY_IN](
[RECID] [bigint] NOT NULL,
[LEGALENTITY] [bigint] NOT NULL,
[PANNUMBER] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_2121961721_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_2121961721_-427987640] UNIQUE NONCLUSTERED 
(
[LEGALENTITY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATIONLEGALENTITY_IN_LEGALENTITY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATIONLEGALENTITY_IN] ADD  CONSTRAINT [DF_TAXINFORMATIONLEGALENTITY_IN_LEGALENTITY]  DEFAULT ((0)) FOR [LEGALENTITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXINFORMATIONLEGALENTITY_IN_PANNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXINFORMATIONLEGALENTITY_IN] ADD  CONSTRAINT [DF_TAXINFORMATIONLEGALENTITY_IN_PANNUMBER]  DEFAULT ('') FOR [PANNUMBER]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXINFORMATIONLEGALENTITY_IN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXONITEM]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXONITEM](
[RECID] [bigint] NOT NULL,
[ABATEMENTPERCENT_IN] [numeric](32, 16) NOT NULL,
[EXEMPTTAX_BR] [int] NOT NULL,
[TAXATIONCODETABLE_BR] [bigint] NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[WITHOUTTAXCREDIT_BR] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_1486226945_-2114646326] PRIMARY KEY CLUSTERED 
(
[TAXITEMGROUP] ASC,
[TAXCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_1486226945_-1293317740] UNIQUE NONCLUSTERED 
(
[TAXCODE] ASC,
[TAXITEMGROUP] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXONITEM_ABATEMENTPERCENT_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXONITEM] ADD  CONSTRAINT [DF_TAXONITEM_ABATEMENTPERCENT_IN]  DEFAULT ((0)) FOR [ABATEMENTPERCENT_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXONITEM_EXEMPTTAX_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXONITEM] ADD  CONSTRAINT [DF_TAXONITEM_EXEMPTTAX_BR]  DEFAULT ((0)) FOR [EXEMPTTAX_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXONITEM_TAXATIONCODETABLE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXONITEM] ADD  CONSTRAINT [DF_TAXONITEM_TAXATIONCODETABLE_BR]  DEFAULT ((0)) FOR [TAXATIONCODETABLE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXONITEM_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXONITEM] ADD  CONSTRAINT [DF_TAXONITEM_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXONITEM_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXONITEM] ADD  CONSTRAINT [DF_TAXONITEM_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXONITEM_WITHOUTTAXCREDIT_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXONITEM] ADD  CONSTRAINT [DF_TAXONITEM_WITHOUTTAXCREDIT_BR]  DEFAULT ((0)) FOR [WITHOUTTAXCREDIT_BR]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXONITEM] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXPARAMETERS](
[RECID] [bigint] NOT NULL,
[ALLOWDUPLICATES] [int] NOT NULL,
[CALCULATEPRINCIPLE] [int] NOT NULL,
[CASHDISCONINVOICE] [int] NOT NULL,
[CHECKINTERSECTION] [int] NOT NULL,
[CONDITIONALTAX] [int] NOT NULL,
[CUSTOMERCALCULATIONDATETYPE_IN] [int] NOT NULL,
[CUSTOMS_IN] [int] NOT NULL,
[EXCISE_IN] [int] NOT NULL,
[EXIMINCENTIVESCHEMES_IN] [int] NOT NULL,
[JOURNALINCLTAX] [int] NOT NULL,
[KEY] [int] NOT NULL,
[MANDATORYTAXDIRECTION] [int] NOT NULL,
[PURCHTAXONOPERATIONS] [int] NOT NULL,
[REPORTADJUSTMENT] [int] NOT NULL,
[REVERSEONCASHDISC] [int] NOT NULL,
[SALESTAX_IN] [int] NOT NULL,
[SERVICETAX_IN] [int] NOT NULL,
[TAXCALCULATIONDATETYPE] [int] NOT NULL,
[TAXGROUP] [nvarchar](10) NOT NULL,
[TAXITEMGROUP] [nvarchar](10) NOT NULL,
[TAXLESSCASHDISC] [int] NOT NULL,
[TAXONOVERPAYMENT] [int] NOT NULL,
[TAXRECOVERABLE_IN] [int] NOT NULL,
[TAXREPORT_JP] [int] NOT NULL,
[TAXSPECIFYLINE] [int] NOT NULL,
[VALIDATETAXCODE] [int] NOT NULL,
[VAT_IN] [int] NOT NULL,
[VENDORCALCULATIONDATETYPE_IN] [int] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-908637253_-1273338697] PRIMARY KEY CLUSTERED 
(
[KEY] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_ALLOWDUPLICATES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_ALLOWDUPLICATES]  DEFAULT ((0)) FOR [ALLOWDUPLICATES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_CALCULATEPRINCIPLE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_CALCULATEPRINCIPLE]  DEFAULT ((0)) FOR [CALCULATEPRINCIPLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_CASHDISCONINVOICE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_CASHDISCONINVOICE]  DEFAULT ((0)) FOR [CASHDISCONINVOICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_CHECKINTERSECTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_CHECKINTERSECTION]  DEFAULT ((0)) FOR [CHECKINTERSECTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_CONDITIONALTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_CONDITIONALTAX]  DEFAULT ((0)) FOR [CONDITIONALTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_CUSTOMERCALCULATIONDATETYPE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_CUSTOMERCALCULATIONDATETYPE_IN]  DEFAULT ((0)) FOR [CUSTOMERCALCULATIONDATETYPE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_CUSTOMS_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_CUSTOMS_IN]  DEFAULT ((0)) FOR [CUSTOMS_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_EXCISE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_EXCISE_IN]  DEFAULT ((0)) FOR [EXCISE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_EXIMINCENTIVESCHEMES_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_EXIMINCENTIVESCHEMES_IN]  DEFAULT ((0)) FOR [EXIMINCENTIVESCHEMES_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_JOURNALINCLTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_JOURNALINCLTAX]  DEFAULT ((0)) FOR [JOURNALINCLTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_MANDATORYTAXDIRECTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_MANDATORYTAXDIRECTION]  DEFAULT ((0)) FOR [MANDATORYTAXDIRECTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_PURCHTAXONOPERATIONS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_PURCHTAXONOPERATIONS]  DEFAULT ((0)) FOR [PURCHTAXONOPERATIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_REPORTADJUSTMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_REPORTADJUSTMENT]  DEFAULT ((0)) FOR [REPORTADJUSTMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_REVERSEONCASHDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_REVERSEONCASHDISC]  DEFAULT ((0)) FOR [REVERSEONCASHDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_SALESTAX_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_SALESTAX_IN]  DEFAULT ((0)) FOR [SALESTAX_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_SERVICETAX_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_SERVICETAX_IN]  DEFAULT ((0)) FOR [SERVICETAX_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXCALCULATIONDATETYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXCALCULATIONDATETYPE]  DEFAULT ((0)) FOR [TAXCALCULATIONDATETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXGROUP]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXITEMGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXITEMGROUP]  DEFAULT ('') FOR [TAXITEMGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXLESSCASHDISC]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXLESSCASHDISC]  DEFAULT ((0)) FOR [TAXLESSCASHDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXONOVERPAYMENT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXONOVERPAYMENT]  DEFAULT ((0)) FOR [TAXONOVERPAYMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXRECOVERABLE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXRECOVERABLE_IN]  DEFAULT ((0)) FOR [TAXRECOVERABLE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXREPORT_JP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXREPORT_JP]  DEFAULT ((0)) FOR [TAXREPORT_JP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_TAXSPECIFYLINE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_TAXSPECIFYLINE]  DEFAULT ((0)) FOR [TAXSPECIFYLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_VALIDATETAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_VALIDATETAXCODE]  DEFAULT ((0)) FOR [VALIDATETAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_VAT_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_VAT_IN]  DEFAULT ((0)) FOR [VAT_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_VENDORCALCULATIONDATETYPE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_VENDORCALCULATIONDATETYPE_IN]  DEFAULT ((0)) FOR [VENDORCALCULATIONDATETYPE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXPARAMETERS_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXPARAMETERS] ADD  CONSTRAINT [DF_TAXPARAMETERS_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXPARAMETERS] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXREGISTRATIONNUMBERS_IN]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXREGISTRATIONNUMBERS_IN](
[RECID] [bigint] NOT NULL,
[REGISTRATIONNUMBER] [nvarchar](15) NOT NULL,
[REGISTRATIONTYPE] [int] NOT NULL,
[TAXTYPE] [int] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1544047818_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1544047818_-1285409270] UNIQUE NONCLUSTERED 
(
[REGISTRATIONTYPE] ASC,
[TAXTYPE] ASC,
[REGISTRATIONNUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXREGISTRATIONNUMBERS_IN_REGISTRATIONNUMBER]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXREGISTRATIONNUMBERS_IN] ADD  CONSTRAINT [DF_TAXREGISTRATIONNUMBERS_IN_REGISTRATIONNUMBER]  DEFAULT ('') FOR [REGISTRATIONNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXREGISTRATIONNUMBERS_IN_REGISTRATIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXREGISTRATIONNUMBERS_IN] ADD  CONSTRAINT [DF_TAXREGISTRATIONNUMBERS_IN_REGISTRATIONTYPE]  DEFAULT ((0)) FOR [REGISTRATIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXREGISTRATIONNUMBERS_IN_TAXTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXREGISTRATIONNUMBERS_IN] ADD  CONSTRAINT [DF_TAXREGISTRATIONNUMBERS_IN_TAXTYPE]  DEFAULT ((0)) FOR [TAXTYPE]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXREGISTRATIONNUMBERS_IN] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[TAXTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[TAXTABLE](
[RECID] [bigint] NOT NULL,
[CUSTOMSPRACTICE_FI] [int] NOT NULL,
[INCLUDEDTAX_BR] [int] NOT NULL,
[NEGATIVETAX] [int] NOT NULL,
[NOTEUSALESLIST] [int] NOT NULL,
[PAYMENTTAXCODE] [nvarchar](10) NOT NULL,
[PRINTCODE] [nvarchar](10) NOT NULL,
[REPFIELDBASEINCOMING] [int] NOT NULL,
[REPFIELDBASEINCOMINGCREDITNOTE] [int] NOT NULL,
[REPFIELDBASEOUTGOING] [int] NOT NULL,
[REPFIELDBASEOUTGOINGCREDITNOTE] [int] NOT NULL,
[REPFIELDBASEUSETAX] [int] NOT NULL,
[REPFIELDBASEUSETAXCREDITNOTE] [int] NOT NULL,
[REPFIELDBASEUSETAXOFFSET] [int] NOT NULL,
[REPFIELDBASEUSETAXOFFSETCREDITNOTE] [int] NOT NULL,
[REPFIELDTAXFREEBUY] [int] NOT NULL,
[REPFIELDTAXFREEBUYCREDITNOTE] [int] NOT NULL,
[REPFIELDTAXFREESALES] [int] NOT NULL,
[REPFIELDTAXFREESALESCREDITNOTE] [int] NOT NULL,
[REPFIELDTAXINCOMING] [int] NOT NULL,
[REPFIELDTAXINCOMINGCREDITNOTE] [int] NOT NULL,
[REPFIELDTAXOUTGOING] [int] NOT NULL,
[REPFIELDTAXOUTGOINGCREDITNOTE] [int] NOT NULL,
[REPFIELDUSETAX] [int] NOT NULL,
[REPFIELDUSETAXCREDITNOTE] [int] NOT NULL,
[REPFIELDUSETAXOFFSET] [int] NOT NULL,
[REPFIELDUSETAXOFFSETCREDITNOTE] [int] NOT NULL,
[RETAINEDTAX_BR] [int] NOT NULL,
[REVENUECODE_BR] [nvarchar](20) NOT NULL,
[TAXACCOUNTGROUP] [nvarchar](10) NOT NULL,
[TAXATIONCODETABLE_BR] [bigint] NOT NULL,
[TAXBASE] [int] NOT NULL,
[TAXBORDERNUMREQ_FI] [int] NOT NULL,
[TAXCALCMETHOD] [int] NOT NULL,
[TAXCODE] [nvarchar](10) NOT NULL,
[TAXCOMPONENTTABLE_IN] [bigint] NOT NULL,
[TAXCOUNTRYREGIONTYPE] [int] NOT NULL,
[TAXCURRENCYCODE] [nvarchar](3) NOT NULL,
[TAXINCLUDEINTAX] [int] NOT NULL,
[TAXJURISDICTIONCODE] [nvarchar](10) NOT NULL,
[TAXLIMITBASE] [int] NOT NULL,
[TAXNAME] [nvarchar](30) NOT NULL,
[TAXONTAX] [nvarchar](10) NOT NULL,
[TAXPACKAGINGSORT] [nvarchar](10) NOT NULL,
[TAXPACKAGINGTAX] [int] NOT NULL,
[TAXPERIOD] [nvarchar](10) NOT NULL,
[TAXPURCHASETAX] [int] NOT NULL,
[TAXROUNDOFF] [numeric](32, 16) NOT NULL,
[TAXROUNDOFFTYPE] [int] NOT NULL,
[TAXSUBSTITUTION_BR] [int] NOT NULL,
[TAXTYPE_BR] [int] NOT NULL,
[TAXTYPE_IN] [int] NOT NULL,
[TAXTYPE_SG] [int] NOT NULL,
[TAXUNIT] [nvarchar](10) NOT NULL,
[TAXWRITESELECTION] [int] NOT NULL,
[UNREALIZEDTAX] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1870905641_-787576842] PRIMARY KEY CLUSTERED 
(
[TAXCODE] ASC,
[DATAAREAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_CUSTOMSPRACTICE_FI]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_CUSTOMSPRACTICE_FI]  DEFAULT ((0)) FOR [CUSTOMSPRACTICE_FI]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_INCLUDEDTAX_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_INCLUDEDTAX_BR]  DEFAULT ((0)) FOR [INCLUDEDTAX_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_NEGATIVETAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_NEGATIVETAX]  DEFAULT ((0)) FOR [NEGATIVETAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_NOTEUSALESLIST]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_NOTEUSALESLIST]  DEFAULT ((0)) FOR [NOTEUSALESLIST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_PAYMENTTAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_PAYMENTTAXCODE]  DEFAULT ('') FOR [PAYMENTTAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_PRINTCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_PRINTCODE]  DEFAULT ('') FOR [PRINTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEINCOMING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEINCOMING]  DEFAULT ((0)) FOR [REPFIELDBASEINCOMING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEINCOMINGCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEINCOMINGCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDBASEINCOMINGCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEOUTGOING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEOUTGOING]  DEFAULT ((0)) FOR [REPFIELDBASEOUTGOING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEOUTGOINGCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEOUTGOINGCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDBASEOUTGOINGCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEUSETAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEUSETAX]  DEFAULT ((0)) FOR [REPFIELDBASEUSETAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEUSETAXCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEUSETAXCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDBASEUSETAXCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEUSETAXOFFSET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEUSETAXOFFSET]  DEFAULT ((0)) FOR [REPFIELDBASEUSETAXOFFSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDBASEUSETAXOFFSETCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDBASEUSETAXOFFSETCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDBASEUSETAXOFFSETCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXFREEBUY]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXFREEBUY]  DEFAULT ((0)) FOR [REPFIELDTAXFREEBUY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXFREEBUYCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXFREEBUYCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDTAXFREEBUYCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXFREESALES]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXFREESALES]  DEFAULT ((0)) FOR [REPFIELDTAXFREESALES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXFREESALESCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXFREESALESCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDTAXFREESALESCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXINCOMING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXINCOMING]  DEFAULT ((0)) FOR [REPFIELDTAXINCOMING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXINCOMINGCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXINCOMINGCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDTAXINCOMINGCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXOUTGOING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXOUTGOING]  DEFAULT ((0)) FOR [REPFIELDTAXOUTGOING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDTAXOUTGOINGCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDTAXOUTGOINGCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDTAXOUTGOINGCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDUSETAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDUSETAX]  DEFAULT ((0)) FOR [REPFIELDUSETAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDUSETAXCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDUSETAXCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDUSETAXCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDUSETAXOFFSET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDUSETAXOFFSET]  DEFAULT ((0)) FOR [REPFIELDUSETAXOFFSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REPFIELDUSETAXOFFSETCREDITNOTE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REPFIELDUSETAXOFFSETCREDITNOTE]  DEFAULT ((0)) FOR [REPFIELDUSETAXOFFSETCREDITNOTE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_RETAINEDTAX_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_RETAINEDTAX_BR]  DEFAULT ((0)) FOR [RETAINEDTAX_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_REVENUECODE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_REVENUECODE_BR]  DEFAULT ('') FOR [REVENUECODE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXACCOUNTGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXACCOUNTGROUP]  DEFAULT ('') FOR [TAXACCOUNTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXATIONCODETABLE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXATIONCODETABLE_BR]  DEFAULT ((0)) FOR [TAXATIONCODETABLE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXBASE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXBASE]  DEFAULT ((0)) FOR [TAXBASE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXBORDERNUMREQ_FI]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXBORDERNUMREQ_FI]  DEFAULT ((0)) FOR [TAXBORDERNUMREQ_FI]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXCALCMETHOD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXCALCMETHOD]  DEFAULT ((0)) FOR [TAXCALCMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXCODE]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXCOMPONENTTABLE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXCOMPONENTTABLE_IN]  DEFAULT ((0)) FOR [TAXCOMPONENTTABLE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXCOUNTRYREGIONTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXCOUNTRYREGIONTYPE]  DEFAULT ((0)) FOR [TAXCOUNTRYREGIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXCURRENCYCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXCURRENCYCODE]  DEFAULT ('') FOR [TAXCURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXINCLUDEINTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXINCLUDEINTAX]  DEFAULT ((0)) FOR [TAXINCLUDEINTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXJURISDICTIONCODE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXJURISDICTIONCODE]  DEFAULT ('') FOR [TAXJURISDICTIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXLIMITBASE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXLIMITBASE]  DEFAULT ((0)) FOR [TAXLIMITBASE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXNAME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXNAME]  DEFAULT ('') FOR [TAXNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXONTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXONTAX]  DEFAULT ('') FOR [TAXONTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXPACKAGINGSORT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXPACKAGINGSORT]  DEFAULT ('') FOR [TAXPACKAGINGSORT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXPACKAGINGTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXPACKAGINGTAX]  DEFAULT ((0)) FOR [TAXPACKAGINGTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXPERIOD]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXPERIOD]  DEFAULT ('') FOR [TAXPERIOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXPURCHASETAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXPURCHASETAX]  DEFAULT ((0)) FOR [TAXPURCHASETAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXROUNDOFF]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXROUNDOFF]  DEFAULT ((0)) FOR [TAXROUNDOFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXROUNDOFFTYPE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXROUNDOFFTYPE]  DEFAULT ((0)) FOR [TAXROUNDOFFTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXSUBSTITUTION_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXSUBSTITUTION_BR]  DEFAULT ((0)) FOR [TAXSUBSTITUTION_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXTYPE_BR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXTYPE_BR]  DEFAULT ((0)) FOR [TAXTYPE_BR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXTYPE_IN]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXTYPE_IN]  DEFAULT ((0)) FOR [TAXTYPE_IN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXTYPE_SG]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXTYPE_SG]  DEFAULT ((0)) FOR [TAXTYPE_SG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXUNIT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXUNIT]  DEFAULT ('') FOR [TAXUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_TAXWRITESELECTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_TAXWRITESELECTION]  DEFAULT ((0)) FOR [TAXWRITESELECTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_TAXTABLE_UNREALIZEDTAX]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[TAXTABLE] ADD  CONSTRAINT [DF_TAXTABLE_UNREALIZEDTAX]  DEFAULT ((0)) FOR [UNREALIZEDTAX]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[TAXTABLE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[UNITOFMEASURE]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[UNITOFMEASURE](
[RECID] [bigint] NOT NULL,
[DECIMALPRECISION] [int] NOT NULL,
[SYMBOL] [nvarchar](10) NOT NULL,
[SYSTEMOFUNITS] [int] NOT NULL,
[UNITOFMEASURECLASS] [int] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1127893861_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1127893861_-1854694893] UNIQUE NONCLUSTERED 
(
[SYMBOL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURE_DECIMALPRECISION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURE] ADD  CONSTRAINT [DF_UNITOFMEASURE_DECIMALPRECISION]  DEFAULT ((0)) FOR [DECIMALPRECISION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURE_SYMBOL]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURE] ADD  CONSTRAINT [DF_UNITOFMEASURE_SYMBOL]  DEFAULT ('') FOR [SYMBOL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURE_SYSTEMOFUNITS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURE] ADD  CONSTRAINT [DF_UNITOFMEASURE_SYSTEMOFUNITS]  DEFAULT ((0)) FOR [SYSTEMOFUNITS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURE_UNITOFMEASURECLASS]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURE] ADD  CONSTRAINT [DF_UNITOFMEASURE_UNITOFMEASURECLASS]  DEFAULT ((0)) FOR [UNITOFMEASURECLASS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURE_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURE] ADD  CONSTRAINT [DF_UNITOFMEASURE_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[UNITOFMEASURE] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[UNITOFMEASURECONVERSION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[UNITOFMEASURECONVERSION](
[RECID] [bigint] NOT NULL,
[DENOMINATOR] [int] NOT NULL,
[FACTOR] [numeric](32, 16) NOT NULL,
[FROMUNITOFMEASURE] [bigint] NOT NULL,
[INNEROFFSET] [numeric](32, 16) NOT NULL,
[NUMERATOR] [int] NOT NULL,
[OUTEROFFSET] [numeric](32, 16) NOT NULL,
[PRODUCT] [bigint] NOT NULL,
[ROUNDING] [int] NOT NULL,
[TOUNITOFMEASURE] [bigint] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_-1947979309_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_-1947979309_625545217] UNIQUE NONCLUSTERED 
(
[PRODUCT] ASC,
[FROMUNITOFMEASURE] ASC,
[TOUNITOFMEASURE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_DENOMINATOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_DENOMINATOR]  DEFAULT ((0)) FOR [DENOMINATOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_FACTOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_FACTOR]  DEFAULT ((0)) FOR [FACTOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_FROMUNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_FROMUNITOFMEASURE]  DEFAULT ((0)) FOR [FROMUNITOFMEASURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_INNEROFFSET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_INNEROFFSET]  DEFAULT ((0)) FOR [INNEROFFSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_NUMERATOR]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_NUMERATOR]  DEFAULT ((0)) FOR [NUMERATOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_OUTEROFFSET]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_OUTEROFFSET]  DEFAULT ((0)) FOR [OUTEROFFSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_PRODUCT]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_PRODUCT]  DEFAULT ((0)) FOR [PRODUCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_ROUNDING]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_ROUNDING]  DEFAULT ((0)) FOR [ROUNDING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_TOUNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_TOUNITOFMEASURE]  DEFAULT ((0)) FOR [TOUNITOFMEASURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURECONVERSION_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURECONVERSION] ADD  CONSTRAINT [DF_UNITOFMEASURECONVERSION_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[UNITOFMEASURECONVERSION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ax].[UNITOFMEASURETRANSLATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [ax].[UNITOFMEASURETRANSLATION](
[RECID] [bigint] NOT NULL,
[DESCRIPTION] [nvarchar](60) NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
[UNITOFMEASURE] [bigint] NOT NULL,
[MODIFIEDDATETIME] [datetime] NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [I_157860626_RECID] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [I_157860626_-1242300900] UNIQUE NONCLUSTERED 
(
[UNITOFMEASURE] ASC,
[LANGUAGEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURETRANSLATION_DESCRIPTION]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURETRANSLATION] ADD  CONSTRAINT [DF_UNITOFMEASURETRANSLATION_DESCRIPTION]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURETRANSLATION_LANGUAGEID]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURETRANSLATION] ADD  CONSTRAINT [DF_UNITOFMEASURETRANSLATION_LANGUAGEID]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURETRANSLATION_UNITOFMEASURE]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURETRANSLATION] ADD  CONSTRAINT [DF_UNITOFMEASURETRANSLATION_UNITOFMEASURE]  DEFAULT ((0)) FOR [UNITOFMEASURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[ax].[DF_UNITOFMEASURETRANSLATION_MODIFIEDDATETIME]') AND type = 'D')
BEGIN
ALTER TABLE [ax].[UNITOFMEASURETRANSLATION] ADD  CONSTRAINT [DF_UNITOFMEASURETRANSLATION_MODIFIEDDATETIME]  DEFAULT (getutcdate()) FOR [MODIFIEDDATETIME]
END

GO
GRANT DELETE, INSERT, SELECT, UPDATE ON [ax].[UNITOFMEASURETRANSLATION] TO [DataSyncUsersRole]
GO
-------------------------------------------------------------------------------

-- Creating tvp [crt].[AFFILIATIONLOYALTYTIERTABLETYPE]
PRINT N'Creating tvp [crt].[AFFILIATIONLOYALTYTIERTABLETYPE]';

GO
IF TYPE_ID('[crt].[AFFILIATIONLOYALTYTIERTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[AFFILIATIONLOYALTYTIERTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].AFFILIATIONLOYALTYTIERTABLETYPE AS TABLE
(
    [AFFILIATIONID] [bigint] NOT NULL,
    [LOYALTYTIERID] [bigint] NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[AFFILIATIONLOYALTYTIERTABLETYPE]'
GO
-- End creating tvp [crt].[AFFILIATIONLOYALTYTIERTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[AFFILIATIONLOYALTYTIERTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[AFFILIATIONLOYALTYTIERTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].ADDRESSBOOKPARTYTABLETYPE
PRINT N'Creating tvp [crt].ADDRESSBOOKPARTYTABLETYPE';

GO
IF TYPE_ID('[crt].ADDRESSBOOKPARTYTABLETYPE') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].ADDRESSBOOKPARTYTABLETYPE already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].ADDRESSBOOKPARTYTABLETYPE AS TABLE
(
    RECORDID         BIGINT NOT NULL,
    STOREADDRESSBOOK BIGINT NOT NULL,
PARTY     BIGINT NOT NULL,
    
    PRIMARY KEY CLUSTERED 
    (
        RECORDID ASC
    ) 
)


END
GO
PRINT N'Finished creating tvp [crt].ADDRESSBOOKPARTYTABLETYPE'
GO
-- End creating tvp [crt].ADDRESSBOOKPARTYTABLETYPE


GRANT EXECUTE ON TYPE::[crt].ADDRESSBOOKPARTYTABLETYPE TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].ADDRESSBOOKPARTYTABLETYPE TO [PublishersRole];
GO

-- Creating tvp [crt].[CUSTOMERADDRESSTABLETYPE]
PRINT N'Creating tvp [crt].[CUSTOMERADDRESSTABLETYPE]';

GO
IF TYPE_ID('[crt].[CUSTOMERADDRESSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[CUSTOMERADDRESSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[CUSTOMERADDRESSTABLETYPE] AS TABLE
(
     RECORDID                           BIGINT NOT NULL
    ,ADDRESSTYPE                        INT NOT NULL
    ,NAME                               NVARCHAR(60)
    ,FULLADDRESS                        NVARCHAR(250)  
    ,STREETNUMBER                       NVARCHAR(20)
    ,STREET                             NVARCHAR(250)
    ,POSTBOX                            NVARCHAR(20)
    ,BUILDINGCOMPLIMENT                 NVARCHAR(60)
    ,CITY                               NVARCHAR(60)
    ,COUNTY                             NVARCHAR(10)
    ,DISTRICTNAME                       NVARCHAR(60)
    ,[STATE]                            NVARCHAR(10)
    ,ZIPCODE                            NVARCHAR(10)
    ,THREELETTERISOREGIONNAME           NVARCHAR(10)
    ,ISPRIMARY                          INT NOT NULL
    ,ISPRIVATE                          INT NOT NULL
    ,DIRPARTYRECORDID                   BIGINT NOT NULL
    ,DIRPARTYLOCATIONRECORDID           BIGINT NOT NULL
    ,DIRPARTYLOCATIONROLERECORDID       BIGINT NOT NULL
    ,LOCATIONDESCRIPTION                NVARCHAR(60) NOT NULL
    ,LOCATOR                            NVARCHAR(255)
    ,LOGISTICSLOCATIONID                NVARCHAR(30)
    ,LOGISTICSLOCATIONRECORDID          BIGINT NOT NULL
    ,TAXGROUP                           NVARCHAR(10) NOT NULL
    ,DEACTIVATE                         BIT NOT NULL
    ,SORTORDER                          INT NOT NULL
    ,EXPIRERECORDID                     BIGINT
    ,LOGISTICSLOCATIONROLERECORDID      BIGINT NOT NULL
    ,LOGISTICSLOCATIONEXTRECORDID       BIGINT NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[CUSTOMERADDRESSTABLETYPE]'
GO
-- End creating tvp [crt].[CUSTOMERADDRESSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[CUSTOMERADDRESSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[CUSTOMERELECTRONICADDRESSTABLETYPE]
PRINT N'Creating tvp [crt].[CUSTOMERELECTRONICADDRESSTABLETYPE]';

GO
IF TYPE_ID('[crt].[CUSTOMERELECTRONICADDRESSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[CUSTOMERELECTRONICADDRESSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[CUSTOMERELECTRONICADDRESSTABLETYPE] AS TABLE
(
     METHODYTPE                     INT NOT NULL
    ,RECORDID                       BIGINT NOT NULL
    ,DIRPARTYLOCATIONRECORDID       BIGINT NOT NULL
    ,DIRPARTYRECORDID               BIGINT NOT NULL
    ,LOCATIONDESCRIPTION            NVARCHAR(60) NOT NULL
    ,LOCATOR                        NVARCHAR(255)
    ,LOCATOREXTENSION               NVARCHAR(10)
    ,LOGISTICSLOCATIONID            NVARCHAR(30) NOT NULL
    ,LOGISTICSLOCATIONRECORDID      BIGINT NOT NULL
    ,PARENTLOCATION                 BIGINT NOT NULL
    ,ISPRIMARYINT NOT NULL
    ,ISMOBILEPHONE                  INT NOT NULL
    ,ISPRIVATE                INT NOT NULL
    ,DIRPARTYLOCATIONROLERECORDID   BIGINT NOT NULL
    ,LOGISTICSLOCATIONROLERECORDID  BIGINT NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[CUSTOMERELECTRONICADDRESSTABLETYPE]'
GO
-- End creating tvp [crt].[CUSTOMERELECTRONICADDRESSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[CUSTOMERELECTRONICADDRESSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE]
PRINT N'Creating tvp [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[CUSTOMERORDERTRANSACTIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE] AS TABLE
(
STOREnvarchar(10)NOT NULL,
TERMINALnvarchar(10)NOT NULL,
TRANSACTIONIDnvarchar(44)NOT NULL,
DATAAREAIDnvarchar(4)NOT NULL,
CANCELLATIONCHARGEnumeric(32,16)NULL,
DEPOSITOVERRIDEnumeric(32,16)NULL,
REQUIREDDEPOSITnumeric(32,16)NOT NULL,
CALCULATEDDEPOSITnumeric(32,16)NOT NULL,
PREPAYMENTPAIDnumeric(32,16)NOT NULL,
PREPAYMENTINVOICEDnumeric(32,16)NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE]'
GO
-- End creating tvp [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[CUSTOMERORDERTRANSACTIONTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[CUSTOMERTABLETYPE]
PRINT N'Creating tvp [crt].[CUSTOMERTABLETYPE]';

GO
IF TYPE_ID('[crt].[CUSTOMERTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[CUSTOMERTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[CUSTOMERTABLETYPE] AS TABLE
(
     ACCOUNTNUMBER                          NVARCHAR(20) NOT NULL
    ,BLOCKED                                INT NOT NULL
    ,CREDITLIMIT                            NUMERIC(32, 16)
    ,CURRENCY                               NVARCHAR(3) NOT NULL
    ,CUSTGROUP                              NVARCHAR(10) NOT NULL
    ,DIRPARTYRECORDID                       BIGINT NOT NULL
    ,INVOICEACCOUNT                         NVARCHAR(20) NOT NULL
    ,LINEDISCOUNTGROUP                      NVARCHAR(10) NOT NULL
    ,MULTILINEDISCOUNTGROUP                 NVARCHAR(10) NOT NULL
    ,NAME                                   NVARCHAR(100) NOT NULL
    ,PERSONNAMEID                           BIGINT NULL
    ,FIRSTNAME                              NVARCHAR(25) NULL
    ,MIDDLENAME                             NVARCHAR(25) NULL
    ,LASTNAME                               NVARCHAR(25) NULL
    ,ORGID                                  NVARCHAR(10) NOT NULL
    ,PARTYNUMBER                            NVARCHAR(40) NOT NULL
    ,PRICEGROUP                             NVARCHAR(10) NOT NULL
    ,RECORDID                               BIGINT NOT NULL
    ,RETAILCUSTTABLERECORDID                BIGINT NOT NULL
    ,TAXGROUP                               NVARCHAR(10) NOT NULL
    ,TOTALDISCOUNTGROUP                     NVARCHAR(10) NOT NULL
    ,VATNUM                                 NVARCHAR(20) NOT NULL
    ,LANGUAGEID                             NVARCHAR(7)
    ,INSTANCERELATIONTYPE                   BIGINT NOT NULL
    ,RECEIPTEMAIL                           NVARCHAR(80)
    ,RECEIPTOPTION                          INT
)


END
GO
PRINT N'Finished creating tvp [crt].[CUSTOMERTABLETYPE]'
GO
-- End creating tvp [crt].[CUSTOMERTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[CUSTOMERTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].EXTENSIONPROPERTIESTABLETYPE
PRINT N'Creating tvp [crt].EXTENSIONPROPERTIESTABLETYPE';

GO
IF TYPE_ID('[crt].EXTENSIONPROPERTIESTABLETYPE') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].EXTENSIONPROPERTIESTABLETYPE already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].EXTENSIONPROPERTIESTABLETYPE AS TABLE
(
    PARENTRECID BIGINT NOT NULL,
    PROPERTYNAME NVARCHAR(256) NOT NULL,
PROPERTYVALUE NVARCHAR(256)
)


END
GO
PRINT N'Finished creating tvp [crt].EXTENSIONPROPERTIESTABLETYPE'
GO
-- End creating tvp [crt].EXTENSIONPROPERTIESTABLETYPE


GRANT EXECUTE ON TYPE::[crt].EXTENSIONPROPERTIESTABLETYPE TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].EXTENSIONPROPERTIESTABLETYPE TO [PublishersRole];
GO

-- Creating tvp [crt].[SALESTRANSACTIONTABLETYPE]
PRINT N'Creating tvp [crt].[SALESTRANSACTIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[SALESTRANSACTIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[SALESTRANSACTIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[SALESTRANSACTIONTABLETYPE] AS TABLE
(
     TRANSACTIONID              NVARCHAR(44)        NOT NULL
    ,TERMINALID                 NVARCHAR(10)        NOT NULL
,CUSTOMERID                 NVARCHAR(20)        NULL
    ,NAME                       NVARCHAR(128)       NULL
    ,BYTELENGTH                 INT                 NULL
    ,TRANSACTIONDATA            VARBINARY(MAX)      NULL
    ,ROWVERSION                 BINARY(8)           NULL
    ,ISSUSPENDED                BIT                 NOT NULL
,TYPEINTNOT NULL
,COMMENT                    NVARCHAR(60)        NULL
,CHANNELIDBIGINTNOT NULL
    ,STAFFNVARCHAR(25)NOT NULL
,AMOUNTNUMERIC(32, 16)NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[SALESTRANSACTIONTABLETYPE]'
GO
-- End creating tvp [crt].[SALESTRANSACTIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[SALESTRANSACTIONTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[ITEMVARIANTINVENTDIMTABLETYPE]
PRINT N'Creating tvp [crt].[ITEMVARIANTINVENTDIMTABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMVARIANTINVENTDIMTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMVARIANTINVENTDIMTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

-- Item ID and variant inventory dimension ID.
CREATE TYPE [crt].ITEMVARIANTINVENTDIMTABLETYPE AS TABLE 
(
    ITEMID nvarchar(20) NOT NULL,
    VARIANTINVENTDIMID nvarchar(20) NOT NULL,
    
    PRIMARY KEY(ITEMID, VARIANTINVENTDIMID)
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMVARIANTINVENTDIMTABLETYPE]'
GO
-- End creating tvp [crt].[ITEMVARIANTINVENTDIMTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMVARIANTINVENTDIMTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[ITEMVARIANTINVENTDIMTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[ITEMRESERVATIONTABLETYPE]
PRINT N'Creating tvp [crt].[ITEMRESERVATIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMRESERVATIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMRESERVATIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].ITEMRESERVATIONTABLETYPE AS TABLE 
(
    RESERVATIONID uniqueidentifier NOT NULL,
    ITEMID nvarchar(20) NOT NULL,
    INVENTDIMID nvarchar(20) NOT NULL,
    QUANTITY numeric(32, 16) NOT NULL,
    EXPIREDATETIME datetime NOT NULL,
    
    PRIMARY KEY(RESERVATIONID)
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMRESERVATIONTABLETYPE]'
GO
-- End creating tvp [crt].[ITEMRESERVATIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMRESERVATIONTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[ITEMRESERVATIONIDTABLETYPE]
PRINT N'Creating tvp [crt].[ITEMRESERVATIONIDTABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMRESERVATIONIDTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMRESERVATIONIDTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].ITEMRESERVATIONIDTABLETYPE AS TABLE 
(
    RESERVATIONID uniqueidentifier NOT NULL,
    
    PRIMARY KEY(RESERVATIONID)
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMRESERVATIONIDTABLETYPE]'
GO
-- End creating tvp [crt].[ITEMRESERVATIONIDTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMRESERVATIONIDTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[ITEMUNITCONVERSIONTABLETYPE]
PRINT N'Creating tvp [crt].[ITEMUNITCONVERSIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMUNITCONVERSIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMUNITCONVERSIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

-- Item unit of measure conversion.
CREATE TYPE [crt].ITEMUNITCONVERSIONTABLETYPE AS TABLE 
(
    ITEMID nvarchar(20) NOT NULL,
    FROMUNITID nvarchar(10) NOT NULL,
    TOUNITID nvarchar(10) NOT NULL,
    
    PRIMARY KEY(ITEMID, FROMUNITID, TOUNITID)
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMUNITCONVERSIONTABLETYPE]'
GO
-- End creating tvp [crt].[ITEMUNITCONVERSIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMUNITCONVERSIONTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[ITEMQUANTITYTABLETYPE]
PRINT N'Creating tvp [crt].[ITEMQUANTITYTABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMQUANTITYTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMQUANTITYTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

-- Item ID and quantity.
CREATE TYPE [crt].ITEMQUANTITYTABLETYPE AS TABLE 
(
    ITEMID nvarchar(20) NOT NULL,
    VARIANTINVENTDIMID nvarchar(20) NOT NULL,
    QUANTITY decimal NOT NULL,    
    
    PRIMARY KEY(ITEMID, VARIANTINVENTDIMID, QUANTITY)
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMQUANTITYTABLETYPE]'
GO
-- End creating tvp [crt].[ITEMQUANTITYTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMQUANTITYTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[ITEMWAREHOUSETABLETYPE]
PRINT N'Creating tvp [crt].[ITEMWAREHOUSETABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMWAREHOUSETABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMWAREHOUSETABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

-- ITEM ID, VARIANT INVENTORY DIMENSION ID, AND WAREHOUSE ID.
CREATE TYPE [crt].ITEMWAREHOUSETABLETYPE AS TABLE 
(
    ITEMID NVARCHAR(20) NOT NULL,
    VARIANTINVENTDIMID NVARCHAR(20) NOT NULL,
    INVENTLOCATIONID NVARCHAR(10) NOT NULL,
    
    PRIMARY KEY(ITEMID, VARIANTINVENTDIMID, INVENTLOCATIONID)
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMWAREHOUSETABLETYPE]'
GO
-- End creating tvp [crt].[ITEMWAREHOUSETABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMWAREHOUSETABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RECORDIDTABLETYPE]
PRINT N'Creating tvp [crt].[RECORDIDTABLETYPE]';

GO
IF TYPE_ID('[crt].[RECORDIDTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RECORDIDTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].RECORDIDTABLETYPE AS TABLE
(
    RECID BIGINT,
    PRIMARY KEY(RECID)
)


END
GO
PRINT N'Finished creating tvp [crt].[RECORDIDTABLETYPE]'
GO
-- End creating tvp [crt].[RECORDIDTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RECORDIDTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[RECORDIDTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[RECORDIDLANGUAGETABLETYPE]
PRINT N'Creating tvp [crt].[RECORDIDLANGUAGETABLETYPE]';

GO
IF TYPE_ID('[crt].[RECORDIDLANGUAGETABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RECORDIDLANGUAGETABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].RECORDIDLANGUAGETABLETYPE AS TABLE
(
    RECID BIGINT NOT NULL,
LANGUAGEID NVARCHAR(7) NOT NULL
    PRIMARY KEY(RECID, LANGUAGEID)
)


END
GO
PRINT N'Finished creating tvp [crt].[RECORDIDLANGUAGETABLETYPE]'
GO
-- End creating tvp [crt].[RECORDIDLANGUAGETABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RECORDIDLANGUAGETABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[RECORDIDLANGUAGETABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[LANGUAGEIDTABLETYPE]
PRINT N'Creating tvp [crt].[LANGUAGEIDTABLETYPE]';

GO
IF TYPE_ID('[crt].[LANGUAGEIDTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[LANGUAGEIDTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].LANGUAGEIDTABLETYPE AS TABLE
(
LANGUAGEID NVARCHAR(7) NOT NULL
    PRIMARY KEY(LANGUAGEID)
)


END
GO
PRINT N'Finished creating tvp [crt].[LANGUAGEIDTABLETYPE]'
GO
-- End creating tvp [crt].[LANGUAGEIDTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[LANGUAGEIDTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[LANGUAGEIDTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[STRINGIDTABLETYPE]
PRINT N'Creating tvp [crt].[STRINGIDTABLETYPE]';

GO
IF TYPE_ID('[crt].[STRINGIDTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[STRINGIDTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].STRINGIDTABLETYPE AS TABLE
(
    STRINGID NVARCHAR(88),
    PRIMARY KEY(STRINGID)
)


END
GO
PRINT N'Finished creating tvp [crt].[STRINGIDTABLETYPE]'
GO
-- End creating tvp [crt].[STRINGIDTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[STRINGIDTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[STRINGIDTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[RECORDIDSTABLETYPE]
PRINT N'Creating tvp [crt].[RECORDIDSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RECORDIDSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RECORDIDSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].RECORDIDSTABLETYPE AS TABLE
(
    RECID       BIGINT,
    PARENTRECID BIGINT,
    PRIMARY KEY (RECID)
)


END
GO
PRINT N'Finished creating tvp [crt].[RECORDIDSTABLETYPE]'
GO
-- End creating tvp [crt].[RECORDIDSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RECORDIDSTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[RECORDIDSTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[PRODUCTLOOKUPIDTABLETYPE]
PRINT N'Creating tvp [crt].[PRODUCTLOOKUPIDTABLETYPE]';

GO
IF TYPE_ID('[crt].[PRODUCTLOOKUPIDTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[PRODUCTLOOKUPIDTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].PRODUCTLOOKUPIDTABLETYPE AS TABLE
(
    PRODUCTID   BIGINT  NOT NULL,
    LOOKUPID    BIGINT  NOT NULL,
    ISREMOTE    BIT     NOT NULL,
    VALIDFROM   DATE    NOT NULL,
    VALIDTO     DATE    NOT NULL,
    PRIMARY KEY(PRODUCTID, VALIDFROM, VALIDTO)
)


END
GO
PRINT N'Finished creating tvp [crt].[PRODUCTLOOKUPIDTABLETYPE]'
GO
-- End creating tvp [crt].[PRODUCTLOOKUPIDTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[PRODUCTLOOKUPIDTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[PRODUCTLOOKUPIDTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[RETAILPRODUCTPRICINGINFOTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILPRODUCTPRICINGINFOTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILPRODUCTPRICINGINFOTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILPRODUCTPRICINGINFOTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
 
CREATE TYPE [crt].[RETAILPRODUCTPRICINGINFOTABLETYPE] AS TABLE
(
    [PRODUCTRECID] [bigint] NOT NULL,
    [PRODUCTLOOKUPID] [bigint] NOT NULL,
    [BASEPRICE] [numeric](32, 16) DEFAULT ((0)) NOT NULL,
    [TRADEAGREEMENTPRICE] [numeric](32, 16) DEFAULT ((0)) NOT NULL,
    [PRICEADJUSTMENTPRICE] [numeric](32, 16) DEFAULT ((0)) NOT NULL,
    [CURRENCY] [nvarchar](3) DEFAULT ('') NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [INVENTDIMID] [nvarchar](20) DEFAULT ('') NOT NULL,
    [UNITID] [nvarchar](10) DEFAULT ('') NOT NULL,
    [VALIDFROM] [datetime] NOT NULL,
[CHANNEL] [bigint] DEFAULT ((0)) NOT NULL,
[CATALOG] [bigint] DEFAULT ((0)) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILPRODUCTPRICINGINFOTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILPRODUCTPRICINGINFOTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILPRODUCTPRICINGINFOTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[RETAILPRODUCTPRICINGINFOTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE] AS TABLE
(
    [SALESID] [nvarchar](40) NOT NULL,
    [PACKINGSLIPID] [nvarchar](40) NOT NULL,
    [PUBLISHSTATUS] [int] NOT NULL,
    [PUBLISHMESSAGE] [nvarchar](2048) NOT NULL,
    [CHANNELBATCHID] [nvarchar](128) NOT NULL,
    [CHANNELREFID] [nvarchar](128) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE] AS TABLE
(
    [DATAAREAID] NVARCHAR(4) NULL,
    [STORE] [nvarchar](10) NULL,
    [TERMINAL] [nvarchar](10) NULL,
    [TRANSACTIONID] [nvarchar](44) NULL,
    [TEXTVALUE] [nvarchar](1999) NULL,
    [NAME] [nvarchar](60) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE] AS TABLE
(
    [TRANSACTIONID] [NVARCHAR](44) NOT NULL,
    [LINENUM] [NUMERIC](32, 16) NOT NULL,
    [DATAAREAID] NVARCHAR(4) NULL,
    [TYPE] [INT] NOT NULL,
    [INFOCODEID] [NVARCHAR](10) NOT NULL,
    [INFORMATION] [NVARCHAR](100) NOT NULL,
    [INFOAMOUNT] [NUMERIC](32, 16) NOT NULL,
    [TRANSDATE] [DATETIME] NOT NULL,
    [TRANSTIME] [INT] NOT NULL,
    [STORE] [NVARCHAR](10) NOT NULL,
    [TERMINAL] [NVARCHAR](10) NOT NULL,
    [STAFF] [NVARCHAR](25) NOT NULL,
    [ITEMTENDER] [NVARCHAR](10) NOT NULL,
    [AMOUNT] [NUMERIC](32, 16) NOT NULL,
    [INPUTTYPE] [INT] NOT NULL,
    [SUBINFOCODEID] [NVARCHAR](10) NOT NULL,
    [STATEMENTCODE] [NVARCHAR](25) NOT NULL,
    [SOURCECODE] [NVARCHAR](20) NOT NULL,
    [TRANSACTIONSTATUS] [INT] NOT NULL,
    [SOURCECODE2] [NVARCHAR](20) NOT NULL,
    [SOURCECODE3] [NVARCHAR](20) NOT NULL,
    [PARENTLINENUM] [NUMERIC](32, 16) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE] AS TABLE
(
    [CURRENCYCODE] NVARCHAR(3) NULL,
    [DATAAREAID] NVARCHAR(4) NULL,
    [MARKUPCODE] NVARCHAR(10) NULL,
    [MARKUPLINENUM] NUMERIC(32, 16) NULL,
    [SALELINENUM] NUMERIC(32, 16) NULL,
    [STORE] NVARCHAR(10) NULL,
    [TAXGROUP] NVARCHAR(10) NULL,
    [TAXITEMGROUP] NVARCHAR(10) NULL,
    [TERMINALID] NVARCHAR(10) NULL,
    [TRANSACTIONID] NVARCHAR(44) NULL,
    [VALUE] NUMERIC(32, 16) NULL,
    [CALCULATEDAMOUNT] NUMERIC(32, 16) NULL,
    [METHOD] INT NULL,
[TAXAMOUNT] NUMERIC(32, 16) NULL,
[TAXAMOUNTINCLUSIVE] NUMERIC(32, 16) NULL,
[TAXAMOUNTEXCLUSIVE] NUMERIC(32, 16) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE] AS TABLE
(
[AMOUNTCUR] NUMERIC(32, 16) NULL,
[CURRENCY] NVARCHAR(3) NULL,
[EXCHRATE] NUMERIC(32, 16) NULL,
[AMOUNTTENDERED] NUMERIC(32, 16) NULL,
[EXCHRATEMST] NUMERIC(32, 16) NULL,
[AMOUNTMST] NUMERIC(32, 16) NULL,
[DATAAREAID] NVARCHAR(4) NULL,
[LINENUM] NUMERIC(32, 16) NULL,
[PAYMENTAUTHORIZATION] NVARCHAR(MAX) NOT NULL,
[STORE] NVARCHAR(10) NULL,
[TENDERTYPE] NVARCHAR(10) NULL,
[CHANGELINE] INT NULL,
[TERMINAL] NVARCHAR(10) NULL,
[STAFF] NVARCHAR(25) NULL,
[TRANSACTIONID] NVARCHAR(44) NULL,
[SIGCAPDATA] NVARCHAR(max) NULL,
[TRANSACTIONSTATUS] INT NULL,
[RECEIPTID] NVARCHAR(18) NULL,
[GIFTCARDID] NVARCHAR(30) NOT NULL,
[LOYALTYCARDID] NVARCHAR(30) NOT NULL,
[CARDORACCOUNT] NVARCHAR(30) NOT NULL,
[CARDTYPEID] NVARCHAR(10) NOT NULL,
[CREDITVOUCHERID] NVARCHAR(30) NOT NULL,
[TRANSDATE] DATETIME NULL,
[TRANSTIME] INT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE] AS TABLE
(
    [CUSTACCOUNT] NVARCHAR(20) NULL,
    [CREATEDDATETIME] DATETIME NULL,
    [DATAAREAID] NVARCHAR(4) NULL,
    [LINEMANUALDISCOUNTAMOUNT] NUMERIC(32, 16) NULL,
    [LINEMANUALDISCOUNTPERCENTAGE] NUMERIC(32, 16) NULL,
    [DISCAMOUNT] NUMERIC(32, 16) NULL,
    [TOTALDISCAMOUNT] NUMERIC(32, 16) NULL,
    [TOTALDISCPCT] NUMERIC(32, 16) NULL,
    [LINEDSCAMOUNT] NUMERIC(32, 16) NULL,
    [PERIODICDISCAMOUNT] NUMERIC(32, 16) NULL,
    [PERIODICPERCENTAGEDISCOUNT] NUMERIC (32,16) NULL,
    [DLVMODE] NVARCHAR(10) NULL,
    [INVENTDIMID] NVARCHAR(20) NULL,
    [INVENTLOCATIONID] NVARCHAR(10) NULL,
    [INVENTSERIALID] NVARCHAR(20) NULL,
    [INVENTSITEID] NVARCHAR(10) NULL,
    [ITEMID] NVARCHAR(20) NULL,
[BARCODE] NVARCHAR(80) NULL,
    [LINENUM] NUMERIC(32, 16) NULL,
    [LISTINGID] NVARCHAR(50) NULL,
    [LOGISTICSPOSTALADDRESS] BIGINT NULL,
    [NETAMOUNT] NUMERIC(32, 16) NULL,
    [NETAMOUNTINCLTAX] NUMERIC(32, 16) NULL,
    [PRICE] NUMERIC(32, 16) NULL,
    [QTY] NUMERIC(32, 16) NULL,
    [RECEIPTDATEREQUESTED] DATETIME NULL,
    [SHIPPINGDATEREQUESTED] DATETIME NULL,
    [STORE] NVARCHAR(10) NULL,
    [TAXAMOUNT] NUMERIC(32, 16) NULL,
    [TAXGROUP] NVARCHAR(10) NULL,
    [TAXITEMGROUP] NVARCHAR(10) NULL,
    [TERMINALID] NVARCHAR(10) NULL,
    [STAFFID] NVARCHAR(25) NULL,
    [TRANSACTIONID] NVARCHAR(44) NULL,
    [UNIT] NVARCHAR(10) NULL,
    [VARIANTID] NVARCHAR(10) NULL,
    [RETURNNOSALE] INT NULL,
    [RETURNTRANSACTIONID] NVARCHAR(44) NULL,
    [RETURNLINENUM] NUMERIC(32, 16) NULL,
    [RETURNSTORE] NVARCHAR(10) NULL,
    [RETURNTERMINALID] NVARCHAR(10) NULL,
    [RECEIPTID] NVARCHAR(18) NULL,
    [TRANSDATE] DATETIME NULL,
    [TRANSTIME] INT NULL,
    [TRANSACTIONSTATUS] INT NULL,
    [COMMENT] NVARCHAR(60) NULL,
    [GIFTCARD] INT NOT NULL,
    [CATALOG] BIGINT NOT NULL,
    [ELECTRONICDELIVERYEMAIL]  NVARCHAR(40) NULL,
    [ELECTRONICDELIVERYEMAILCONTENT] NVARCHAR(250) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONTABLETYPE] AS TABLE
(
    [CHANNELREFERENCEID] NVARCHAR(50) NULL,
    [CREATEDDATETIME] DATETIME NULL,
    [TRANSDATE] DATETIME NULL,  -- Used in AX form for filtering transactions.
    [TRANSTIME] INT NULL,       -- Used in AX form for filtering transactions.
    [CURRENCY] NVARCHAR(3) NULL,
    [EXCHRATE] NUMERIC(32, 16) NULL,
    [ENTRYSTATUS] INT NULL,
    [CUSTOMERID] NVARCHAR(20) NULL,
    [DATAAREAID] NVARCHAR(4) NULL,
    [DELIVERYMODE] NVARCHAR(10) NULL,
    [GROSSAMOUNT] NUMERIC(32, 16) NULL,
    [INVENTLOCATIONID] NVARCHAR(10) NULL,
    [INVENTSITEID] NVARCHAR(10) NULL,
    [INCOMEEXPENSEAMOUNT] NUMERIC(32, 16) NULL,
    [LOGISTICSPOSTALADDRESS] BIGINT NULL,
    [NETAMOUNT] NUMERIC(32, 16) NULL,
    [PAYMENTAMOUNT] NUMERIC(32, 16) NULL,
    [RECEIPTDATEREQUESTED] DATETIME NULL,
    [SHIPPINGDATEREQUESTED] DATETIME NULL,
    [STORE] NVARCHAR(10) NULL,
    [TERMINAL] NVARCHAR(10) NULL,
    [STAFF] NVARCHAR(25) NULL,
    [TRANSACTIONID] NVARCHAR(44) NULL,
    [SALESORDERID] NVARCHAR(20) NULL,
    [TYPE] INT NULL,
    [LOYALTYCARDID] NVARCHAR(30) NULL,
    [RECEIPTEMAIL] NVARCHAR(80) NULL,
    [RECEIPTID] NVARCHAR(18) NULL,
    [NUMBEROFITEMS] NUMERIC(32, 16) NULL,
    [NUMBEROFITEMLINES] NUMERIC(32, 16) NULL,
    [NUMBEROFPAYMENTLINES] INT NULL,
    [TIMEWHENTRANSCLOSED] INT NULL,
    [SALEISRETURNSALE] INT NULL,
    [DISCAMOUNT] NUMERIC(32, 16) NULL,
    [TOTALDISCAMOUNT] NUMERIC(32, 16) NULL,
    [CUSTDISCAMOUNT] NUMERIC(32, 16) NULL,
    [TOTALMANUALDISCOUNTAMOUNT] NUMERIC(32, 16) NULL,
    [TOTALMANUALDISCOUNTPERCENTAGE] NUMERIC(32, 16) NULL,
    [BATCHID] BIGINT NULL,
    [BATCHTERMINALID] NVARCHAR(10) NULL,
    [COMMENT] NVARCHAR(60) NULL,
[DESCRIPTION] NVARCHAR(150) NULL,
[BUSINESSDATE] DATE NULL,
[STATEMENTCODE] NVARCHAR(25) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE] AS TABLE
(
    [AMOUNT] NUMERIC(32, 16) NULL,
    [DATAAREAID] NVARCHAR(4) NULL,
    [ISINCLUDEDINPRICE] INT NULL,
    [SALELINENUM] NUMERIC(32, 16) NULL,
    [STOREID] NVARCHAR(10) NULL,
    [TAXCODE] NVARCHAR(10) NULL,
    [TERMINALID] NVARCHAR(10) NULL,
    [TRANSACTIONID] NVARCHAR(44) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE] AS TABLE
(
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [TRANSACTIONID] [nvarchar](44) NOT NULL,
    [SALELINENUM] [numeric](32, 16) NOT NULL,
    [NAME] [nvarchar](128) NOT NULL,  -- Reduced to 128 to fit in PK index
    [VALUE] [nvarchar](2000) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILINCOMEEXPENSETABLETYPE]
PRINT N'Creating tvp [crt].[RETAILINCOMEEXPENSETABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILINCOMEEXPENSETABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILINCOMEEXPENSETABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILINCOMEEXPENSETABLETYPE] AS TABLE
(
[TRANSACTIONID] [NVARCHAR](44) NOT NULL,
[RECEIPTID] [NVARCHAR](18) NOT NULL,
[INCOMEEXEPENSEACCOUNT] [NVARCHAR](10) NOT NULL,
[STORE] [NVARCHAR](10) NOT NULL,
[TERMINAL] [NVARCHAR](10) NOT NULL,
[STAFF] [NVARCHAR](25) NOT NULL,
[TRANSACTIONSTATUS] [INT] NOT NULL,
[AMOUNT] [NUMERIC] NOT NULL,
[ACCOUNTTYPE] [INT] NOT NULL,
[TRANSDATE] [DATE] NULL,
[TRANSTIME] [INT] NULL,
[DATAAREAID] [NVARCHAR](4) NOT NULL,
[CHANNEL] [BIGINT] NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILINCOMEEXPENSETABLETYPE]'
GO
-- End creating tvp [crt].[RETAILINCOMEEXPENSETABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILINCOMEEXPENSETABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[SHIFTTENDERAMOUNTTYPE]
PRINT N'Creating tvp [crt].[SHIFTTENDERAMOUNTTYPE]';

GO
IF TYPE_ID('[crt].[SHIFTTENDERAMOUNTTYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[SHIFTTENDERAMOUNTTYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].[SHIFTTENDERAMOUNTTYPE] AS TABLE(
    [TENDERTYPEID] [nvarchar] (20) NULL,
    [TENDERTYPENAME] [nvarchar] (120) NULL,
    [CURRENCY] [nvarchar] (6) NULL,
[COUNTINGREQUIRED] [int] NULL,
    [TENDEREDAMOUNT] [numeric] (32, 16) NULL,
    [TENDEREDAMOUNTCUR] [numeric] (32, 16) NULL,
    [TRANSACTIONTYPE] [int] NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[SHIFTTENDERAMOUNTTYPE]'
GO
-- End creating tvp [crt].[SHIFTTENDERAMOUNTTYPE]


GRANT EXECUTE ON TYPE::[crt].[SHIFTTENDERAMOUNTTYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[PRICEACCOUNTRELATIONSTABLETYPE]
PRINT N'Creating tvp [crt].[PRICEACCOUNTRELATIONSTABLETYPE]';

GO
IF TYPE_ID('[crt].[PRICEACCOUNTRELATIONSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[PRICEACCOUNTRELATIONSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].[PRICEACCOUNTRELATIONSTABLETYPE] AS TABLE
(
    [ACCOUNTRELATION] [nvarchar](20) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[PRICEACCOUNTRELATIONSTABLETYPE]'
GO
-- End creating tvp [crt].[PRICEACCOUNTRELATIONSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[PRICEACCOUNTRELATIONSTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[PRICEACCOUNTRELATIONSTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[PRICEGROUPTABLETYPE]
PRINT N'Creating tvp [crt].[PRICEGROUPTABLETYPE]';

GO
IF TYPE_ID('[crt].[PRICEGROUPTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[PRICEGROUPTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].PRICEGROUPTABLETYPE AS TABLE
(
    [RECID] [bigint] NOT NULL,
    [PRICEGROUP] [bigint] NOT NULL,
    [GROUPID] [nvarchar](10) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[PRICEGROUPTABLETYPE]'
GO
-- End creating tvp [crt].[PRICEGROUPTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[PRICEGROUPTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[PRICEGROUPTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE] AS TABLE
(
    [DATAAREAID] NVARCHAR(4) NULL,
    [STORE] [nvarchar](10) NULL,
    [TERMINAL] [nvarchar](10) NULL,
    [TRANSACTIONID] [nvarchar](44) NULL,
    [SALELINENUM] [numeric](32, 16) NOT NULL,
    [DELIVERYNAME] [nvarchar](60) NOT NULL,
    [SALESNAME] [nvarchar](60) NOT NULL,
    [ZIPCODE] [nvarchar](10) NOT NULL,
    [COUNTRYREGIONID] [nvarchar](10) NOT NULL,
    [STATE] [nvarchar](10) NOT NULL,
    [CITY] [nvarchar](60) NOT NULL,
    [COUNTY] [nvarchar](10) NOT NULL,
    [STREET] [nvarchar](250) NOT NULL,
    [EMAIL] [nvarchar](80) NOT NULL,
[EMAILCONTENT] [nvarchar](80) NOT NULL,
    [PHONE] [nvarchar](20) NOT NULL,
    [STREETNUMBER] [nvarchar](20) NOT NULL,
    [DISTRICTNAME] [nvarchar](60) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE] AS TABLE
(
    [AMOUNT] NUMERIC(32, 16) NULL,
    [DATAAREAID] NVARCHAR(4) NULL,
    [DEALPRICE] NUMERIC(32, 16) NULL,
    [DISCOUNTAMOUNT] NUMERIC(32, 16) NULL,
    [DISCOUNTCODE] NVARCHAR(15) NULL,
    [LINENUM] NUMERIC(32, 16) NULL,
    [PERCENTAGE] [numeric](32, 16) NULL,
    [PERIODICDISCOUNTOFFERID] NVARCHAR(20) NULL,
[OFFERNAME] NVARCHAR(60) NULL,
    [SALELINENUM] NUMERIC(32, 16) NULL,
    [STOREID] NVARCHAR(10) NULL,
    [TERMINALID] NVARCHAR(10) NULL,
    [TRANSACTIONID] NVARCHAR(44) NULL,
    [DISCOUNTORIGINTYPE] [int] NULL,
    [CUSTOMERDISCOUNTTYPE] [int] NULL,
    [MANUALDISCOUNTTYPE] [int] NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[SALESLINEDELIVERYOPTIONSTABLETYPE]
PRINT N'Creating tvp [crt].[SALESLINEDELIVERYOPTIONSTABLETYPE]';

GO
IF TYPE_ID('[crt].[SALESLINEDELIVERYOPTIONSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[SALESLINEDELIVERYOPTIONSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[SALESLINEDELIVERYOPTIONSTABLETYPE] AS TABLE
(
    [SALESLINEID]           [nvarchar](32)      NOT NULL,
    [ITEMID]                [nvarchar](20)      NOT NULL,
    [VARIANTINVENTDIMID]    [nvarchar](20)      NOT NULL,
    [COUNTRYREGIONID]       [nvarchar](20)      NOT NULL,
    [STATEID]               [nvarchar](20)      NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[SALESLINEDELIVERYOPTIONSTABLETYPE]'
GO
-- End creating tvp [crt].[SALESLINEDELIVERYOPTIONSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[SALESLINEDELIVERYOPTIONSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[SHIFTTABLETYPE]
PRINT N'Creating tvp [crt].[SHIFTTABLETYPE]';

GO
IF TYPE_ID('[crt].[SHIFTTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[SHIFTTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].[SHIFTTABLETYPE] AS TABLE(
    [CASHDRAWER] [nvarchar] (512) NULL,
    [CHANNEL] [bigint] NULL,
    [CLOSEDATE] [date] NULL,
    [CLOSEDATETIMEUTC] [datetime] NULL,
    [CLOSEDATETIMEUTCTZID] [int] NULL,
    [CLOSETIME] [int] NULL,
    [CURRENTTERMINALID] [nvarchar](10) NULL,
    [CUSTOMERSCOUNT] [int] NULL,
    [DISCOUNTTOTAL] [numeric](32, 16) NULL,
    [LOGONSCOUNT] [int] NULL,
    [NOSALECOUNT] [int] NULL,
    [PAIDTOACCOUNTTOTAL] [numeric](32, 16) NULL,
    [POSTED] [int] NULL,
    [RETURNSTOTAL] [numeric](32, 16) NULL,
    [ROUNDEDAMOUNTTOTAL] [numeric](32, 16) NULL,
    [SALESCOUNT] [int] NULL,
    [SALESTOTAL] [numeric](32, 16) NULL,
    [SHIFTID] [bigint] NULL,
    [STAFFID] [nvarchar](25) NULL,
    [CURRENTSTAFFID] [nvarchar](25) NULL,
    [STARTDATE] [date] NULL,
    [STARTDATETIMEUTC] [datetime] NULL,
    [STARTDATETIMEUTCTZID] [int] NULL,
    [STARTTIME] [int] NULL,
    [STATUS] [int] NULL,
    [STATUSDATETIMEUTC] [datetime] NULL,
    [STOREID] [nvarchar](10) NULL,
    [TAXTOTAL] [numeric](32, 16) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [TRANSACTIONSCOUNT] [int] NULL,
    [VOIDSCOUNT] [int] NULL,
    [DATAAREAID] [nvarchar](4) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[SHIFTTABLETYPE]'
GO
-- End creating tvp [crt].[SHIFTTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[SHIFTTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[SHIFTACCOUNTLINETYPE]
PRINT N'Creating tvp [crt].[SHIFTACCOUNTLINETYPE]';

GO
IF TYPE_ID('[crt].[SHIFTACCOUNTLINETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[SHIFTACCOUNTLINETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].[SHIFTACCOUNTLINETYPE] AS TABLE(
    [INCOMEEXEPENSEACCOUNT] [nvarchar] (10) NULL,
    [ACCOUNTTYPE][int] NULL,
    [AMOUNT][numeric] (17) NULL,
[SHIFTID][bigint] NULL,
[STOREID][nvarchar] (10) NULL,
[TERMINALID][nvarchar] (10) NULL,
[CHANNEL][bigint] NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[SHIFTACCOUNTLINETYPE]'
GO
-- End creating tvp [crt].[SHIFTACCOUNTLINETYPE]


GRANT EXECUTE ON TYPE::[crt].[SHIFTACCOUNTLINETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[SHIFTTENDERLINETABLETYPE]
PRINT N'Creating tvp [crt].[SHIFTTENDERLINETABLETYPE]';

GO
IF TYPE_ID('[crt].[SHIFTTENDERLINETABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[SHIFTTENDERLINETABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].[SHIFTTENDERLINETABLETYPE] AS TABLE(
    [ADDTOTENDERAMOUNT] [numeric](32, 16) NULL,
    [ADDTOTENDERAMOUNTCUR] [numeric](32, 16) NULL,
    [BANKDROPAMOUNT] [numeric](32, 16) NULL,
    [BANKDROPAMOUNTCUR] [numeric](32, 16) NULL,
    [CARDTYPEID] [nvarchar](10) NULL,
    [CHANGEAMOUNT] [numeric](32, 16) NULL,
    [CHANGEAMOUNTCUR] [numeric](32, 16) NULL,
    [CHANNEL] [bigint] NULL,
    [COUNT] [int] NULL,
    [COUNTINGREQUIRED] [int] NULL,
    [CURRENCY] [nvarchar](3) NULL,
    [DECLARETENDERAMOUNT] [numeric](32, 16) NULL,
    [DECLARETENDERAMOUNTCUR] [numeric](32, 16) NULL,
    [REMOVETENDERAMOUNT] [numeric](32, 16) NULL,
    [REMOVETENDERAMOUNTCUR] [numeric](32, 16) NULL,
    [SAFEDROPAMOUNT] [numeric](32, 16) NULL,
    [SAFEDROPAMOUNTCUR] [numeric](32, 16) NULL,
    [SHIFTID] [bigint] NULL,
    [STARTINGAMOUNT] [numeric](32, 16) NULL,
    [STARTINGAMOUNTCUR] [numeric](32, 16) NULL,
    [STOREID] [nvarchar](10) NULL,
    [TENDEREDAMOUNT] [numeric](32, 16) NULL,
    [TENDEREDAMOUNTCUR] [numeric](32, 16) NULL,
    [TENDERTYPEID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[SHIFTTENDERLINETABLETYPE]'
GO
-- End creating tvp [crt].[SHIFTTENDERLINETABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[SHIFTTENDERLINETABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[LISTINGPUBLISHSTATUSTABLETYPE]
PRINT N'Creating tvp [crt].[LISTINGPUBLISHSTATUSTABLETYPE]';

GO
IF TYPE_ID('[crt].[LISTINGPUBLISHSTATUSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[LISTINGPUBLISHSTATUSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].LISTINGPUBLISHSTATUSTABLETYPE AS TABLE
(
    [ACTIONSTATUS] [int] NOT NULL,
    [APPLIEDACTION] [int] NOT NULL,
    [CATALOG] [bigint] NOT NULL,
    [CHANNEL] [bigint] NOT NULL,
    [CHANNELLISTINGID] [nvarchar](50) NOT NULL,
    [LISTINGMODIFIEDDATETIME] [datetime] NOT NULL,
    [LISTINGMODIFIEDDATETIMETZID] [int] NOT NULL,
    [PRODUCT] [bigint] NOT NULL,
    [PROCESSED] [int] NOT NULL,
    [STATUSDATETIME] [datetime] NOT NULL,
    [STATUSDATETIMETZID] [int] NOT NULL,
    [STATUSMESSAGE] [nvarchar](2048) NOT NULL,
    [CHANNELBATCHID] [nvarchar](100) NOT NULL,
    [CHANNELSTATE] [nvarchar](4000) NOT NULL,

    PRIMARY KEY NONCLUSTERED
    (
        [STATUSDATETIME] ASC,
        [PRODUCT] ASC
    )
)


END
GO
PRINT N'Finished creating tvp [crt].[LISTINGPUBLISHSTATUSTABLETYPE]'
GO
-- End creating tvp [crt].[LISTINGPUBLISHSTATUSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[LISTINGPUBLISHSTATUSTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[LISTINGPUBLISHSTATUSTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].RETAILSTOCKCOUNTJOURNALSTABLETYPE AS TABLE
(
    [RECID] [varchar](50) NOT NULL,
    [JOURNALID] [nvarchar](50) NOT NULL,
    [DESCRIPTION] [nvarchar](60) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE] TO [UsersRole];
GO


-- Creating tvp [crt].[RETAILSTOCKCOUNTTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILSTOCKCOUNTTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILSTOCKCOUNTTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILSTOCKCOUNTTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].RETAILSTOCKCOUNTTABLETYPE AS TABLE
(
    [JOURNALID] [nvarchar](50) NOT NULL,
    [RECID] [bigint] NULL,
    [OPERATIONTYPE] [int] NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [ITEMNAME] [nvarchar](60) NULL,
    [COUNTED] [numeric](28, 12) NULL,
    [QUANTITY] [numeric](28, 12) NULL,
    [UNIT] [nvarchar](10) NULL,
    [USERID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [COUNTDATE] [datetime] NULL,
    [STATUS] [int] NULL,
    [INVENTSIZEID] [nvarchar](10) NULL,
    [INVENTCOLORID] [nvarchar](10) NULL,
    [INVENTSTYLEID] [nvarchar](10) NULL,
    [CONFIGID] [nvarchar](10) NULL,
    [TRACKINGGUID] [uniqueidentifier] NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILSTOCKCOUNTTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILSTOCKCOUNTTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILSTOCKCOUNTTABLETYPE] TO [UsersRole];
GO


-- Creating tvp [crt].[TENDERDECLARATIONTRANSTYPE]
PRINT N'Creating tvp [crt].[TENDERDECLARATIONTRANSTYPE]';

GO
IF TYPE_ID('[crt].[TENDERDECLARATIONTRANSTYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[TENDERDECLARATIONTRANSTYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

/******* [crt].[TENDERDECLARATIONTRANSTYPE] refers to TABLE RETAILTRANSACTIONTENDERDECLARATIONTRANS*******/

CREATE TYPE [crt].[TENDERDECLARATIONTRANSTYPE] AS TABLE(
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[AMOUNTMST] [numeric](32, 16) NOT NULL,
[AMOUNTTENDERED] [numeric](32, 16) NOT NULL,
[CARDID] [nvarchar](10) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[EXCHRATE] [numeric](32, 16) NOT NULL,
[EXCHRATEMST] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[POSCURRENCY] [nvarchar](3) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[RECEIPTID] [nvarchar](18) NOT NULL,
[REPLICATED] [int] NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TENDERTYPE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[TENDERDECLARATIONTRANSTYPE]'
GO
-- End creating tvp [crt].[TENDERDECLARATIONTRANSTYPE]


GRANT EXECUTE ON TYPE::[crt].[TENDERDECLARATIONTRANSTYPE] TO [UsersRole];  
GO



-- Creating tvp [crt].[TENDERDROPTRANSTYPE]
PRINT N'Creating tvp [crt].[TENDERDROPTRANSTYPE]';

GO
IF TYPE_ID('[crt].[TENDERDROPTRANSTYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[TENDERDROPTRANSTYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

/******* [crt].[TENDERDROPTRANSTYPE] refers to TABLES RETAILTRANSACTIONBANKEDTENDERTRANS And RETAILTRANSACTIONSAFETENDERTRANS*******/

CREATE TYPE [crt].[TENDERDROPTRANSTYPE] AS TABLE(
[AMOUNTCUR] [numeric](32, 16) NOT NULL,
[AMOUNTCURPOS] [numeric](32, 16) NOT NULL,
[AMOUNTMST] [numeric](32, 16) NOT NULL,
[AMOUNTMSTPOS] [numeric](32, 16) NOT NULL,
[AMOUNTTENDERED] [numeric](32, 16) NOT NULL,
[AMOUNTTENDEREDPOS] [numeric](32, 16) NOT NULL,
[TYPE] [int] NULL,
[BANKBAGNO] [nvarchar](30) NOT NULL,
[CARDORACCOUNT] [nvarchar](30) NOT NULL,
[CARDTYPEID] [nvarchar](10) NOT NULL,
[CURRENCY] [nvarchar](3) NOT NULL,
[EXCHRATE] [numeric](32, 16) NOT NULL,
[EXCHRATEMST] [numeric](32, 16) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[REPLICATED] [int] NOT NULL,
[SHIFT] [nvarchar](10) NOT NULL,
[SHIFTDATE] [date] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[STATEMENTCODE] [nvarchar](25) NOT NULL,
[STATUSTYPE] [int] NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TENDERTYPE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[TRANSDATE] [date] NOT NULL,
[TRANSTIME] [int] NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[TENDERDROPTRANSTYPE]'
GO
-- End creating tvp [crt].[TENDERDROPTRANSTYPE]


GRANT EXECUTE ON TYPE::[crt].[TENDERDROPTRANSTYPE] TO [UsersRole];  
GO



-- Creating tvp [crt].[WISHLISTTABLETYPE]
PRINT N'Creating tvp [crt].[WISHLISTTABLETYPE]';

GO
IF TYPE_ID('[crt].[WISHLISTTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[WISHLISTTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN
 
SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[WISHLISTTABLETYPE] AS TABLE( 
[ID] [nvarchar] (44) NOT NULL, 
[CUSTOMERID] [nvarchar](20) NOT NULL, 
[NAME] [nvarchar](128) NOT NULL, 
[WISHLISTDATA] [varbinary](max) NOT NULL, 
[FAVORITE] [bit] NOT NULL, 
[RECURRING] [bit] NOT NULL 
) 


END
GO
PRINT N'Finished creating tvp [crt].[WISHLISTTABLETYPE]'
GO
-- End creating tvp [crt].[WISHLISTTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[WISHLISTTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[CATALOGDEFINITIONTABLETYPE]
PRINT N'Creating tvp [crt].[CATALOGDEFINITIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[CATALOGDEFINITIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[CATALOGDEFINITIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[CATALOGDEFINITIONTABLETYPE] AS TABLE
(
    [LISTID] [nvarchar](50) NOT NULL,
    [ATTRIBUTERECID] [bigint] NOT NULL,
    [ATTRIBUTEKEYNAME] [nvarchar](50) NOT NULL,
    [LISTGROUPID] [bigint] NOT NULL
    
    PRIMARY KEY CLUSTERED 
    (
        [LISTID] ASC,
        [ATTRIBUTERECID] ASC
    ) WITH (IGNORE_DUP_KEY = OFF)
)


END
GO
PRINT N'Finished creating tvp [crt].[CATALOGDEFINITIONTABLETYPE]'
GO
-- End creating tvp [crt].[CATALOGDEFINITIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].CATALOGDEFINITIONTABLETYPE TO [PublishersRole];
GO

-- Creating tvp [crt].[CATALOGLISTMAPPINGTABLETYPE]
PRINT N'Creating tvp [crt].[CATALOGLISTMAPPINGTABLETYPE]';

GO
IF TYPE_ID('[crt].[CATALOGLISTMAPPINGTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[CATALOGLISTMAPPINGTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[CATALOGLISTMAPPINGTABLETYPE] AS TABLE
(
    [LISTINGRECID] [bigint] NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
    [LISTID] [nvarchar](50) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[CATALOGLISTMAPPINGTABLETYPE]'
GO
-- End creating tvp [crt].[CATALOGLISTMAPPINGTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].CATALOGLISTMAPPINGTABLETYPE TO [PublishersRole];
GO


-- Creating tvp [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE] AS TABLE
(
    [AFFILIATION] [bigint] NOT NULL,
    [CARDNUMBER] [nvarchar](30) NOT NULL,
    [CUSTACCOUNT] [nvarchar](20) NOT NULL,
    [ENTRYDATE] [date] NOT NULL,
    [ENTRYTIME] [int] NOT NULL,
    [ENTRYTYPE] [int] NOT NULL,
    [EXPIRATIONDATE] [date] NOT NULL,
    [LINENUM] [numeric](32, 16) NOT NULL,
    [LOYALTYTIER] [bigint] NOT NULL,
    [RECEIPTID] [nvarchar](18) NOT NULL,
    [REWARDPOINT] [bigint] NOT NULL,
    [REWARDPOINTAMOUNTQTY] [numeric](32, 16) NOT NULL,
    [STAFFID] [nvarchar](25) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [TRANSACTIONID] [nvarchar](44) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[LOYALTYCARDTABLETYPE]
PRINT N'Creating tvp [crt].[LOYALTYCARDTABLETYPE]';

GO
IF TYPE_ID('[crt].[LOYALTYCARDTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[LOYALTYCARDTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[LOYALTYCARDTABLETYPE] AS TABLE
(
[RECID] [bigint] NOT NULL,
[CARDNUMBER] [nvarchar](30) NOT NULL,
[CARDTENDERTYPE] [int] NOT NULL,
[PARTY] [bigint] NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[LOYALTYCARDTABLETYPE]'
GO
-- End creating tvp [crt].[LOYALTYCARDTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[LOYALTYCARDTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[LOYALTYCARDTIERTABLETYPE]
PRINT N'Creating tvp [crt].[LOYALTYCARDTIERTABLETYPE]';

GO
IF TYPE_ID('[crt].[LOYALTYCARDTIERTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[LOYALTYCARDTIERTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[LOYALTYCARDTIERTABLETYPE] AS TABLE
(
[RECID] [bigint] NOT NULL,
[AFFILIATION] [bigint] NOT NULL,
[LOYALTYCARD] [bigint] NOT NULL,
[LOYALTYTIER] [bigint] NOT NULL,
[VALIDFROM] [date] NOT NULL,
[VALIDTO] [date] NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[LOYALTYCARDTIERTABLETYPE]'
GO
-- End creating tvp [crt].[LOYALTYCARDTIERTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[LOYALTYCARDTIERTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[ITEMLINETRANSACTIONTABLETYPE]
PRINT N'Creating tvp [crt].[ITEMLINETRANSACTIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMLINETRANSACTIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMLINETRANSACTIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[ITEMLINETRANSACTIONTABLETYPE] AS TABLE(
[ITEMID] [nvarchar](20) NOT NULL,
[LINENUM] [numeric](32, 16) NOT NULL,
[QTY] [numeric](32, 16) NOT NULL,
[STOREID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[TRANSACTIONSTATUS] [int] NOT NULL,
[VARIANTID] [nvarchar](10) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMLINETRANSACTIONTABLETYPE]'
GO
-- End creating tvp [crt].[ITEMLINETRANSACTIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMLINETRANSACTIONTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[ITEMLINETRANSACTIONTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[QUERYRESULTSETTINGSTYPE]
PRINT N'Creating tvp [crt].[QUERYRESULTSETTINGSTYPE]';

GO
IF TYPE_ID('[crt].[QUERYRESULTSETTINGSTYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[QUERYRESULTSETTINGSTYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[QUERYRESULTSETTINGSTYPE] AS TABLE(
    [SKIP] [int] NOT NULL,
    [TOP] [int] NOT NULL,
    [ORDERBY] NVARCHAR(60) NULL,
    [ASCENDING] BIT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[QUERYRESULTSETTINGSTYPE]'
GO
-- End creating tvp [crt].[QUERYRESULTSETTINGSTYPE]


GRANT EXECUTE ON TYPE::[crt].[QUERYRESULTSETTINGSTYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[QUERYRESULTSETTINGSTYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[ITEMIDSEARCHTABLETYPE]
PRINT N'Creating tvp [crt].[ITEMIDSEARCHTABLETYPE]';

GO
IF TYPE_ID('[crt].[ITEMIDSEARCHTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[ITEMIDSEARCHTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[ITEMIDSEARCHTABLETYPE] AS TABLE
(
    [ITEMID]        NVARCHAR(20) NOT NULL,
    [INVENTDIMID]   NVARCHAR(20) NOT NULL,

    PRIMARY KEY CLUSTERED
    (
        [ITEMID] ASC,
        [INVENTDIMID] ASC
    ) WITH (IGNORE_DUP_KEY = OFF)
)


END
GO
PRINT N'Finished creating tvp [crt].[ITEMIDSEARCHTABLETYPE]'
GO
-- End creating tvp [crt].[ITEMIDSEARCHTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[ITEMIDSEARCHTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[ITEMIDSEARCHTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[KEYWORDSEARCHTABLETYPE]
PRINT N'Creating tvp [crt].[KEYWORDSEARCHTABLETYPE]';

GO
IF TYPE_ID('[crt].[KEYWORDSEARCHTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[KEYWORDSEARCHTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[KEYWORDSEARCHTABLETYPE] AS TABLE(
[INDEX] [int] NOT NULL,
[KEYWORD] varchar(50) NOT NULL,
PRIMARY KEY CLUSTERED 
(
[INDEX] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)


END
GO
PRINT N'Finished creating tvp [crt].[KEYWORDSEARCHTABLETYPE]'
GO
-- End creating tvp [crt].[KEYWORDSEARCHTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[KEYWORDSEARCHTABLETYPE] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[KEYWORDSEARCHTABLETYPE] TO [PublishersRole];
GO

-- Creating tvp [crt].[PURCHASEORDERLINETABLETYPE]
PRINT N'Creating tvp [crt].[PURCHASEORDERLINETABLETYPE]';

GO
IF TYPE_ID('[crt].[PURCHASEORDERLINETABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[PURCHASEORDERLINETABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[PURCHASEORDERLINETABLETYPE] AS TABLE
(
    [RECID] [nvarchar](50) NOT NULL,
    [LINERECEIPTNUMBER] [nvarchar](20) NULL,
    [ITEMID] [nvarchar](20) NULL,
    [ITEMNAME] [nvarchar](60) NULL,
[INVENTDIMID] [nvarchar](20) NULL,
    [QUANTITYORDERED] [numeric](28, 12) NULL,
[PURCHASEQUANTITY] [numeric](28, 12) NULL,
[PURCHASEUNIT] [nvarchar](10) NULL,
    [PURCHASERECEIVED] [numeric](28, 12) NULL,
    [PURCHASERECEIVEDNOW] [numeric](28, 12) NULL,
    [INVENTBATCHID] [nvarchar](10) NULL,
[INVENTSITEID] [nvarchar](10) NULL,
[INVENTLOCATIONID] [nvarchar](20) NULL,
[CONFIGID] [nvarchar](10) NULL,
[INVENTSERIALID] [nvarchar](10) NULL,
[INVENTSIZEID] [nvarchar](10) NULL,
[INVENTCOLORID] [nvarchar](10) NULL,
[INVENTSTYLEID] [nvarchar](10) NULL,
[RECEIPTDATE] [datetime] NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[PURCHASEORDERLINETABLETYPE]'
GO
-- End creating tvp [crt].[PURCHASEORDERLINETABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[PURCHASEORDERLINETABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[TRANSFERORDERLINETABLETYPE]
PRINT N'Creating tvp [crt].[TRANSFERORDERLINETABLETYPE]';

GO
IF TYPE_ID('[crt].[TRANSFERORDERLINETABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[TRANSFERORDERLINETABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[TRANSFERORDERLINETABLETYPE] AS TABLE
(
[RECID] [nvarchar](50) NOT NULL,
    [LINERECEIPTNUMBER] [nvarchar](20) NULL,
    [ITEMID] [nvarchar](20) NULL,
    [ITEMNAME] [nvarchar](60) NULL,
[INVENTDIMID] [nvarchar](20) NULL,
    [QUANTITYTRANSFERRED] [numeric](28, 12) NULL,
[QUANTITYSHIPPED] [numeric](28, 12) NULL,
[QUANTITYRECEIVED] [numeric](28, 12) NULL,
    [QUANTITYSHIPNOW] [numeric](28, 12) NULL,
    [QUANTITYRECEIVENOW] [numeric](28, 12) NULL,
[QUANTITYREMAINSHIP] [numeric](28, 12) NULL,
[QUANTITYREMAINRECEIVE] [numeric](28, 12) NULL,
[PURCHASEUNIT] [nvarchar](10) NULL,
    [INVENTBATCHID] [nvarchar](10) NULL,
[INVENTSITEID] [nvarchar](10) NULL,
[INVENTLOCATIONID] [nvarchar](20) NULL,
[CONFIGID] [nvarchar](10) NULL,
[INVENTSERIALID] [nvarchar](10) NULL,
[INVENTSIZEID] [nvarchar](10) NULL,
[INVENTCOLORID] [nvarchar](10) NULL,
[INVENTSTYLEID] [nvarchar](10) NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[TRANSFERORDERLINETABLETYPE]'
GO
-- End creating tvp [crt].[TRANSFERORDERLINETABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[TRANSFERORDERLINETABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[PICKINGLISTLINETABLETYPE]
PRINT N'Creating tvp [crt].[PICKINGLISTLINETABLETYPE]';

GO
IF TYPE_ID('[crt].[PICKINGLISTLINETABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[PICKINGLISTLINETABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[PICKINGLISTLINETABLETYPE] AS TABLE
(
    [RECID] [nvarchar](50) NOT NULL,
    [ITEMID] [nvarchar](20) NULL,
    [ITEMNAME] [nvarchar](60) NULL,
[INVENTDIMID] [nvarchar](20) NULL,
    [PURCHASERECEIVEDNOW] [numeric](28, 12) NULL,
    [INVENTBATCHID] [nvarchar](10) NULL,
[INVENTSITEID] [nvarchar](10) NULL,
[INVENTLOCATIONID] [nvarchar](20) NULL,
[CONFIGID] [nvarchar](10) NULL,
[INVENTSERIALID] [nvarchar](10) NULL,
[INVENTSIZEID] [nvarchar](10) NULL,
[INVENTCOLORID] [nvarchar](10) NULL,
[INVENTSTYLEID] [nvarchar](10) NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[PICKINGLISTLINETABLETYPE]'
GO
-- End creating tvp [crt].[PICKINGLISTLINETABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[PICKINGLISTLINETABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
    [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE] creates a TYPE 
    about sales affiliations relationship between affiliation and retail transaction
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

CREATE TYPE [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE] AS TABLE
(
    [AFFILIATION] [bigint] NOT NULL,
    [LOYALTYTIER] [bigint] NOT NULL,
    [TRANSACTIONID] [nvarchar](44) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [RECEIPTID] [nvarchar](18) NOT NULL,
    [STAFFID] [nvarchar](25) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[PRODUCTCHANGETRACKINGANCHORSET]
PRINT N'Creating tvp [crt].[PRODUCTCHANGETRACKINGANCHORSET]';

GO
IF TYPE_ID('[crt].[PRODUCTCHANGETRACKINGANCHORSET]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[PRODUCTCHANGETRACKINGANCHORSET] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[PRODUCTCHANGETRACKINGANCHORSET] AS TABLE
(
CHANNELBIGINT,
ECORESPRODUCT BIGINT,
ECORESPRODUCTINSTANCEVALUE BIGINT,
ECORESINSTANCEVALUE BIGINT,
ECORESATTRIBUTE BIGINT,
ECORESATTRIBUTEVALUE BIGINT,
ECORESVALUE BIGINT,
ECORESBOOLEANVALUE BIGINT,
ECORESDATETIMEVALUE BIGINT,
ECORESCURRENCYVALUE BIGINT,
ECORESFLOATVALUE BIGINT,
ECORESINTVALUE BIGINT,
ECORESREFERENCEVALUE BIGINT,
ECORESTEXTVALUE BIGINT,
ECORESTEXTVALUETRANSLATION BIGINT,
ECORESPRODUCTTRANSLATION BIGINT,
ECORESPRODUCTVARIANTCOLOR BIGINT,
ECORESPRODUCTVARIANTCONFIGURATION BIGINT,
ECORESPRODUCTVARIANTDIMENSIONVALUE BIGINT,
ECORESPRODUCTVARIANTSIZE BIGINT,
ECORESPRODUCTVARIANTSTYLE BIGINT,
ECORESCOLOR BIGINT,
ECORESCONFIGURATION BIGINT,
ECORESSIZE BIGINT,
ECORESSTYLE BIGINT,
ECORESATTRIBUTEGROUPATTRIBUTE BIGINT,
ECORESCATEGORYATTRIBUTEGROUP BIGINT,
ECORESCATEGORYATTRIBUTELOOKUP BIGINT,
ECORESDISTINCTPRODUCTVARIANT BIGINT,
ECORESPRODUCTCATEGORY BIGINT,
RETAILCATEGORYCONTAINMENTLOOKUP BIGINT,
RETAILPUBCATALOGPRODUCT BIGINT,
RETAILPUBCATALOGPRODUCTCATEGORY BIGINT,
RETAILPUBCATALOGPRODUCTRELATION BIGINT,
RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION BIGINT,
RETAILPUBINTERNALORGATTRIBUTEGROUP BIGINT,
RETAILPUBINTORGINHERITANCEEXPLODED BIGINT,
RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA BIGINT,
RETAILPUBPRODUCTATTRIBUTEVALUE BIGINT,
RETAILPUBRETAILCHANNELTABLE BIGINT,
RETAILSHAREDPARAMETERS BIGINT,
RETAILSTANDARDATTRIBUTE BIGINT,
UNITOFMEASURE BIGINT,

    PRIMARY KEY(CHANNEL)
)


END
GO
PRINT N'Finished creating tvp [crt].[PRODUCTCHANGETRACKINGANCHORSET]'
GO
-- End creating tvp [crt].[PRODUCTCHANGETRACKINGANCHORSET]


GRANT EXECUTE ON TYPE::[crt].[PRODUCTCHANGETRACKINGANCHORSET] TO [UsersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[PRODUCTCHANGETRACKINGANCHORSET] TO [PublishersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE] AS TABLE
(
[ISTAXONTAX] INT NULL,
    [SALELINENUM] NUMERIC(32, 16) NULL,
    [STOREID] NVARCHAR(10) NULL,
[TAXBASIS]  NUMERIC(32, 16) NULL,
    [TAXCODE] NVARCHAR(10) NOT NULL,
[TAXCOMPONENT] NVARCHAR(15) NULL,
[TAXFORMULA] NVARCHAR(100) NULL,
[TAXISEXEMPT] INT NULL,
[TAXISINCLUDEDINPRICE] INT NULL,
[TAXITEMGROUP]NVARCHAR(10) NULL,
[TAXPERCENTAGE] NUMERIC(32, 16) NULL,
    [TERMINALID] NVARCHAR(10) NULL,
    [TRANSACTIONID] NVARCHAR(44) NOT NULL,
[DATAAREAID] NVARCHAR(4) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[KITCOMPONENTINFOTYPE]
PRINT N'Creating tvp [crt].[KITCOMPONENTINFOTYPE]';

GO
IF TYPE_ID('[crt].[KITCOMPONENTINFOTYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[KITCOMPONENTINFOTYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON

CREATE TYPE [crt].[KITCOMPONENTINFOTYPE] AS TABLE(
[KITLINEPRODUCTLISTING]bigintNOT NULL,
[QUANTITY]numeric(32,16)NOT NULL,
[UNIT]nvarchar(10)NOT NULL,
[CHARGE]numeric(32,16)NOT NULL,
[ITEMID] nvarchar(20)NOT NULL,
[KITLINEPRODUCTMASTERLISTING] bigintNOT NULL,
[ISDEFAULTCOMPONENT] numericNOT NULL,
[KITPRODUCTMASTERLISTING] bigintNOT NULL,
[KITLINEIDENTIFIER] bigintNOT NULL,
[CHANNEL] bigintNOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[KITCOMPONENTINFOTYPE]'
GO
-- End creating tvp [crt].[KITCOMPONENTINFOTYPE]


GRANT EXECUTE ON TYPE::[crt].[KITCOMPONENTINFOTYPE] TO [PublishersRole];
GO

GRANT EXECUTE ON TYPE::[crt].[KITCOMPONENTINFOTYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE]
PRINT N'Creating tvp [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE]';

GO
IF TYPE_ID('[crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TYPE [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE] AS TABLE
(
    [DATAAREAID] NVARCHAR(4) NULL,
    [STOREID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [TRANSACTIONID] [nvarchar](44) NULL,
    [LINENUM] [numeric](32, 16) NOT NULL,
    [TRANSACTIONSTATUS] INT NULL,
    [INVOICEID] [nvarchar](10) NULL,
    [AMOUNTCUR] NUMERIC(32, 16) NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE]'
GO
-- End creating tvp [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE] TO [UsersRole];
GO

-- Creating tvp [crt].[CUSTOMERAFFILIATIONTABLETYPE]
PRINT N'Creating tvp [crt].[CUSTOMERAFFILIATIONTABLETYPE]';

GO
IF TYPE_ID('[crt].[CUSTOMERAFFILIATIONTABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [crt].[CUSTOMERAFFILIATIONTABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

SET QUOTED_IDENTIFIER ON
CREATE TYPE [crt].[CUSTOMERAFFILIATIONTABLETYPE] AS TABLE
(
     RECID                           BIGINT NOT NULL
    ,CUSTACCOUNTNUM                  NVARCHAR(20)
    ,RETAILAFFILIATIONID             BIGINT NOT NULL
)


END
GO
PRINT N'Finished creating tvp [crt].[CUSTOMERAFFILIATIONTABLETYPE]'
GO
-- End creating tvp [crt].[CUSTOMERAFFILIATIONTABLETYPE]


GRANT EXECUTE ON TYPE::[crt].[CUSTOMERAFFILIATIONTABLETYPE] TO [UsersRole];
GO

-- Creating table [crt].[CUSTOMERORDERTRANSACTION]
PRINT N'Creating table [crt].[CUSTOMERORDERTRANSACTION]';

GO
IF OBJECT_ID(N'[crt].[CUSTOMERORDERTRANSACTION]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[CUSTOMERORDERTRANSACTION] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[CUSTOMERORDERTRANSACTION]
(
[CHANNEL] [bigint] NOT NULL,
[STORE] [nvarchar](10) NOT NULL,
[TERMINAL] [nvarchar](10) NOT NULL,
[TRANSACTIONID] [nvarchar](44) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[CANCELLATIONCHARGE] [numeric](32,16) NULL,
[DEPOSITOVERRIDE] [numeric](32,16) NULL,
[REQUIREDDEPOSIT] [numeric](32,16) NOT NULL,
[CALCULATEDDEPOSIT] [numeric](32,16) NOT NULL,
[PREPAYMENTPAID] [numeric](32,16) NOT NULL,
[PREPAYMENTINVOICED] [numeric](32,16) NOT NULL,
[ROWVERSION] [timestamp] NOT NULL,

CONSTRAINT [PK_RETAILCUSTOMERORDERTRANSACTIONTABLE] PRIMARY KEY CLUSTERED 
(
[STORE] ASC,
[TERMINAL] ASC,
[TRANSACTIONID] ASC,
[CHANNEL] ASC,
[DATAAREAID] ASC
) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[CUSTOMERORDERTRANSACTION]'
GO
-- End creating table [crt].[CUSTOMERORDERTRANSACTION]


GO

-- Creating table [ax].DBVERSION
PRINT N'Creating table [ax].DBVERSION';

GO
IF OBJECT_ID(N'[ax].DBVERSION', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [ax].DBVERSION already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [ax].DBVERSION
(
    VersionType nvarchar(50) NOT NULL,
    VersionNumber INT NOT NULL,
    VersionString nvarchar(50) NULL
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [ax].DBVERSION'
GO
-- End creating table [ax].DBVERSION


-- build 6.3.158.0
PRINT N'Setting the DBVersion from the build 6.3.158.0'

--we populate the DBVersion stored proc
declare @thisDbVersion int;
declare @thisDbVersionString nvarchar(50);
declare @thisDbVersionType nvarchar(50);

--the format for the int is as follows:
-- 2 digits for the major version
-- 2 digits for the minor versiom
-- 3 digits for the build num major
-- 2 digit for the build num minor
-- this is because one int = 32 bit = 4G -> 10 decimal digit but the highest can only go from 0 to 3
-- so we don't really want to use it for the product version right away as it will limit us to 19
-- skipping it allows us a max range of 199.99.999.99 
-- for the time being the build minor is not upscaled so 3.5.1.1 is 3|05|001|01 and not 3|50|001|01

SET @thisDbVersion = 6 * POWER(10, 7) + 3 * POWER(10, 5) + 158 * POWER(10, 2) + 0;
SET @thisDbVersionString = CAST( N'6' + N'.' + N'3' + N'.' + N'158' + N'.' + N'0' AS nvarchar(50))
SET @thisDbVersionType = N'databaseVersion';

PRINT N'DBVersion is ' + CAST(@thisDbVersion as nvarchar(50));

IF EXISTS(SELECT TOP 1 VersionNumber FROM [ax].[DBVersion] WHERE VersionType = @thisDbVersionType)  
    UPDATE [ax].[DBVersion] SET VersionNumber = @thisDbVersion, VersionString = @thisDbVersionString
ELSE 
    INSERT [ax].[DBVersion] (VersionType, VersionNumber, VersionString) VALUES (@thisDbVersionType, @thisDbVersion, @thisDbVersionString)
GO

PRINT N'DBVersion set'

-- Creating table [crt].[TMPASSORTEDPRODUCTS]
PRINT N'Creating table [crt].[TMPASSORTEDPRODUCTS]';

GO
IF OBJECT_ID(N'[crt].[TMPASSORTEDPRODUCTS]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[TMPASSORTEDPRODUCTS] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[TMPASSORTEDPRODUCTS]
(
    [CHANNELID] [bigint] NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [PRODUCTID] [bigint] NOT NULL,
    [VALIDFROM] [date] NOT NULL,
    [VALIDTO] [date] NOT NULL

    CONSTRAINT [PK_TMPASSORTEDPRODUCTS] PRIMARY KEY CLUSTERED
    (
        [CHANNELID] ASC,
        [PRODUCTID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[TMPASSORTEDPRODUCTS]'
GO
-- End creating table [crt].[TMPASSORTEDPRODUCTS]

-- Creating table [crt].[ORDERCREATIONSTATUS]
PRINT N'Creating table [crt].[ORDERCREATIONSTATUS]';

GO
IF OBJECT_ID(N'[crt].[ORDERCREATIONSTATUS]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[ORDERCREATIONSTATUS] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[ORDERCREATIONSTATUS]
(
    [TRANSACTIONID] [nvarchar] (44) NOT NULL,
    [STORE] [nvarchar] (10) NOT NULL,
    [TERMINAL] [nvarchar](500) NULL,
    [CHANNEL] [BIGINT] NULL,
    [STATUS] [nvarchar](500) NULL,
    [POTENTIALCAUSEOFFAILURE] [nvarchar] (4000) NULL,
    [DETAILS] [nvarchar] (4000) NULL,
    [QUERYTIMESTAMP] [DATETIME] NOT NULL
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[ORDERCREATIONSTATUS]'
GO
-- End creating table [crt].[ORDERCREATIONSTATUS]

-- Creating table [crt].[SALESTRANSACTION]
PRINT N'Creating table [crt].[SALESTRANSACTION]';

GO
IF OBJECT_ID(N'[crt].[SALESTRANSACTION]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[SALESTRANSACTION] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[SALESTRANSACTION]
(
    [TRANSACTIONID] [nvarchar](44) NOT NULL,
    [CHANNELID] [bigint] NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [CUSTOMERID] [nvarchar](20) NULL,
    [NAME] [nvarchar](128) NULL,
    [BYTELENGTH] [int] NOT NULL,
    [TRANSACTIONDATA] [varbinary](max) NOT NULL,
    [CREATEDDATETIME] [datetime] NOT NULL,
    [MODIFIEDDATETIME] [datetime] NOT NULL,
    [DELETEDDATETIME] [datetime] NULL,
    [ROWVERSION] [rowversion] NOT NULL,
    [ISSUSPENDED] [bit] NOT NULL,
[COMMENT] [nvarchar](60),
[TYPE] [int] NOT NULL,
[STAFF] [nvarchar](25) NOT NULL,
[AMOUNT] [numeric](32, 16) NOT NULL

    CONSTRAINT [PK_SALESTRANSACTION] PRIMARY KEY CLUSTERED
    (
        [TRANSACTIONID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[SALESTRANSACTION]'
GO
-- End creating table [crt].[SALESTRANSACTION]




IF INDEXPROPERTY (OBJECT_ID (N'[crt].[SALESTRANSACTION]', N'U'), N'IX_SALESTRANSACTION_MODIFIEDDATETIME', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_SALESTRANSACTION_MODIFIEDDATETIME'


CREATE NONCLUSTERED INDEX IX_SALESTRANSACTION_MODIFIEDDATETIME ON [crt].[SALESTRANSACTION]
(
    [MODIFIEDDATETIME]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_SALESTRANSACTION_MODIFIEDDATETIME'



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[SALESTRANSACTION]', N'U'), N'IX_SALESTRANSACTION_CUSTOMERID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_SALESTRANSACTION_CUSTOMERID'


CREATE NONCLUSTERED INDEX IX_SALESTRANSACTION_CUSTOMERID ON [crt].[SALESTRANSACTION]
(
    [CUSTOMERID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_SALESTRANSACTION_CUSTOMERID'

-- Creating table [crt].[WISHLIST]
PRINT N'Creating table [crt].[WISHLIST]';

GO
IF OBJECT_ID(N'[crt].[WISHLIST]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[WISHLIST] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[WISHLIST]
(
    [ID] [nvarchar](44) NOT NULL,
    [CUSTOMERID] [nvarchar](20) NOT NULL,
    [NAME] [nvarchar](128) NOT NULL,
    [WISHLISTDATA] [varbinary](max) NOT NULL,
    [CREATEDDATETIME] [datetime] NOT NULL,
    [MODIFIEDDATETIME] [datetime] NOT NULL,
    [DELETEDDATETIME] [datetime] NULL,
    [FAVORITE] [bit] NOT NULL,
    [RECURRING] [bit] NOT NULL,

     CONSTRAINT [PK_WISHLIST] PRIMARY KEY CLUSTERED
    (
        [ID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[WISHLIST]'
GO
-- End creating table [crt].[WISHLIST]

-- Creating table [crt].[ITEMRESERVATION]
PRINT N'Creating table [crt].[ITEMRESERVATION]';

GO
IF OBJECT_ID(N'[crt].[ITEMRESERVATION]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[ITEMRESERVATION] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].ITEMRESERVATION
(
    [RESERVATIONID] [uniqueidentifier] NOT NULL,
    [INVENTAVAILABILITY] [bigint] NOT NULL,
    [QUANTITY] [numeric](32, 16) NOT NULL,
    [EXPIREDATETIME] [datetime] NOT NULL,
    [ISRELEASED] [bit] NOT NULL,

    CONSTRAINT PK_ITEMRESERVATION_RESERVATIONID PRIMARY KEY CLUSTERED
    (
        RESERVATIONID ASC
    ) ON [PRIMARY],
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[ITEMRESERVATION]'
GO
-- End creating table [crt].[ITEMRESERVATION]



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[ITEMRESERVATION]', N'U'), N'IX_ITEMRESERVATION_INVENTAVAILABILITY', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ITEMRESERVATION_INVENTAVAILABILITY'


CREATE NONCLUSTERED INDEX IX_ITEMRESERVATION_INVENTAVAILABILITY
    ON [crt].[ITEMRESERVATION]
    (
        INVENTAVAILABILITY
    )


END
ELSE
    PRINT 'Existing index IX_ITEMRESERVATION_INVENTAVAILABILITY'



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[ITEMRESERVATION]', N'U'), N'IX_ITEMRESERVATION_EXPIREDATETIME', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ITEMRESERVATION_EXPIREDATETIME'


CREATE NONCLUSTERED INDEX IX_ITEMRESERVATION_EXPIREDATETIME
    ON [crt].[ITEMRESERVATION]
    (
        EXPIREDATETIME
    )


END
ELSE
    PRINT 'Existing index IX_ITEMRESERVATION_EXPIREDATETIME'



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[ITEMRESERVATION]', N'U'), N'IX_ITEMRESERVATION_ISRELEASED', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ITEMRESERVATION_ISRELEASED'


CREATE NONCLUSTERED INDEX IX_ITEMRESERVATION_ISRELEASED
    ON [crt].[ITEMRESERVATION]
    (
        ISRELEASED
    )


END
ELSE
    PRINT 'Existing index IX_ITEMRESERVATION_ISRELEASED'


-- Creating table [crt].[RETAILCATALOGPUBLISHINGSYNCSTATE]
PRINT N'Creating table [crt].[RETAILCATALOGPUBLISHINGSYNCSTATE]';

GO
IF OBJECT_ID(N'[crt].[RETAILCATALOGPUBLISHINGSYNCSTATE]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILCATALOGPUBLISHINGSYNCSTATE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILCATALOGPUBLISHINGSYNCSTATE]
(
    [DESTINATIONID] [uniqueidentifier] NOT NULL,
    [TABLENAME] [nvarchar](50) NOT NULL,
    [LASTSYNCVERSION] [bigint] NOT NULL,

    CONSTRAINT [PK_RETAILCATALOGPUBLISHINGSYNCSTATE] PRIMARY KEY CLUSTERED 
    (
        [DESTINATIONID] ASC,
        [TABLENAME] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILCATALOGPUBLISHINGSYNCSTATE]'
GO
-- End creating table [crt].[RETAILCATALOGPUBLISHINGSYNCSTATE]
IF COL_LENGTH('ax.RETAILCHANNELPAYMENTCONNECTORLINE','ISTESTMODE') IS NULL
BEGIN
    ALTER TABLE [ax].[RETAILCHANNELPAYMENTCONNECTORLINE] ADD [ISTESTMODE] [bit] NULL
END
GO

-- Creating table [crt].[RETAILCHANNELPROPERTIES]
PRINT N'Creating table [crt].[RETAILCHANNELPROPERTIES]';

GO
IF OBJECT_ID(N'[crt].[RETAILCHANNELPROPERTIES]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILCHANNELPROPERTIES] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILCHANNELPROPERTIES]
(
    [RECID] [bigint],
    [CHANNEL] [bigint] NOT NULL,
    [NAME] [nvarchar](128) NOT NULL,  -- Reduced to 128 to fit in PK index
    [VALUE] [nvarchar](max) NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,

    CONSTRAINT [PK_RETAILCHANNELPROPERTIES] PRIMARY KEY CLUSTERED
    (
        [CHANNEL] ASC,
        [NAME] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILCHANNELPROPERTIES]'
GO
-- End creating table [crt].[RETAILCHANNELPROPERTIES]
IF COL_LENGTH('ax.RETAILCHANNELPAYMENTCONNECTORLINE','ISTESTMODE') IS NULL
BEGIN
    ALTER TABLE [ax].[RETAILCHANNELPAYMENTCONNECTORLINE] ADD [ISTESTMODE] [bit] NULL
END
GO

-- Creating table [crt].[RETAILSHIFTSTAGINGTABLE]
PRINT N'Creating table [crt].[RETAILSHIFTSTAGINGTABLE]';

GO
IF OBJECT_ID(N'[crt].[RETAILSHIFTSTAGINGTABLE]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILSHIFTSTAGINGTABLE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILSHIFTSTAGINGTABLE]
(
    [CHANNEL] [bigint] NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [SHIFTID] [bigint] NOT NULL,
    [STAFFID] [nvarchar](25) NOT NULL,
    [CURRENTSTAFFID] [nvarchar](25) NULL,
    [STATUS] [int] NOT NULL,
    [CURRENTTERMINALID] [nvarchar](10) NULL,
    [STARTDATETIMEUTC] [datetime] NOT NULL,
    [STATUSDATETIMEUTC] [datetime] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [CASHDRAWER] [nvarchar](512) NULL,
    [ROWVERSION] [timestamp] NOT NULL,

    CONSTRAINT [PK_RETAILSHIFTSTAGINGTABLE] PRIMARY KEY CLUSTERED
    (
        [CHANNEL] ASC,
        [TERMINALID] ASC,
        [SHIFTID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILSHIFTSTAGINGTABLE]'
GO
-- End creating table [crt].[RETAILSHIFTSTAGINGTABLE]
IF COL_LENGTH('[ax].RETAILLISTINGSTATUSLOG','CHANNELBATCHID') IS NULL
BEGIN
    ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD [CHANNELBATCHID] NVARCHAR(100) NOT NULL DEFAULT('');
END
GO

IF COL_LENGTH('[ax].RETAILLISTINGSTATUSLOG','CHANNELSTATE') IS NULL
BEGIN
    ALTER TABLE [ax].[RETAILLISTINGSTATUSLOG] ADD [CHANNELSTATE] NVARCHAR(4000) NOT NULL DEFAULT('');
END
GO

-- Creating table [crt].[RETAILSHIPMENTPUBLISHINGSTATUS]
PRINT N'Creating table [crt].[RETAILSHIPMENTPUBLISHINGSTATUS]';

GO
IF OBJECT_ID(N'[crt].[RETAILSHIPMENTPUBLISHINGSTATUS]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILSHIPMENTPUBLISHINGSTATUS] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILSHIPMENTPUBLISHINGSTATUS]
(
    [CHANNELID] [bigint] NOT NULL,
    [SALESID] [nvarchar](40) NOT NULL,
    [PACKINGSLIPID] [nvarchar](40) NOT NULL,
    [PUBLISHSTATUS] [int] NOT NULL,
    [CHANNELBATCHID] [nvarchar](128) NOT NULL,
    [CHANNELREFID] [nvarchar](128) NOT NULL,
    [ROWVERSION] [timestamp] NOT NULL,
    [LASTMODIFIEDDATETIME] [datetime] NOT NULL DEFAULT (GETUTCDATE()),
    [PUBLISHMESSAGE] [nvarchar](2048) NOT NULL

    CONSTRAINT [PK_RETAILSHIPMENTPUBLISHINGSTATUS] PRIMARY KEY CLUSTERED
    (
        [CHANNELID] ASC,
        [SALESID] ASC,
        [PACKINGSLIPID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILSHIPMENTPUBLISHINGSTATUS]'
GO
-- End creating table [crt].[RETAILSHIPMENTPUBLISHINGSTATUS]

-- Creating table [crt].[RETAILTRANSACTIONPROPERTIES]
PRINT N'Creating table [crt].[RETAILTRANSACTIONPROPERTIES]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONPROPERTIES]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILTRANSACTIONPROPERTIES] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILTRANSACTIONPROPERTIES]
(
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [CHANNEL] [bigint] NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [TRANSACTIONID] [nvarchar](44) NOT NULL,
    [SALELINENUM] [numeric](32, 16) NOT NULL,
    [NAME] [nvarchar](128) NOT NULL,  -- Reduced to 128 to fit in PK index
    [VALUE] [nvarchar](2000) NOT NULL

    CONSTRAINT [PK_RETAILTRANSACTIONPROPERTIES] PRIMARY KEY CLUSTERED
    (
        [DATAAREAID] ASC,
        [CHANNEL] ASC,
        [STOREID] ASC,
        [TERMINALID] ASC,
        [TRANSACTIONID] ASC,
        [SALELINENUM] ASC,
        [NAME] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILTRANSACTIONPROPERTIES]'
GO
-- End creating table [crt].[RETAILTRANSACTIONPROPERTIES]

-- Creating table [crt].[RETAILSTOCKCOUNTJOURNALS]
PRINT N'Creating table [crt].[RETAILSTOCKCOUNTJOURNALS]';

GO
IF OBJECT_ID(N'[crt].[RETAILSTOCKCOUNTJOURNALS]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILSTOCKCOUNTJOURNALS] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILSTOCKCOUNTJOURNALS]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RECID] [varchar](50) NOT NULL,
    [JOURNALID] [nvarchar](50) NOT NULL,
    [DESCRIPTION] [nvarchar](60) NULL,
    [ROWVERSION] [timestamp] NOT NULL,

    CONSTRAINT [PK_RETAILSTOCKCOUNTJOURNALS] PRIMARY KEY CLUSTERED
    (
        [ID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILSTOCKCOUNTJOURNALS]'
GO
-- End creating table [crt].[RETAILSTOCKCOUNTJOURNALS]

-- Creating table [crt].[RETAILSTOCKCOUNT]
PRINT N'Creating table [crt].[RETAILSTOCKCOUNT]';

GO
IF OBJECT_ID(N'[crt].[RETAILSTOCKCOUNT]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILSTOCKCOUNT] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILSTOCKCOUNT]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [JOURNALID] [nvarchar](50) NOT NULL,
    [RECID] [bigint] NULL,
    [OPERATIONTYPE] [int] NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [ITEMNAME] [nvarchar](60) NULL,
    [COUNTED] [numeric](28, 12) NULL,
    [QUANTITY] [numeric](28, 12) NULL,
    [UNIT] [nvarchar](10) NULL,
    [USERID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [COUNTDATE] [datetime] NULL,
    [STATUS] [int] NULL,
    [INVENTSIZEID] [nvarchar](10) NOT NULL,
    [INVENTCOLORID] [nvarchar](10) NOT  NULL,
    [INVENTSTYLEID] [nvarchar](10) NOT NULL,
    [CONFIGID] [nvarchar](10) NOT NULL,
    [TRACKINGGUID] [uniqueidentifier] NOT NULL,
    [ROWVERSION] [timestamp] NOT NULL,

    CONSTRAINT [PK_RETAILSTOCKCOUNT] PRIMARY KEY CLUSTERED
    (
        [ID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]



END
GO
PRINT N'Finished creating table [crt].[RETAILSTOCKCOUNT]'
GO
-- End creating table [crt].[RETAILSTOCKCOUNT]

-- Creating table [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]
PRINT N'Creating table [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]';

GO
IF OBJECT_ID(N'[crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]
(
    [CATEGORY] [bigint] NOT NULL,
    [PRODUCT] [bigint] NOT NULL,
    [RECID] [bigint] NOT NULL,
    [ISPROCESSED] [int] DEFAULT ((0)) NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,

    CONSTRAINT [PK_ECORESPRODUCTCATEGORY_PRICETRACKING] PRIMARY KEY NONCLUSTERED
    (
        [CATEGORY] ASC,
        [PRODUCT] ASC,
        [RECID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]'
GO
-- End creating table [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]



-- Creating table [crt].[PRICEDISCTABLE_PRICETRACKING]
PRINT N'Creating table [crt].[PRICEDISCTABLE_PRICETRACKING]';

GO
IF OBJECT_ID(N'[crt].[PRICEDISCTABLE_PRICETRACKING]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[PRICEDISCTABLE_PRICETRACKING] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[PRICEDISCTABLE_PRICETRACKING]
(
    [ACCOUNTCODE] [int] NOT NULL,
    [ITEMRELATION] [nvarchar](20) NOT NULL,
    [ACCOUNTRELATION] [nvarchar](20) NOT NULL,
    [INVENTDIMID] [nvarchar](20) NOT NULL,
    [RECID] [bigint] NOT NULL,
    [ISPROCESSED] [int] DEFAULT ((0)) NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,

    CONSTRAINT [PK_PRICEDISCTABLE_PRICETRACKING_1] PRIMARY KEY CLUSTERED
    (
        [ITEMRELATION] ASC,
        [INVENTDIMID] ASC,
        [RECID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[PRICEDISCTABLE_PRICETRACKING]'
GO
-- End creating table [crt].[PRICEDISCTABLE_PRICETRACKING]

-- Creating table [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
PRINT N'Creating table [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]';

GO
IF OBJECT_ID(N'[crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
(
    [TABLEID] [bigint] NOT NULL,
    [RECID] [bigint] NOT NULL,
    [DATE] [date] NOT NULL,
    [DATETYPE] [int] NOT NULL,
    [ISPROCESSED] [int] DEFAULT ((0)) NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,

    CONSTRAINT [PK_RETAILLISTINGPRICEDATEEFFECTIVITY] PRIMARY KEY CLUSTERED
    (
        [TABLEID] ASC,
        [RECID] ASC,
        [DATETYPE] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]'
GO
-- End creating table [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]

-- Creating table [crt].[PRICETRACKINGTIMESTAMP]
PRINT N'Creating table [crt].[PRICETRACKINGTIMESTAMP]';

GO
IF OBJECT_ID(N'[crt].[PRICETRACKINGTIMESTAMP]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[PRICETRACKINGTIMESTAMP] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[PRICETRACKINGTIMESTAMP]
(
    [CHANNELID] [bigint] NOT NULL,
    [LASTTIMESTAMP] [varbinary](8) NOT NULL,
    [LASTUTCTIME] [date] NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,

    CONSTRAINT [PK_PRICETRACKINGTIMESTAMP_1] PRIMARY KEY CLUSTERED
    (
        [CHANNELID] ASC,
        [LASTTIMESTAMP] ASC,
        [LASTUTCTIME] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[PRICETRACKINGTIMESTAMP]'
GO
-- End creating table [crt].[PRICETRACKINGTIMESTAMP]

-- Creating table [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]
PRINT N'Creating table [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]';

GO
IF OBJECT_ID(N'[crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]
(
    [CATEGORY] [bigint] NOT NULL,
    [CONTAINEDCATEGORY] [bigint] NOT NULL,
    [RECID] [bigint] NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,
    [ISPROCESSED] [int] DEFAULT((0)) NOT NULL,

    CONSTRAINT [PK_RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING] PRIMARY KEY CLUSTERED
    (
        [CATEGORY] ASC,
        [CONTAINEDCATEGORY] ASC,
        [RECID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]'
GO
-- End creating table [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]

-- Creating table [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]
PRINT N'Creating table [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]';

GO
IF OBJECT_ID(N'[crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]
(
    [RETAILCHANNEL] [bigint] NOT NULL,
    [PRICEGROUP] [bigint] NOT NULL,
    [RECID] [bigint] NOT NULL,
    [ISPROCESSED] [int] DEFAULT ((0)) NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,

    CONSTRAINT [PK_RETAILCHANNELPRICEGROUP_PRICETRACKING] PRIMARY KEY NONCLUSTERED
    (
        [RETAILCHANNEL] ASC,
        [PRICEGROUP] ASC,
        [RECID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]'
GO
-- End creating table [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]

-- Creating table [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]
PRINT N'Creating table [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]';

GO
IF OBJECT_ID(N'[crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]
(
    [CATEGORY] [bigint] NOT NULL,
    [PRODUCT] [bigint] NOT NULL,
    [VARIANT] [bigint] NOT NULL,
    [RECID] [bigint] NOT NULL,
    [ISPROCESSED] [int] DEFAULT ((0)) NOT NULL,
    [ROWVERSION] [rowversion] NOT NULL,

    CONSTRAINT [PK_RETAILGROUPMEMBERLINE_PRICETRACKING] PRIMARY KEY NONCLUSTERED
    (
        [CATEGORY] ASC,
        [PRODUCT] ASC,
        [VARIANT] ASC,
        [RECID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]'
GO
-- End creating table [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]

-- Creating table [crt].[CATALOGDEFINITION]
PRINT N'Creating table [crt].[CATALOGDEFINITION]';

GO
IF OBJECT_ID(N'[crt].[CATALOGDEFINITION]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[CATALOGDEFINITION] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[CATALOGDEFINITION]
(
    [CHANNELID] [bigint] NOT NULL,
    [LISTID] [nvarchar](50) NOT NULL,
    [ATTRIBUTERECID] [bigint] NOT NULL,
    [LISTGROUPID] [bigint] NOT NULL,
    [ATTRIBUTEKEYNAME] [nvarchar](50) NOT NULL,

    CONSTRAINT [PK_CATALOGDEFINITION] PRIMARY KEY CLUSTERED
    (
        [CHANNELID] ASC,
        [LISTID] ASC,
        [ATTRIBUTERECID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[CATALOGDEFINITION]'
GO
-- End creating table [crt].[CATALOGDEFINITION]



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[CATALOGDEFINITION]', N'U'), N'IX_CATALOGDEFINITION_LISTDEFINITION', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_CATALOGDEFINITION_LISTDEFINITION'


CREATE NONCLUSTERED INDEX IX_CATALOGDEFINITION_LISTDEFINITION
    ON [crt].[CATALOGDEFINITION]
    (
        LISTID
    )


END
ELSE
    PRINT 'Existing index IX_CATALOGDEFINITION_LISTDEFINITION'



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[CATALOGDEFINITION]', N'U'), N'IX_CATALOGDEFINITION_LISTGROUPS', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_CATALOGDEFINITION_LISTGROUPS'


CREATE NONCLUSTERED INDEX IX_CATALOGDEFINITION_LISTGROUPS
    ON [crt].[CATALOGDEFINITION]
    (
        LISTID,
        ATTRIBUTERECID,
        ATTRIBUTEKEYNAME,
        LISTGROUPID
    )


END
ELSE
    PRINT 'Existing index IX_CATALOGDEFINITION_LISTGROUPS'

-- Creating table [crt].[CATALOGLISTMAPPING]
PRINT N'Creating table [crt].[CATALOGLISTMAPPING]';

GO
IF OBJECT_ID(N'[crt].[CATALOGLISTMAPPING]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[CATALOGLISTMAPPING] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[CATALOGLISTMAPPING]
(
    [CHANNELID] [bigint] NOT NULL,
[CATALOGID][bigint] NOT NULL,
[LISTINGRECID] [bigint] NOT NULL,
[LANGUAGEID] [nvarchar](7) NOT NULL,
    [LISTID] [nvarchar](50) NOT NULL,

    CONSTRAINT [PK_CATALOGLISTMAPPING] PRIMARY KEY CLUSTERED
    (
        [CHANNELID] ASC,
[CATALOGID] ASC,
[LISTINGRECID] ASC,
[LANGUAGEID] ASC,
        [LISTID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[CATALOGLISTMAPPING]'
GO
-- End creating table [crt].[CATALOGLISTMAPPING]
IF COL_LENGTH('ax.RETAILHARDWAREPROFILE','EFTTESTMODE') IS NULL
BEGIN
    ALTER TABLE [ax].[RETAILHARDWAREPROFILE] ADD [EFTTESTMODE] [int] NULL DEFAULT 0
END
GO

-- Creating table [crt].[UPLOADSESSION]
PRINT N'Creating table [crt].[UPLOADSESSION]';

GO
IF OBJECT_ID(N'[crt].[UPLOADSESSION]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[UPLOADSESSION] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[UPLOADSESSION] (
    [ID]              BIGINT         IDENTITY (1, 1) NOT NULL,
    [JOBID]NVARCHAR (20)  NOT NULL DEFAULT (''),
    [STATUS]          INT            NOT NULL DEFAULT 0,
    [MESSAGE]         NVARCHAR (MAX) NULL ,
    [UPLOADPATH] NVARCHAR(1024) NULL , 
    [DATECREATED]DATETIMENULL DEFAULT GetDate(), 
    [DATEUPLOADED]DATETIMENULL, 
    [FILESIZE] BIGINT NOT NULL DEFAULT 0, 
    [CHECKSUM] NVARCHAR(64) NULL DEFAULT (''), 
    CONSTRAINT [PK_UPLOADSESSION] PRIMARY KEY CLUSTERED ([ID] ASC)
);


END
GO
PRINT N'Finished creating table [crt].[UPLOADSESSION]'
GO
-- End creating table [crt].[UPLOADSESSION]


GRANT DELETE, INSERT, SELECT, UPDATE ON [crt].[UPLOADSESSION] TO [DataSyncUsersRole];
GO

-- Creating table [crt].[TABLEREPLICATIONLOG]
PRINT N'Creating table [crt].[TABLEREPLICATIONLOG]';

GO
IF OBJECT_ID(N'[crt].[TABLEREPLICATIONLOG]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[TABLEREPLICATIONLOG] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[TABLEREPLICATIONLOG]
(
    [ID] BIGINT IDENTITY (1, 1) NOT NULL PRIMARY KEY, 
    [UPLOADSESSIONID] BIGINT NOT NULL, 
    [TABLENAME] NVARCHAR(50) NOT NULL, 
    [FILTERFIELDNAME] NVARCHAR(50) NOT NULL, 
    [FILTERMIN] BIGINT NOT NULL DEFAULT 0, 
    [FILTERMAX] BIGINT NOT NULL DEFAULT 0
);


END
GO
PRINT N'Finished creating table [crt].[TABLEREPLICATIONLOG]'
GO
-- End creating table [crt].[TABLEREPLICATIONLOG]



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[TABLEREPLICATIONLOG]', N'U'), N'IX_TABLEREPLICATIONLOG_UPLOADSESSIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_TABLEREPLICATIONLOG_UPLOADSESSIONID'


CREATE NONCLUSTERED INDEX [IX_TABLEREPLICATIONLOG_UPLOADSESSIONID]
    ON [crt].[TABLEREPLICATIONLOG]([UPLOADSESSIONID] ASC);


END
ELSE
    PRINT 'Existing index IX_TABLEREPLICATIONLOG_UPLOADSESSIONID'


GRANT DELETE, INSERT, SELECT, UPDATE ON [crt].[TABLEREPLICATIONLOG] TO [DataSyncUsersRole];
GO

-- Creating table [crt].[PURCHASEORDERLINE]
PRINT N'Creating table [crt].[PURCHASEORDERLINE]';

GO
IF OBJECT_ID(N'[crt].[PURCHASEORDERLINE]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[PURCHASEORDERLINE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[PURCHASEORDERLINE](
[RECID] [nvarchar](50) NOT NULL,
    [ORDERID] [nvarchar](50) NOT NULL,
    [LINERECEIPTNUMBER] [nvarchar](20) NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [ITEMNAME] [nvarchar](60) NULL,
[INVENTDIMID] [nvarchar](20) NULL,
    [QUANTITYORDERED] [numeric](28, 12) NULL CONSTRAINT "DF_QUANTITYORDERED" DEFAULT 0,
[PURCHASEQUANTITY] [numeric](28, 12) NULL CONSTRAINT "DF_PURCHASEQUANTITY" DEFAULT 0,
[PURCHASEUNIT] [nvarchar](10) NULL,
    [PURCHASERECEIVED] [numeric](28, 12) NULL CONSTRAINT "DF_PURCHASERECEIVED" DEFAULT 0,
    [PURCHASERECEIVEDNOW] [numeric](28, 12) NULL CONSTRAINT "DF_PURCHASERECEIVEDNOW" DEFAULT 0,
    [INVENTBATCHID] [nvarchar](10) NULL,
[INVENTSITEID] [nvarchar](10) NULL,
[INVENTLOCATIONID] [nvarchar](20) NULL,
[CONFIGID] [nvarchar](10) NOT NULL,
[INVENTSERIALID] [nvarchar](10) NULL,
[INVENTSIZEID] [nvarchar](10) NOT NULL,
[INVENTCOLORID] [nvarchar](10) NOT NULL,
[INVENTSTYLEID] [nvarchar](10) NOT NULL,
[RECEIPTDATE] [datetime] NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL,
 CONSTRAINT [PK_PURCHASEORDERLINE] PRIMARY KEY CLUSTERED
(
    [ORDERID],[RECID],[ITEMID],[CONFIGID],[INVENTCOLORID],[INVENTSIZEID],[INVENTSTYLEID]
)
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[PURCHASEORDERLINE]'
GO
-- End creating table [crt].[PURCHASEORDERLINE]

-- Creating table [crt].[TRANSFERORDERLINE]
PRINT N'Creating table [crt].[TRANSFERORDERLINE]';

GO
IF OBJECT_ID(N'[crt].[TRANSFERORDERLINE]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[TRANSFERORDERLINE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[TRANSFERORDERLINE](
[RECID] [nvarchar](50) NOT NULL,
    [ORDERID] [nvarchar](50) NOT NULL,
    [LINERECEIPTNUMBER] [nvarchar](20) NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [ITEMNAME] [nvarchar](60) NULL,
[INVENTDIMID] [nvarchar](20) NULL,
    [QUANTITYTRANSFERRED] [numeric](28, 12) NULL CONSTRAINT "DF_QTYTRANSFER" DEFAULT 0,
[QUANTITYSHIPPED] [numeric](28, 12) NULL CONSTRAINT "DF_QTYSHIPPED" DEFAULT 0,
[QUANTITYRECEIVED] [numeric](28, 12) NULL CONSTRAINT "DF_QTYRECEIVED" DEFAULT 0,
    [QUANTITYSHIPNOW] [numeric](28, 12) NULL CONSTRAINT "DF_QTYSHIPNOW" DEFAULT 0,
    [QUANTITYRECEIVENOW] [numeric](28, 12) NULL CONSTRAINT "DF_QTYRECEIVENOW" DEFAULT 0,
[QUANTITYREMAINSHIP] [numeric](28, 12) NULL CONSTRAINT "DF_QTYREMAINSHIP" DEFAULT 0,
[QUANTITYREMAINRECEIVE] [numeric](28, 12) NULL CONSTRAINT "DF_QTYREMAINRECEIVE" DEFAULT 0,
[PURCHASEUNIT] [nvarchar](10) NULL,
    [INVENTBATCHID] [nvarchar](10) NULL,
[INVENTSITEID] [nvarchar](10) NULL,
[INVENTLOCATIONID] [nvarchar](20) NULL,
[CONFIGID] [nvarchar](10) NOT NULL,
[INVENTSERIALID] [nvarchar](10) NULL,
[INVENTSIZEID] [nvarchar](10) NOT NULL,
[INVENTCOLORID] [nvarchar](10) NOT NULL,
[INVENTSTYLEID] [nvarchar](10) NOT NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL,
 CONSTRAINT [PK_TRANSFERORDERLINE] PRIMARY KEY CLUSTERED
(
    [ORDERID],[RECID],[ITEMID],[CONFIGID],[INVENTCOLORID],[INVENTSIZEID],[INVENTSTYLEID]
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[TRANSFERORDERLINE]'
GO
-- End creating table [crt].[TRANSFERORDERLINE]

-- Creating table [crt].[PICKINGLISTLINE]
PRINT N'Creating table [crt].[PICKINGLISTLINE]';

GO
IF OBJECT_ID(N'[crt].[PICKINGLISTLINE]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[PICKINGLISTLINE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[PICKINGLISTLINE](
[RECID] [nvarchar](50) NOT NULL,
    [ORDERID] [nvarchar](50) NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [ITEMNAME] [nvarchar](60) NULL,
[INVENTDIMID] [nvarchar](20) NULL,
    [PURCHASERECEIVEDNOW] [numeric](28, 12) NULL CONSTRAINT "DF_PURCHASERECEIVEDNOWQTY" DEFAULT 0,
    [INVENTBATCHID] [nvarchar](10) NULL,
[INVENTSITEID] [nvarchar](10) NULL,
[INVENTLOCATIONID] [nvarchar](20) NULL,
[CONFIGID] [nvarchar](10) NULL,
[INVENTSERIALID] [nvarchar](10) NULL,
[INVENTSIZEID] [nvarchar](10) NULL,
[INVENTCOLORID] [nvarchar](10) NULL,
[INVENTSTYLEID] [nvarchar](10) NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL,
 CONSTRAINT [PK_PICKINGLISTLINE] PRIMARY KEY CLUSTERED
(
    [ORDERID],[RECID]
)
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[PICKINGLISTLINE]'
GO
-- End creating table [crt].[PICKINGLISTLINE]

-- Creating table [crt].[RETAILCUSTOMEREMAILACTIVATION]
PRINT N'Creating table [crt].[RETAILCUSTOMEREMAILACTIVATION]';

GO
IF OBJECT_ID(N'[crt].[RETAILCUSTOMEREMAILACTIVATION]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILCUSTOMEREMAILACTIVATION] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILCUSTOMEREMAILACTIVATION]
(
    [ACTIVATIONID] [uniqueidentifier] DEFAULT NEWSEQUENTIALID() NOT NULL,
    [EMAIL] [nvarchar](100) NOT NULL,
    [LASTMODIFIEDTIME] [datetime] NOT NULL,
    [STATUS] [int] NOT NULL,

    CONSTRAINT [PK_RETAILCUSTOMEREMAILACTIVATION] PRIMARY KEY CLUSTERED
    (
        [ACTIVATIONID] ASC
    ) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILCUSTOMEREMAILACTIVATION]'
GO
-- End creating table [crt].[RETAILCUSTOMEREMAILACTIVATION]



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[RETAILCUSTOMEREMAILACTIVATION]', N'U'), N'IX_RETAILCUSTOMEREMAILACTIVATION_GROUPS', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILCUSTOMEREMAILACTIVATION_GROUPS'


CREATE NONCLUSTERED INDEX IX_RETAILCUSTOMEREMAILACTIVATION_GROUPS
    ON [crt].[RETAILCUSTOMEREMAILACTIVATION]
    (
    ACTIVATIONID,
        EMAIL,
LASTMODIFIEDTIME,
        STATUS
    )


END
ELSE
    PRINT 'Existing index IX_RETAILCUSTOMEREMAILACTIVATION_GROUPS'

-- Creating table [crt].[RETAILSTAFFLOGINLOG]
PRINT N'Creating table [crt].[RETAILSTAFFLOGINLOG]';

GO
IF OBJECT_ID(N'[crt].[RETAILSTAFFLOGINLOG]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [crt].[RETAILSTAFFLOGINLOG] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [crt].[RETAILSTAFFLOGINLOG](
[CHANNELID] [nvarchar](10) NOT NULL,
[TERMINALID] [nvarchar](10) NOT NULL,
[STAFFID] [nvarchar](25) NOT NULL,
[DATAAREAID] [nvarchar](4) NOT NULL,
[CREATEDDATETIME] [datetime] NOT NULL,
    
    CONSTRAINT [PK_RETAILSTAFFLOGINLOG] PRIMARY KEY CLUSTERED 
(
[DATAAREAID] ASC,
[CHANNELID] ASC,
[TERMINALID] ASC,
[STAFFID] ASC
) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [crt].[RETAILSTAFFLOGINLOG]'
GO
-- End creating table [crt].[RETAILSTAFFLOGINLOG]



-- from data managers
GRANT SELECT ON [crt].[RETAILCHANNELPROPERTIES] TO [PublishersRole];
GO

GRANT SELECT ON [crt].[SALESTRANSACTION] TO [UsersRole];
GO

GRANT SELECT ON [crt].[WISHLIST] TO [UsersRole];
GO

GRANT SELECT ON [ax].[INVENTLOCATION] TO [UsersRole];
GO

GRANT SELECT, INSERT, UPDATE ON [crt].[RETAILCATALOGPUBLISHINGSYNCSTATE] TO [PublishersRole];
GO

GRANT SELECT, INSERT ON [ax].[RETAILLISTINGSTATUSLOG] TO [PublishersRole];
GO

-- ALTER is needed for TRUNCATE TABLE inside of sproc STORECATALOGDEFINITION
GRANT ALTER, SELECT, INSERT ON [crt].[CATALOGDEFINITION] TO [PublishersRole];
GO

GRANT SELECT, INSERT ON [crt].[CATALOGLISTMAPPING] TO [PublishersRole];
GO

-- Creating table [ax].[RETAILMANUALCHANGESLOG_BR]
PRINT N'Creating table [ax].[RETAILMANUALCHANGESLOG_BR]';

GO
IF OBJECT_ID(N'[ax].[RETAILMANUALCHANGESLOG_BR]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [ax].[RETAILMANUALCHANGESLOG_BR] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [ax].[RETAILMANUALCHANGESLOG_BR](
    [TABLENAME] [nvarchar](50) NOT NULL,
    [PRIMARYKEY] [nvarchar](200) NOT NULL,
    [APPLICATION] [nvarchar](128) NOT NULL

CONSTRAINT [PK_RETAILMANUALCHANGESLOG] PRIMARY KEY CLUSTERED
(
[TABLENAME] ASC,
[PRIMARYKEY] ASC
) ON [PRIMARY]
) ON [PRIMARY]


END
GO
PRINT N'Finished creating table [ax].[RETAILMANUALCHANGESLOG_BR]'
GO
-- End creating table [ax].[RETAILMANUALCHANGESLOG_BR]

-- Creating scalar function [crt].[GETCATEGORYPATH]
PRINT N'Creating scalar function [crt].[GETCATEGORYPATH]';

GO
IF OBJECT_ID(N'[crt].[GETCATEGORYPATH]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATEGORYPATH] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETCATEGORYPATH].'
GO


ALTER FUNCTION [crt].GETCATEGORYPATH 
(
    @bi_ChannelId BIGINT,
@bi_CategoryId BIGINT
)
RETURNS NVARCHAR(MAX)
BEGIN
    DECLARE @BUFFER NVARCHAR(MAX)
DECLARE @CATEGORYHIERARCHY BIGINT 
DECLARE @NESTEDSETLEFT BIGINT 
DECLARE @NESTEDSETRIGHT BIGINT 
DECLARE @CURRENTCATEGORYNAME NVARCHAR(254) 

-- INITIALIZING FOR TOP-LEVEL CATEGORIES, OTHERWISE COALESCE WILL NOT RETURN PROPER RESULT
SET @BUFFER = N'';

SELECT @CATEGORYHIERARCHY =  RPERC.CATEGORYHIERARCHY , 
   @NESTEDSETLEFT = RPERC.NESTEDSETLEFT, 
   @NESTEDSETRIGHT = RPERC.NESTEDSETRIGHT,
   @CURRENTCATEGORYNAME = RPERC.NAME
   FROM [ax].RETAILPUBECORESCATEGORY RPERC 
   WHERE RPERC.CHANNEL = @bi_ChannelId AND RPERC.ORIGINID = @bi_CategoryId

SELECT @BUFFER = COALESCE(@BUFFER + '/' + ERC.NAME, ERC.NAME) 
FROM [ax].ECORESCATEGORY ERC
WHERE ERC.CATEGORYHIERARCHY = @CATEGORYHIERARCHY
                        AND ERC.NESTEDSETLEFT  < @NESTEDSETLEFT
                        AND ERC.NESTEDSETRIGHT > @NESTEDSETRIGHT
ORDER BY ERC.NESTEDSETLEFT 

-- APPEND CURRENT CATEGORY NAME
SELECT @BUFFER = COALESCE(@BUFFER + '/' + @CURRENTCATEGORYNAME, @BUFFER) 
            
    RETURN @BUFFER
END


GO
PRINT N'Finished creating scalar function [crt].[GETCATEGORYPATH]'
-- End creating scalar function [crt].[GETCATEGORYPATH]


GRANT EXECUTE ON [crt].[GETCATEGORYPATH] TO [UsersRole];
GO

-- Creating scalar function [crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE]
PRINT N'Creating scalar function [crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE].'
GO


ALTER FUNCTION [crt].GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE ()
RETURNS nvarchar(1999)
BEGIN
    DECLARE @IMAGE nvarchar(1999);

SELECT  TOP 1 @IMAGE = ERTV.TEXTVALUE
    FROM ax.RETAILSHAREDPARAMETERS RSP 
INNER JOIN ax.ECORESATTRIBUTEGROUPATTRIBUTE AGA on RSP.WORKERDEFAULTATTRIBUTEGROUP = AGA.ATTRIBUTEGROUP
INNER JOIN ax.ECORESATTRIBUTE ERA on ERA.RECID = AGA.ATTRIBUTE AND ERA.ATTRIBUTETYPE = RSP.IMAGESATTRIBUTETYPE
INNER JOIN ax.ECORESTEXTVALUE ERTV on AGA.DEFAULTVALUE = ERTV.RECID
WHERE RSP.[KEY] = 0
            
    RETURN ISNULL(@IMAGE, '');
END


GO
PRINT N'Finished creating scalar function [crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE]'
-- End creating scalar function [crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE]


GRANT EXECUTE ON [crt].[GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE] TO [UsersRole];
GO

-- Creating scalar function [crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE]
PRINT N'Creating scalar function [crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE].'
GO


ALTER FUNCTION [crt].GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE ()
RETURNS nvarchar(1999)
BEGIN
    DECLARE @IMAGE nvarchar(1999);

    SELECT  TOP 1 @IMAGE = ERTV.TEXTVALUE
FROM ax.RETAILSHAREDPARAMETERS RSP 
INNER JOIN ax.ECORESATTRIBUTEGROUPATTRIBUTE AGA on RSP.CATALOGDEFAULTATTRIBUTEGROUP = AGA.ATTRIBUTEGROUP
INNER JOIN ax.ECORESATTRIBUTE ERA on ERA.RECID = AGA.ATTRIBUTE AND ERA.ATTRIBUTETYPE = RSP.IMAGESATTRIBUTETYPE
INNER JOIN ax.ECORESTEXTVALUE ERTV on AGA.DEFAULTVALUE = ERTV.RECID
WHERE RSP.[KEY] = 0
            
    RETURN ISNULL(@IMAGE, '');
END


GO
PRINT N'Finished creating scalar function [crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE]'
-- End creating scalar function [crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE]


GRANT EXECUTE ON [crt].[GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE] TO [UsersRole];
GO

-- Creating scalar function [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE]
PRINT N'Creating scalar function [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE].'
GO


ALTER FUNCTION [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE] ()
RETURNS nvarchar(1999)
BEGIN
    DECLARE @IMAGE nvarchar(1999);

SELECT  TOP 1 @IMAGE = ERTV.TEXTVALUE
    FROM ax.RETAILSHAREDPARAMETERS RSP 
INNER JOIN ax.ECORESATTRIBUTEGROUPATTRIBUTE AGA on RSP.CUSTOMERDEFAULTATTRIBUTEGROUP = AGA.ATTRIBUTEGROUP
INNER JOIN ax.ECORESATTRIBUTE ERA on ERA.RECID = AGA.ATTRIBUTE AND ERA.ATTRIBUTETYPE = RSP.IMAGESATTRIBUTETYPE
INNER JOIN ax.ECORESTEXTVALUE ERTV on AGA.DEFAULTVALUE = ERTV.RECID
WHERE RSP.[KEY] = 0
            
    RETURN ISNULL(@IMAGE, '');
END


GO
PRINT N'Finished creating scalar function [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE]'
-- End creating scalar function [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE]


GRANT EXECUTE ON [crt].[GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE] TO [UsersRole];
GO

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND NOT EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = 'COMMERCEFULLTEXTCATALOG')
BEGIN
    PRINT 'Creating fulltext catalog COMMERCEFULLTEXTCATALOG'


CREATE FULLTEXT CATALOG COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the fulltext catalog COMMERCEFULLTEXTCATALOG already exists'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].DIRPARTYTABLE'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].DIRPARTYTABLE'


CREATE FULLTEXT INDEX
ON [ax].DIRPARTYTABLE (NAME) KEY INDEX [I_-747565321_RECID] 
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].DIRPARTYTABLE already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].RETAILTRANSACTIONADDRESSTRANS'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].RETAILTRANSACTIONADDRESSTRANS'


CREATE FULLTEXT INDEX
ON [ax].RETAILTRANSACTIONADDRESSTRANS (DELIVERYNAME) KEY INDEX [UI_RETAILTRANSACTIONADDRESSTRANS_REPLICATIONCOUNTERFROMORIGIN] 
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].RETAILTRANSACTIONADDRESSTRANS already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].ECORESCOLOR'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].ECORESCOLOR'


CREATE FULLTEXT INDEX
ON [ax].ECORESCOLOR (NAME) KEY INDEX [I_1935030618_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].ECORESCOLOR already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].ECORESCONFIGURATION'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].ECORESCONFIGURATION'


CREATE FULLTEXT INDEX
ON [ax].ECORESCONFIGURATION (NAME) KEY INDEX [I_1043434429_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].ECORESCONFIGURATION already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].ECORESPRODUCT'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].ECORESPRODUCT'


CREATE FULLTEXT INDEX
ON [ax].ECORESPRODUCT (SEARCHNAME, DISPLAYPRODUCTNUMBER) KEY INDEX [I_-441108210_RECID]
ON COMMERCEFULLTEXTCATALOG 


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].ECORESPRODUCT already has fulltext index.'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESPRODUCTTRANSLATION]', N'U'), N'IX_ECORESPRODUCTTRANSLATION_PRODUCT_TRANSLATION', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESPRODUCTTRANSLATION_PRODUCT_TRANSLATION'


CREATE NONCLUSTERED INDEX IX_ECORESPRODUCTTRANSLATION_PRODUCT_TRANSLATION ON [ax].[ECORESPRODUCTTRANSLATION]
(
    [PRODUCT] ASC,
    [LANGUAGEID] ASC
)
INCLUDE
(
    [DESCRIPTION],
    [NAME]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESPRODUCTTRANSLATION_PRODUCT_TRANSLATION'


IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].ECORESPRODUCTTRANSLATION'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].ECORESPRODUCTTRANSLATION'


CREATE FULLTEXT INDEX
ON [ax].ECORESPRODUCTTRANSLATION ([NAME], [DESCRIPTION]) KEY INDEX [I_-1618573415_RECID]
ON COMMERCEFULLTEXTCATALOG 


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].ECORESPRODUCTTRANSLATION already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].ECORESSIZE'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].ECORESSIZE'


CREATE FULLTEXT INDEX
ON [ax].ECORESSIZE (NAME) KEY INDEX [I_357393082_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].ECORESSIZE already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].ECORESSTYLE'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].ECORESSTYLE'


CREATE FULLTEXT INDEX
ON [ax].ECORESSTYLE (NAME) KEY INDEX [I_967371264_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].ECORESSTYLE already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].ECORESTEXTVALUE'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].ECORESTEXTVALUE'


CREATE FULLTEXT INDEX
ON [ax].ECORESTEXTVALUE (TEXTVALUE) KEY INDEX [I_1324545795_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].ECORESTEXTVALUE already has fulltext index.'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLE]', N'U'), N'IX_INVENTTABLE_PRODUCT_DATAAREAID_ITEM', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLE_PRODUCT_DATAAREAID_ITEM'


CREATE NONCLUSTERED INDEX [IX_INVENTTABLE_PRODUCT_DATAAREAID_ITEM] ON [ax].[INVENTTABLE]
(
    [PRODUCT] ASC,
    [DATAAREAID] ASC,
    [ITEMID] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTTABLE_PRODUCT_DATAAREAID_ITEM'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLE]', N'U'), N'IX_INVENTTABLE_PRODUCT', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLE_PRODUCT'


CREATE NONCLUSTERED INDEX [IX_INVENTTABLE_PRODUCT] ON [ax].[INVENTTABLE]
(
    [PRODUCT] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTTABLE_PRODUCT'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLE]', N'U'), N'IX_INVENTTABLE_ITEMID_DATAAREAID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLE_ITEMID_DATAAREAID'


CREATE NONCLUSTERED INDEX [IX_INVENTTABLE_ITEMID_DATAAREAID] ON [ax].[INVENTTABLE]
(
    [ITEMID] ASC,
    [DATAAREAID] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTTABLE_ITEMID_DATAAREAID'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLE]', N'U'), N'IX_INVENTTABLE_RECID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLE_RECID'


CREATE UNIQUE NONCLUSTERED INDEX [IX_INVENTTABLE_RECID] ON [ax].[INVENTTABLE]
(
    RECID ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTTABLE_RECID'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].[INVENTTABLE]'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].[INVENTTABLE]'


CREATE FULLTEXT INDEX
ON [ax].INVENTTABLE (ITEMID) KEY INDEX [IX_INVENTTABLE_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].[INVENTTABLE] already has fulltext index.'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILLOYALTYCARD]', N'U'), N'IX_RETAILLOYALTYCARD_RECID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILLOYALTYCARD_RECID'


CREATE UNIQUE NONCLUSTERED INDEX [IX_RETAILLOYALTYCARD_RECID] ON [ax].[RETAILLOYALTYCARD]
(
    RECID ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILLOYALTYCARD_RECID'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].[RETAILLOYALTYCARD]'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].[RETAILLOYALTYCARD]'


CREATE FULLTEXT INDEX
ON [ax].RETAILLOYALTYCARD (CARDNUMBER) KEY INDEX [IX_RETAILLOYALTYCARD_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].[RETAILLOYALTYCARD] already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].LOGISTICSPOSTALADDRESS'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].LOGISTICSPOSTALADDRESS'


CREATE FULLTEXT INDEX
ON [ax].LOGISTICSPOSTALADDRESS (ADDRESS) KEY INDEX [I_621354382_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].LOGISTICSPOSTALADDRESS already has fulltext index.'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[CUSTTABLE]', N'U'), N'IX_CUSTTABLE_RECID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_CUSTTABLE_RECID'


CREATE UNIQUE NONCLUSTERED INDEX [IX_CUSTTABLE_RECID] ON [ax].[CUSTTABLE]
(
    RECID ASC
)
INCLUDE
(
[PARTY]
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_CUSTTABLE_RECID'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].[CUSTTABLE]'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].[CUSTTABLE]'


CREATE FULLTEXT INDEX
ON [ax].CUSTTABLE (ACCOUNTNUM) KEY INDEX [IX_CUSTTABLE_RECID]
ON COMMERCEFULLTEXTCATALOG 


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].[CUSTTABLE] already has fulltext index.'

IF ((SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) = 1) AND EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = N'COMMERCEFULLTEXTCATALOG') AND NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(N'[ax].LOGISTICSELECTRONICADDRESS'))
BEGIN
    PRINT 'Adding fulltext index to table [ax].LOGISTICSELECTRONICADDRESS'


CREATE FULLTEXT INDEX
ON [ax].LOGISTICSELECTRONICADDRESS (LOCATOR) KEY INDEX [I_1137359931_RECID]
ON COMMERCEFULLTEXTCATALOG


END
ELSE
    PRINT 'The Full Text Search is not installed or the catalog COMMERCEFULLTEXTCATALOG does not exist or the table [ax].LOGISTICSELECTRONICADDRESS already has fulltext index.'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBECORESCATEGORY]', N'U'), N'IX_RETAILPUBECORESCATEGORY_CHANNELORIGINID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBECORESCATEGORY_CHANNELORIGINID'


CREATE NONCLUSTERED INDEX IX_RETAILPUBECORESCATEGORY_CHANNELORIGINID ON [ax].[RETAILPUBECORESCATEGORY] 
(
    CHANNEL,
ORIGINID
)
INCLUDE 
(
    CATEGORYHIERARCHY,
NESTEDSETLEFT,
NESTEDSETRIGHT,
NAME
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBECORESCATEGORY_CHANNELORIGINID'
/* BEGIN SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this)

IF OBJECT_ID(N'[ax].[RETAILCUSTPREFERENCE]', N'U') IS NOT NULL
BEGIN
    PRINT N'Table [ax].[RETAILCUSTPREFERENCE] already exists, Creation has been skipped.'
END
ELSE
BEGIN

CREATE TABLE [ax].[RETAILCUSTPREFERENCE](
[DATAAREAID] [nvarchar](4) NOT NULL,
[RECID] [bigint] NOT NULL,
[EMAILOPTIN] [int] DEFAULT ((0)) NOT NULL,
[ACCOUNTNUM] [nvarchar](20) NOT NULL,
 CONSTRAINT [PK_RETAILCUSTPREFERENCE] PRIMARY KEY CLUSTERED 
(
[RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

END


END SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this) */
GO

-- Creating view [crt].[ATTRIBUTEMAPVIEW]
PRINT N'Creating view [crt].[ATTRIBUTEMAPVIEW]';

GO
IF OBJECT_ID(N'[crt].[ATTRIBUTEMAPVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ATTRIBUTEMAPVIEW]
GO

CREATE VIEW [crt].[ATTRIBUTEMAPVIEW] AS
(
--non-ref attribute case
SELECT  ERA.RECID AS ACTUALATTRIBUTE, 
ERA.RECID AS ATTRIBUTE
FROM [ax].ECORESATTRIBUTE ERA
INNER JOIN [ax].ECORESATTRIBUTETYPE ERAT ON ERAT.RECID = ERA.ATTRIBUTETYPE
WHERE ERAT.DATATYPE != 20 --  20 = REFEFENCE ATTRIBUTE TYPE


UNION ALL 

-- ref. Attribute case
SELECT  ERRV.REFRECID AS REFERENCEDATTRIBUTE, 
ERA.RECID AS ATTRIBUTEID 
FROM [ax].ECORESATTRIBUTE ERA
INNER JOIN [ax].ECORESATTRIBUTETYPE ERAT ON ERAT.RECID = ERA.ATTRIBUTETYPE
INNER JOIN [ax].ECORESATTRIBUTEDEFAULTVALUE ERADV ON ERA.RECID = ERADV.ATTRIBUTE
INNER JOIN [ax].ECORESREFERENCEVALUE ERRV ON ERRV.RECID = ERADV.VALUE
WHERE ERAT.DATATYPE = 20 --  20 = REFEFENCE ATTRIBUTE TYPE
)
GO

GO
PRINT N'Finished creating view [crt].[ATTRIBUTEMAPVIEW]'
GO
-- End creating view [crt].[ATTRIBUTEMAPVIEW]


GRANT SELECT ON [crt].[ATTRIBUTEMAPVIEW] TO [UsersRole];
GO

-- Creating view [crt].[BUTTONGRIDSVIEW]
PRINT N'Creating view [crt].[BUTTONGRIDSVIEW]';

GO
IF OBJECT_ID(N'[crt].[BUTTONGRIDSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[BUTTONGRIDSVIEW]
GO

CREATE VIEW [crt].[BUTTONGRIDSVIEW] AS
(
    SELECT
        bg.[BUTTONGRIDID],
        bg.[DEFAULTCOLOR],
        bg.[NAME],
bg.[RECID],
        bg.[SPACEBETWEENBUTTONS]
    FROM [ax].[RETAILBUTTONGRID] bg
)


GO
PRINT N'Finished creating view [crt].[BUTTONGRIDSVIEW]'
GO
-- End creating view [crt].[BUTTONGRIDSVIEW]


GRANT SELECT ON [crt].[BUTTONGRIDSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[BUTTONGRIDBUTTONSVIEW]
PRINT N'Creating view [crt].[BUTTONGRIDBUTTONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[BUTTONGRIDBUTTONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[BUTTONGRIDBUTTONSVIEW]
GO

CREATE VIEW [crt].[BUTTONGRIDBUTTONSVIEW] AS
(
    SELECT
        bgb.[ACTION],
        bgb.[ACTIONPROPERTY],
bgb.[BUTTONGRIDID],
        bgb.[BACKCOLOR],
        bgb.[BORDERCOLOR],
bgb.[COL],
bgb.[COLSPAN],
bgb.[DISPLAYTEXT],
bgb.[FONTCOLOR],
bgb.[ID],
bgb.[RECID],
bgb.[ROWNUM],
bgb.[ROWSPAN],
bgb.[USECUSTOMLOOKANDFEEL],
bgb.[PICTUREID],
rim.[PICTURE]
    FROM [ax].[RETAILBUTTONGRIDBUTTONS] bgb
LEFT JOIN [ax].[RETAILIMAGES] rim on bgb.[PICTUREID] = rim.[PICTUREID]
)


GO
PRINT N'Finished creating view [crt].[BUTTONGRIDBUTTONSVIEW]'
GO
-- End creating view [crt].[BUTTONGRIDBUTTONSVIEW]


GRANT SELECT ON [crt].[BUTTONGRIDBUTTONSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[STORAGELOOKUPVIEW]
PRINT N'Creating view [crt].[STORAGELOOKUPVIEW]';

GO
IF OBJECT_ID(N'[crt].[STORAGELOOKUPVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[STORAGELOOKUPVIEW]
GO

CREATE VIEW [crt].[STORAGELOOKUPVIEW] AS
(
    SELECT
        dp.[NAME],
        rctx.[CHANNEL] AS 'CHANNELID',
        om.[OMOPERATINGUNITNUMBER] AS 'OPERATINGUNITNUMBER',
        db.[SERVER],
        db.[DATABASE],
        CASE
            WHEN ([rpct].RECID IS NULL) THEN 0
            ELSE 1
        END AS 'ISPUBLISHEDTOLOCAL',
        'Data Source=' + db.[SERVER] + ';Initial Catalog=' + db.[DATABASE] + ';Integrated Security=SSPI;' AS [CONNECTIONSTRING]
    FROM ax.RETAILCHANNELTABLEEXT rctx
    INNER JOIN [ax].[RETAILCONNDATABASEPROFILE] db ON db.RECID = rctx.LIVECHANNELDATABASE
    LEFT OUTER JOIN [ax].[RETAILCHANNELTABLE] rct ON rct.RECID = rctx.CHANNEL -- Left join is required for channels published to other DB.
    LEFT OUTER JOIN [ax].[OMOPERATINGUNIT] om ON om.RECID = rct.OMOPERATINGUNITID
    LEFT OUTER JOIN [ax].[DIRPARTYTABLE] dp ON dp.RECID = om.RECID
    LEFT OUTER JOIN [ax].[RETAILPUBRETAILCHANNELTABLE] rpct ON rpct.ORIGINID = rctx.CHANNEL
)


GO
PRINT N'Finished creating view [crt].[STORAGELOOKUPVIEW]'
GO
-- End creating view [crt].[STORAGELOOKUPVIEW]


GRANT SELECT ON [crt].[STORAGELOOKUPVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[STORAGELOOKUPVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[ASSORTEDPRODUCTSINNERVIEW]
PRINT N'Creating view [crt].[ASSORTEDPRODUCTSINNERVIEW]';

GO
IF OBJECT_ID(N'[crt].[ASSORTEDPRODUCTSINNERVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ASSORTEDPRODUCTSINNERVIEW]
GO

CREATE VIEW [crt].[ASSORTEDPRODUCTSINNERVIEW] WITH SCHEMABINDING AS
(
    SELECT
        rct.RECID AS 'CHANNELID',
        ral.PRODUCTID,
        ral.VARIANTID,
        ral.VALIDFROM,
        ral.VALIDTO,
        ral.LINETYPE,
        COUNT_BIG(*) AS LINECOUNT
    FROM [ax].RETAILASSORTMENTLOOKUP ral
    INNER JOIN [ax].RETAILASSORTMENTLOOKUPCHANNELGROUP ralcg on ralcg.ASSORTMENTID = ral.ASSORTMENTID
    INNER JOIN [ax].RETAILCHANNELTABLE rct on rct.OMOPERATINGUNITID = ralcg.OMOPERATINGUNITID -- Resolve OM to Channel
    INNER JOIN [ax].INVENTTABLE it on it.PRODUCT = ral.PRODUCTID and it.DATAAREAID = rct.INVENTLOCATIONDATAAREAID -- Include only Released items
    GROUP BY rct.RECID, ral.PRODUCTID, ral.VARIANTID, ral.VALIDFROM, ral.VALIDTO, ral.LINETYPE
)


GO
PRINT N'Finished creating view [crt].[ASSORTEDPRODUCTSINNERVIEW]'
GO
-- End creating view [crt].[ASSORTEDPRODUCTSINNERVIEW]


CREATE UNIQUE CLUSTERED INDEX I_ASSORTEDPRODUCTSINNERVIEW ON crt.ASSORTEDPRODUCTSINNERVIEW (CHANNELID, PRODUCTID, VARIANTID, VALIDFROM, VALIDTO, LINETYPE)
GO


-- Creating view [crt].[ASSORTEDPRODUCTSVIEW]
PRINT N'Creating view [crt].[ASSORTEDPRODUCTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[ASSORTEDPRODUCTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ASSORTEDPRODUCTSVIEW]
GO

CREATE VIEW [crt].[ASSORTEDPRODUCTSVIEW] AS
(
    ---!!!!!!!! If you are changing this view, make sure that the Filter*IdsByAssortment family of functions is also changed. !!!!!!


    SELECT
        CHANNELID,
        PRODUCTID,
        VARIANTID,
        VALIDFROM,
        VALIDTO
    FROM [crt].[ASSORTEDPRODUCTSINNERVIEW] WITH (NOEXPAND)
    GROUP BY CHANNELID, PRODUCTID, VARIANTID, VALIDFROM, VALIDTO
    HAVING MIN(LINETYPE) = 1 -- Remove excluded products

    UNION

    SELECT
        tap.CHANNELID,
        tap.PRODUCTID,
        0 AS 'VARIANTID',
        tap.VALIDFROM,
        tap.VALIDTO
    FROM [crt].TMPASSORTEDPRODUCTS tap
)


GO
PRINT N'Finished creating view [crt].[ASSORTEDPRODUCTSVIEW]'
GO
-- End creating view [crt].[ASSORTEDPRODUCTSVIEW]


GRANT SELECT ON [crt].[ASSORTEDPRODUCTSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[ASSORTEDPRODUCTSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[GETCUSTOMERGROUPSVIEW]
PRINT N'Creating view [crt].[GETCUSTOMERGROUPSVIEW]';

GO
IF OBJECT_ID(N'[crt].[GETCUSTOMERGROUPSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[GETCUSTOMERGROUPSVIEW]
GO

CREATE VIEW [crt].[GETCUSTOMERGROUPSVIEW] AS
(
    SELECT
        cg.[RECID],
        cg.[NAME],
        cg.[CUSTGROUP],
cg.[DATAAREAID]
    FROM [ax].CUSTGROUP cg
)


GO
PRINT N'Finished creating view [crt].[GETCUSTOMERGROUPSVIEW]'
GO
-- End creating view [crt].[GETCUSTOMERGROUPSVIEW]


GRANT SELECT ON [crt].[GETCUSTOMERGROUPSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CHANNELLANGUAGESVIEW]
PRINT N'Creating view [crt].[CHANNELLANGUAGESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELLANGUAGESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELLANGUAGESVIEW]
GO

CREATE VIEW [crt].[CHANNELLANGUAGESVIEW] AS
(
    SELECT
        rprcl.ISDEFAULT,
        rprcl.ONLINECHANNEL AS CHANNEL,
        rprcl.LANGUAGEID
    FROM [ax].[RETAILPUBRETAILONLINECHANNELLANGUAGES] rprcl

    UNION

    SELECT
        1 AS ISDEFAULT,
        rst.RECID AS CHANNEL,
        -- If the store does not have a language defined, use the language set on the store's legal entity.
        CASE
            WHEN ISNULL(rst.CULTURENAME, '') != '' THEN rst.CULTURENAME
            ELSE dp.LANGUAGEID
        END AS LANGUAGEID
    FROM [ax].[RETAILSTORETABLE] rst
    INNER JOIN [ax].RETAILCHANNELTABLE rct ON rct.RECID = rst.RECID
    INNER JOIN [ax].COMPANYINFO ci ON ci.DATAAREA = rct.INVENTLOCATIONDATAAREAID
    LEFT OUTER JOIN [ax].DIRPARTYTABLE dp ON dp.RECID = ci.RECID
)


GO
PRINT N'Finished creating view [crt].[CHANNELLANGUAGESVIEW]'
GO
-- End creating view [crt].[CHANNELLANGUAGESVIEW]


GRANT SELECT ON [crt].[CHANNELLANGUAGESVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELLANGUAGESVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELCONFIGURATIONVIEW]
PRINT N'Creating view [crt].[CHANNELCONFIGURATIONVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELCONFIGURATIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELCONFIGURATIONVIEW]
GO

CREATE VIEW [crt].[CHANNELCONFIGURATIONVIEW] AS
(
    SELECT
        [rct].[RECID],
        [rct].[CHANNELTYPE],
        [rct].[INVENTLOCATION],
        [rct].[INVENTLOCATIONDATAAREAID],
        [rct].[CURRENCY],
        [rct].[PRICEINCLUDESSALESTAX],
[l].ACCOUNTINGCURRENCY AS 'COMPANYCURRENCY',
        [lpa].[COUNTRYREGIONID],
        [lacr].[ISOCODE] AS 'COUNTRYREGIONISOCODE',
        [rsp].[EXCHANGERATETYPE],
        [rsp].[STAFFPASSWORDHASH],
        [rsp].[TSPASSWORDENCRYPTION],
        [rsp].[DEVICETOKENALGORITHM],
        [rsp].[EARNLOYALTYOFFLINE],
        [rtsp].[PROFILEID] AS 'TSPROFILEID',
        [rtsp].[LANGUAGE] AS 'TSLANGUAGEID',
        [rtsp].[TSSTAFF] AS 'TSSTAFFLOGONCONFIGURATION',
        [rtsp].[CENTRALTABLESERVER] AS 'TSHOST',
        [rtsp].[CENTRALTABLESERVERPORT] AS 'TSPORT',
        [rtsp].[RETAILTSDATA] AS 'TSENCRYPTEDPASSWORD',
        [rtsp].[SERVERCERTIFICATEDNS] AS 'TSSERVERCERTIFICATEDNS',
        [rtsp].[SERVERSERVICENAME] AS 'TSSERVICENAME',
        [rtsp].[PROTOCOL] AS 'TSPROTOCOL',
        [rtsp].[SECURITYOFF] AS 'TSSECURITYOFF',
        [rp].PICKUPDELIVERYMODECODE,
        [rp].ELECTRONICDELIVERYMODECODE,
        [rp].GIFTCARDITEM,
        [rp].CANCELLATIONCHARGE,
        [rp].CANCELLATIONCHARGECODE,
        [rp].EXPIRATIONDATE AS 'QUOTEEXPIRATIONDAYS',
        [rp].MINIMUMDEPOSITFORSALESORDER,
        [rp].SHIPPINGCHARGECODE,
        [rct].CHANNELTIMEZONEINFOID AS 'TIMEZONEINFOID',
        [clv].LANGUAGEID AS 'DEFAULTLANGUAGEID',
        [rsbp].[APIKEY] AS 'BINGAPIKEY',
        [lpa].VALIDFROM,
        [lpa].VALIDTO,
        [crt].GETCATALOGIMAGEATTRIBUTEDEFAULTVALUE() AS CATALOGDEFAULTIMAGETEMPLATE,
        [crt].GETEMPLOYEEIMAGEATTRIBUTEDEFAULTVALUE() AS EMPLOYEEDEFAULTIMAGETEMPLATE,
        [crt].GETCUSTOMERIMAGEATTRIBUTEDEFAULTVALUE() AS CUSTOMERDEFAULTIMAGETEMPLATE
    FROM [ax].RETAILCHANNELTABLE rct

    -- Get transaction service profile information
    INNER JOIN [ax].RETAILTRANSACTIONSERVICEPROFILE rtsp ON rct.TRANSACTIONSERVICEPROFILE = rtsp.PROFILEID

    -- Get the store's country/region
    INNER JOIN [ax].COMPANYINFO ci ON ci.DATAAREA = rct.INVENTLOCATIONDATAAREAID
INNER JOIN [ax].LEDGER l ON l.PRIMARYFORLEGALENTITY = ci.RECID
    INNER JOIN [ax].DIRPARTYLOCATION drl ON drl.ISPRIMARY = 1 AND drl.PARTY = ci.RECID
    INNER JOIN [ax].LOGISTICSPOSTALADDRESS lpa ON lpa.ISPRIVATE = 0 AND lpa.LOCATION = drl.LOCATION
    INNER JOIN [ax].LOGISTICSADDRESSCOUNTRYREGION lacr ON lacr.COUNTRYREGIONID = lpa.COUNTRYREGIONID

     -- Get the store's default language
    INNER JOIN [crt].CHANNELLANGUAGESVIEW clv ON clv.CHANNEL = rct.RECID AND clv.ISDEFAULT = 1
    INNER JOIN [ax].RETAILPARAMETERS rp ON rp.[KEY] = 0 AND rp.DATAAREAID = rct.INVENTLOCATIONDATAAREAID

    CROSS JOIN [ax].RETAILSHAREDPARAMETERS rsp

    LEFT JOIN [ax].RETAILSHAREDBINGPARAMETERS rsbp ON rsbp.[KEY] = 0
    WHERE rsp.[KEY] = 0
)


GO
PRINT N'Finished creating view [crt].[CHANNELCONFIGURATIONVIEW]'
GO
-- End creating view [crt].[CHANNELCONFIGURATIONVIEW]


GRANT SELECT ON [crt].[CHANNELCONFIGURATIONVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELCONFIGURATIONVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW]
PRINT N'Creating view [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW]';

GO
IF OBJECT_ID(N'[crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW]
GO

CREATE VIEW [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW] AS
(
    SELECT
        [rsp].[STAFFPASSWORDHASH],
        [rsp].[TSPASSWORDENCRYPTION],
        [rsp].[DEVICETOKENALGORITHM],
        [rtsp].[PROFILEID] AS 'TSPROFILEID',
        [rtsp].[LANGUAGE] AS 'TSLANGUAGEID',
        [rtsp].[TSSTAFF] AS 'TSSTAFFLOGINCONFIGURATION',
        [rtsp].[CENTRALTABLESERVER] AS 'TSHOST',
        [rtsp].[CENTRALTABLESERVERPORT] AS 'TSPORT',
        [rtsp].[RETAILTSDATA] AS 'TSENCRYPTEDPASSWORD',
        [rtsp].[SERVERCERTIFICATEDNS] AS 'TSSERVERCERTIFICATEDNS',
        [rtsp].[SERVERSERVICENAME] AS 'TSSERVICENAME',
        [rtsp].[PROTOCOL] AS 'TSPROTOCOL',
        [rtsp].[SECURITYOFF] AS 'TSSECURITYOFF'
    FROM [ax].RETAILTRANSACTIONSERVICEPROFILE rtsp 
    INNER JOIN [ax].RETAILSHAREDPARAMETERS rsp ON rtsp.PROFILEID = rsp.TRANSACTIONSERVICEPROFILE
)


GO
PRINT N'Finished creating view [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW]'
GO
-- End creating view [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW]


GRANT SELECT ON [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[DEFAULTTRANSACTIONSERVICEPROFILEVIEW] TO [PublishersRole];
GO


-- Creating view [crt].[ITEMSPRICEVIEW]
PRINT N'Creating view [crt].[ITEMSPRICEVIEW]';

GO
IF OBJECT_ID(N'[crt].[ITEMSPRICEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ITEMSPRICEVIEW]
GO

CREATE VIEW [crt].[ITEMSPRICEVIEW] AS

(

    SELECT DISTINCT

        it.[RECID],       

        it.[ITEMID],      

        itm.[PRICE],

        itm.[UNITID],

        it.[PRODUCT],

        it.[DATAAREAID],

        itm.[MARKUPGROUPID],

        itm.[MARKUP],

        itm.[ALLOCATEMARKUP],

        itm.[PRICEQTY],

        itm.[LINEDISC],

        itm.[MULTILINEDISC],

        itm.[ENDDISC],

        rit.[NODISCOUNTALLOWED],

        itm.[TAXITEMGROUPID] AS 'ITEMTAXGROUPID'     

    FROM [ax].INVENTTABLE it      

    INNER JOIN [ax].INVENTTABLEMODULE itm ON itm.MODULETYPE = 2 AND itm.ITEMID = it.ITEMID AND itm.DATAAREAID = it.DATAAREAID 

    INNER JOIN [ax].RETAILINVENTTABLE rit ON it.ITEMID = rit.ITEMID AND rit.DATAAREAID = it.DATAAREAID   

)


GO
PRINT N'Finished creating view [crt].[ITEMSPRICEVIEW]'
GO
-- End creating view [crt].[ITEMSPRICEVIEW]


GRANT SELECT ON [crt].[ITEMSPRICEVIEW] TO [UsersRole];

GO



-- Creating view [crt].[PAYMENTCONNECTORVIEW]
PRINT N'Creating view [crt].[PAYMENTCONNECTORVIEW]';

GO
IF OBJECT_ID(N'[crt].[PAYMENTCONNECTORVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PAYMENTCONNECTORVIEW]
GO

CREATE VIEW [crt].[PAYMENTCONNECTORVIEW] AS
(
    SELECT
       rcpcl.[RECID],
       rcpcl.[PAYMENTCONNECTORNAME] AS NAME,
       rcpcl.[PAYMENTCONNECTORPROPERTIES] AS PROPERTIES,
       rcpcl.[ONLINECHANNEL],
       rcpcl.[ISTESTMODE]
    FROM [ax].RETAILCHANNELPAYMENTCONNECTORLINE rcpcl
)


GO
PRINT N'Finished creating view [crt].[PAYMENTCONNECTORVIEW]'
GO
-- End creating view [crt].[PAYMENTCONNECTORVIEW]


GRANT SELECT ON [crt].[PAYMENTCONNECTORVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PAYMENTCONNECTORVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[TERMINALPAYMENTCONNECTORVIEW]
PRINT N'Creating view [crt].[TERMINALPAYMENTCONNECTORVIEW]';

GO
IF OBJECT_ID(N'[crt].[TERMINALPAYMENTCONNECTORVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TERMINALPAYMENTCONNECTORVIEW]
GO

CREATE VIEW [crt].[TERMINALPAYMENTCONNECTORVIEW] AS
(
    SELECT
       0 AS RECID
       ,rhp.[EFTCONNECTORNAME] AS NAME
       ,rhp.[EFTCONNECTORPROPERTIES] AS PROPERTIES
       ,rt.[TERMINALID]
       ,rhp.[EFTTESTMODE] AS ISTESTMODE
    FROM [ax].RETAILTERMINALTABLE rt
    INNER JOIN [ax].RETAILHARDWAREPROFILE rhp ON rt.HARDWAREPROFILE = rhp.PROFILEID
)


GO
PRINT N'Finished creating view [crt].[TERMINALPAYMENTCONNECTORVIEW]'
GO
-- End creating view [crt].[TERMINALPAYMENTCONNECTORVIEW]


GRANT SELECT ON [crt].[TERMINALPAYMENTCONNECTORVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[TERMINALPAYMENTCONNECTORVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHARGESVIEW]
PRINT N'Creating view [crt].[CHARGESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHARGESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHARGESVIEW]
GO

CREATE VIEW [crt].[CHARGESVIEW] AS
(
    SELECT
mt.RECID,
        mt.MARKUPCODE,
mt.MODULETYPE,
        mt.TAXITEMGROUP AS ITEMTAXGROUPID,
mt.DATAAREAID
    FROM [ax].MARKUPTABLE AS mt
)


GO
PRINT N'Finished creating view [crt].[CHARGESVIEW]'
GO
-- End creating view [crt].[CHARGESVIEW]


GRANT SELECT ON [crt].[CHARGESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILSPECIALCATEGORYVARIANTVIEW]
PRINT N'Creating view [crt].[RETAILSPECIALCATEGORYVARIANTVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILSPECIALCATEGORYVARIANTVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILSPECIALCATEGORYVARIANTVIEW]
GO

-- Similar to RETAILSPECIALCATEGORYPRODUCT view from AX BUT shows all special
-- categories associated with each variants.
CREATE VIEW [crt].[RETAILSPECIALCATEGORYVARIANTVIEW] AS
(
    SELECT
       T3.RECID AS PRODUCT,
       T1.CATEGORY AS CATEGORY
    FROM [ax].RETAILSPECIALCATEGORYMEMBER AS T1
    INNER JOIN [ax].RETAILGROUPMEMBERLINE AS T2 ON T2.RECID = T1.RETAILGROUPMEMBER
    INNER JOIN [ax].ECORESPRODUCT AS T3 ON T3.RECID = T2.VARIANT
)


GO
PRINT N'Finished creating view [crt].[RETAILSPECIALCATEGORYVARIANTVIEW]'
GO
-- End creating view [crt].[RETAILSPECIALCATEGORYVARIANTVIEW]


GRANT SELECT ON [crt].[RETAILSPECIALCATEGORYVARIANTVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW]
PRINT N'Creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW]
GO

-- Shows products in retail category hierarchy and all special category hierarchies
CREATE VIEW [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW] AS
(
    SELECT
       T1.CATEGORY AS CATEGORY,
       T1.PRODUCT AS PRODUCT
    FROM [ax].[ECORESPRODUCTCATEGORY] T1

    UNION

SELECT
T1.CATEGORY AS CATEGORY,
T2.RECID AS PRODUCT
    FROM [ax].[ECORESPRODUCTCATEGORY] T1
    INNER JOIN [ax].[ECORESDISTINCTPRODUCTVARIANT] T2
    ON T2.PRODUCTMASTER = T1.PRODUCT

    UNION

    SELECT
       T1.CATEGORY,
       T1.PRODUCT
    FROM [crt].[RETAILSPECIALCATEGORYVARIANTVIEW] T1
)


GO
PRINT N'Finished creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW]'
GO
-- End creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW]


GRANT SELECT ON [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW]
PRINT N'Creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW]
GO

-- Shows all categories and ancestors for a given product/variant.
CREATE VIEW [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW] AS
(
    SELECT
       RPC.PRODUCT,
       RCCL.CATEGORY
    FROM [crt].[RETAILPRODUCTORVARIANTCATEGORYVIEW] RPC
    INNER JOIN [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] RCCL ON RCCL.CONTAINEDCATEGORY = RPC.CATEGORY
)


GO
PRINT N'Finished creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW]'
GO
-- End creating view [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW]


GRANT SELECT ON [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[MARKUPAUTOCONFIGURATIONVIEW]
PRINT N'Creating view [crt].[MARKUPAUTOCONFIGURATIONVIEW]';

GO
IF OBJECT_ID(N'[crt].[MARKUPAUTOCONFIGURATIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[MARKUPAUTOCONFIGURATIONVIEW]
GO

CREATE VIEW [crt].[MARKUPAUTOCONFIGURATIONVIEW] AS
(
    SELECT
        mat.RECID AS CHARGEID,
        mat.MODULECATEGORY,
        mat.MODULETYPE,
        mat.ACCOUNTCODE,
        mat.ACCOUNTRELATION,
        mat.ITEMCODE,
        mat.ITEMRELATION,
        mat.DLVMODECODE,
        mat.DLVMODERELATION,
        mal.VALUE,
        mal.CURRENCYCODE,
        mal.KEEP,
        mt.MARKUPCODE,
        mal.MARKUPCATEGORY AS MARKUPMETHOD,
        mal.TAXGROUP AS SALESTAXGROUP,
        mt.TAXITEMGROUP AS ITEMTAXGROUP,
        mal.FROMAMOUNT,
        mal.TOAMOUNT,
        mal.RECID,
        mat.DATAAREAID
    FROM [ax].MARKUPAUTOTABLE AS mat
    INNER JOIN [ax].MARKUPAUTOLINE AS mal
        -- join where auto charge lines point to autocharge table
        ON 227 = mal.TABLETABLEID AND mat.RECID = mal.TABLERECID AND mal.DATAAREAID = mat.DATAAREAID
    INNER JOIN [ax].MARKUPTABLE AS mt
        -- join to charge code to get charge code tax group
        ON mal.MARKUPCODE = mt.MARKUPCODE AND mal.MODULETYPE = mt.MODULETYPE AND mal.DATAAREAID = mt.DATAAREAID
    -- only fetch sales and delivery charges
    WHERE (mat.MODULETYPE = 1 OR mat.MODULETYPE = 3)
)


GO
PRINT N'Finished creating view [crt].[MARKUPAUTOCONFIGURATIONVIEW]'
GO
-- End creating view [crt].[MARKUPAUTOCONFIGURATIONVIEW]


GRANT SELECT ON [crt].[MARKUPAUTOCONFIGURATIONVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CUSTOMERELECTRONICADDRESSESVIEW]
PRINT N'Creating view [crt].[CUSTOMERELECTRONICADDRESSESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CUSTOMERELECTRONICADDRESSESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CUSTOMERELECTRONICADDRESSESVIEW]
GO

CREATE VIEW [crt].[CUSTOMERELECTRONICADDRESSESVIEW] AS
(
    SELECT
        lea.TYPE AS METHODYTPE,
        lea.RECID AS RECORDID,
dpl.RECID AS DIRPARTYLOCATIONRECORDID,
        dpt.RECID AS DIRPARTYRECORDID,
        dpt.PARTYNUMBER AS PARTYNUMBER,
lea.DESCRIPTION AS LOCATIONDESCRIPTION,
        lea.LOCATOR,
        lea.LOCATOREXTENSION,
ll.LOCATIONID,
        ll.RECID AS LOGISTICSLOCATIONRECORDID,
        ll.PARENTLOCATION,
lea.ISPRIMARY,
    lea.ISMOBILEPHONE
    FROM [ax].LOGISTICSELECTRONICADDRESS lea
    INNER JOIN [ax].LOGISTICSLOCATION ll ON lea.LOCATION = ll.RECID
    INNER JOIN [ax].DIRPARTYLOCATION dpl ON ll.RECID = dpl.LOCATION
    INNER JOIN [ax].DIRPARTYTABLE dpt ON dpt.RECID = dpl.PARTY 
    WHERE
        (ll.ISPOSTALADDRESS = 0) AND
        (dpl.ISPOSTALADDRESS = 0) AND
        (lea.ISPRIVATE = 0) AND
        ((lea.ISPRIMARY = 1) OR (lea.ISMOBILEPHONE = 1))
)


GO
PRINT N'Finished creating view [crt].[CUSTOMERELECTRONICADDRESSESVIEW]'
GO
-- End creating view [crt].[CUSTOMERELECTRONICADDRESSESVIEW]


GRANT SELECT ON [crt].[CUSTOMERELECTRONICADDRESSESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW]
PRINT N'Creating view [crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW]
GO

CREATE VIEW [crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW] AS
(
    SELECT
        lea.TYPE AS METHODYTPE,
        lea.RECID AS RECORDID,
dpl.RECID AS DIRPARTYLOCATIONRECORDID,
        dpt.RECID AS DIRPARTYRECORDID,
        dpt.PARTYNUMBER AS PARTYNUMBER,
lea.DESCRIPTION AS LOCATIONDESCRIPTION,
        lea.LOCATOR,
        lea.LOCATOREXTENSION,
ll.LOCATIONID,
        ll.RECID AS LOGISTICSLOCATIONRECORDID,
        ll.PARENTLOCATION,
lea.ISPRIMARY,
    lea.ISMOBILEPHONE
    FROM [ax].LOGISTICSELECTRONICADDRESS lea
    INNER JOIN [ax].LOGISTICSLOCATION ll ON lea.LOCATION = ll.RECID and ll.PARENTLOCATION != 0
    INNER JOIN [ax].LOGISTICSPOSTALADDRESS lpa ON ll.PARENTLOCATION = lpa.LOCATION AND GETUTCDATE() BETWEEN VALIDFROM and VALIDTO
    INNER JOIN [ax].DIRPARTYLOCATION dpl ON lpa.LOCATION = dpl.LOCATION
    INNER JOIN [ax].DIRPARTYTABLE dpt ON dpt.RECID = dpl.PARTY 
    WHERE
        (ll.ISPOSTALADDRESS = 0) AND
        (dpl.ISPOSTALADDRESS = 1) AND
        (lea.ISPRIVATE = 0) AND
-- want to include the phone, email, url (primary) and the cell which is not marked primary but is marked ismobile.
        ((lea.ISPRIMARY = 1) OR (lea.ISMOBILEPHONE = 1))
)


GO
PRINT N'Finished creating view [crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW]'
GO
-- End creating view [crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW]


GRANT SELECT ON [crt].[CUSTOMERPOSTALELECTRONICADDRESSESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CUSTOMERPOSTALADDRESSESVIEW]
PRINT N'Creating view [crt].[CUSTOMERPOSTALADDRESSESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CUSTOMERPOSTALADDRESSESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CUSTOMERPOSTALADDRESSESVIEW]
GO

CREATE VIEW [crt].[CUSTOMERPOSTALADDRESSESVIEW] AS
(
    SELECT
        ll.DESCRIPTION AS NAME,
        dpl.ATTENTIONTOADDRESSLINE,
        lpa.ADDRESS,
        lpa.COUNTRYREGIONID,
        lpa.ZIPCODE,
        lpa.STATE,
        lpa.COUNTY,
        lpa.CITY,
        lpa.STREET,
        lpa.STREETNUMBER,
        lpa.BUILDINGCOMPLIMENT,
        lpa.POSTBOX,
        lpa.DISTRICTNAME,
        lpa.RECID,
        dpl.ISPRIMARY,
isnull(lle.TAXGROUP, '') TAXGROUP,
        ll.RECID AS LOGISTICSLOCATIONRECID,
        dpt.RECID AS DIRPARTYTABLERECID,
        dpt.PARTYNUMBER PARTYNUMBER,
        ISNULL(llr.TYPE, 0) AS ADDRESSTYPE,
        dpl.RECID AS DIRPARTYLOCATIONRECID,
isnull(ceap.LOCATOR, '') PHONE,
isnull(ceap.LOCATOREXTENSION, '') PHONEEXT,
isnull(ceap.RECORDID, 0) PHONERECORDID,
isnull(ceae.LOCATOR, '') EMAIL,
isnull(ceae.RECORDID, 0) EMAILRECORDID,
isnull(ceau.LOCATOR, '') URL,
isnull(ceau.RECORDID, 0) URLRECORDID
    FROM [ax].DIRPARTYTABLE dpt
    INNER JOIN [ax].DIRPARTYLOCATION dpl ON dpt.RECID = dpl.PARTY
    INNER JOIN [ax].LOGISTICSLOCATION ll ON dpl.LOCATION = ll.RECID
    INNER JOIN [ax].LOGISTICSPOSTALADDRESS lpa ON ll.RECID = lpa.LOCATION
-- tax group
LEFT OUTER JOIN ax.LOGISTICSLOCATIONEXT lle on ll.RECID = lle.LOCATION 

    -- phone
LEFT OUTER JOIN [crt].CUSTOMERPOSTALELECTRONICADDRESSESVIEW ceap on ll.RECID = ceap.PARENTLOCATION 
and ceap.METHODYTPE = 1 and ceap.ISPRIMARY = 1
-- email
LEFT OUTER JOIN [crt].CUSTOMERPOSTALELECTRONICADDRESSESVIEW ceae on ll.RECID = ceae.PARENTLOCATION 
and ceae.METHODYTPE = 2 and ceae.ISPRIMARY = 1
-- url
LEFT OUTER JOIN [crt].CUSTOMERPOSTALELECTRONICADDRESSESVIEW ceau on ll.RECID = ceau.PARENTLOCATION 
and ceau.METHODYTPE = 3 and ceau.ISPRIMARY = 1
LEFT OUTER JOIN 
(SELECT min(LOCATIONROLE) as PARTYLOCATIONROLE, PARTYLOCATION
FROM ax.DIRPARTYLOCATIONROLE
group by PARTYLOCATION
 ) dplr ON dplr.PARTYLOCATION = dpl.RECID
LEFT OUTER JOIN [ax].LOGISTICSLOCATIONROLE llr ON dplr.PARTYLOCATIONROLE = llr.RECID
    WHERE
        (ll.ISPOSTALADDRESS = 1) AND
        (dpl.ISPOSTALADDRESS = 1) AND
        (lpa.VALIDTO >= GETUTCDATE()) AND
        (lpa.VALIDFROM <= GETUTCDATE()) AND
        (lpa.ISPRIVATE = 0)
)


GO
PRINT N'Finished creating view [crt].[CUSTOMERPOSTALADDRESSESVIEW]'
GO
-- End creating view [crt].[CUSTOMERPOSTALADDRESSESVIEW]


GRANT SELECT ON [crt].[CUSTOMERPOSTALADDRESSESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[PERSONNAMEVIEW]
PRINT N'Creating view [crt].[PERSONNAMEVIEW]';

GO
IF OBJECT_ID(N'[crt].[PERSONNAMEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PERSONNAMEVIEW]
GO

CREATE VIEW [crt].[PERSONNAMEVIEW] AS
(

SELECT        RECID, FIRSTNAME, LASTNAME, MIDDLENAME, PERSON, VALIDFROM, VALIDTO
FROM            ax.DIRPERSONNAME AS dpn
WHERE        (GETUTCDATE() BETWEEN VALIDFROM AND VALIDTO)
)


GO
PRINT N'Finished creating view [crt].[PERSONNAMEVIEW]'
GO
-- End creating view [crt].[PERSONNAMEVIEW]


GRANT SELECT ON [crt].[PERSONNAMEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CUSTOMERSVIEW]
PRINT N'Creating view [crt].[CUSTOMERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CUSTOMERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CUSTOMERSVIEW]
GO

CREATE VIEW [crt].[CUSTOMERSVIEW] AS
(
    SELECT
        ct.ACCOUNTNUM AS ACCOUNTNUMBER,
        ct.RECID,
ct.CREATEDDATETIME,
        dpt.RECID AS PARTY,
        dpt.NAME,
        dpn.RECID AS PERSONNAMEID,
        dpn.FIRSTNAME,
        dpn.MIDDLENAME,
        dpn.LASTNAME,
        dpt.PARTYNUMBER,
        dpt.INSTANCERELATIONTYPE,
        ceap.LOCATOR PHONE,
        ceap.LOCATOREXTENSION PHONEEXT,
        ceap.RECORDID PHONERECORDID,
        ceae.LOCATOR EMAIL,
        ceae.RECORDID EMAILRECORDID,
        ceau.LOCATOR URL,
        ceau.RECORDID URLRECORDID,
        ceacp.LOCATOR CELLPHONE,
        ceacp.RECORDID CELLPHONERECORDID,
        rct.RECEIPTEMAIL RECEIPTEMAIL,
        dpt.LANGUAGEID AS LANGUAGE,
        ct.DATAAREAID,
        rct.RECID RETAILCUSTOMERRECID,
        ct.CURRENCY,
        ct.INVOICEACCOUNT,
        ct.CREDITMAX,
        ct.ONETIMECUSTOMER,
        ct.MARKUPGROUP,
        ct.PRICEGROUP,
        ct.CUSTGROUP,
        ct.BLOCKED,
        ct.ORGID,
        ct.MULTILINEDISC,
        ct.USEPURCHREQUEST,
        ct.LINEDISC,
        ct.INCLTAX,
        ct.ENDDISC,
        ct.TAXGROUP,
        ct.CREDITRATING,
        ct.TAXLICENSENUM,
        ct.VATNUM,
        ct.IDENTIFICATIONNUMBER
/* BEGIN SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this)
, isnull(rcp.EMAILOPTIN, 0) as EMAILOPTIN
END SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this) */
    FROM [ax].CUSTTABLE ct
    JOIN [ax].DIRPARTYTABLE dpt ON ct.PARTY = dpt.RECID
    LEFT OUTER JOIN ax.RETAILCUSTTABLE rct ON ct.ACCOUNTNUM = rct.ACCOUNTNUM AND ct.DATAAREAID = rct.DATAAREAID
    LEFT OUTER JOIN ax.DIRPERSONNAME dpn ON dpt.RECID = dpn.PERSON AND (GETUTCDATE() BETWEEN dpn.VALIDFROM AND dpn.VALIDTO)
    -- phone
    LEFT OUTER JOIN [crt].CUSTOMERELECTRONICADDRESSESVIEW ceap ON dpt.RECID = ceap.DIRPARTYRECORDID
                AND ceap.METHODYTPE = 1 AND ceap.ISPRIMARY = 1 AND ceap.PARENTLOCATION = 0
    -- email
    LEFT OUTER JOIN [crt].CUSTOMERELECTRONICADDRESSESVIEW ceae ON dpt.RECID = ceae.DIRPARTYRECORDID
                AND ceae.METHODYTPE = 2 AND ceae.ISPRIMARY = 1 AND ceae.PARENTLOCATION = 0
    -- url
    LEFT OUTER JOIN [crt].CUSTOMERELECTRONICADDRESSESVIEW ceau ON dpt.RECID = ceau.DIRPARTYRECORDID
                AND ceau.METHODYTPE = 3 AND ceau.ISPRIMARY = 1 AND ceau.PARENTLOCATION = 0
    -- cellphone
    LEFT OUTER JOIN [crt].CUSTOMERELECTRONICADDRESSESVIEW ceacp ON dpt.RECID = ceacp.DIRPARTYRECORDID
                AND ceacp.METHODYTPE = 1
                AND ceacp.ISPRIMARY = 0
                AND ceacp.ISMOBILEPHONE = 1
/* BEGIN SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this)
    LEFT OUTER JOIN [ax].RETAILCUSTPREFERENCE rcp ON ct.ACCOUNTNUM = rcp.ACCOUNTNUM
            AND ct.DATAAREAID = rcp.DATAAREAID
END SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this) */
)


GO
PRINT N'Finished creating view [crt].[CUSTOMERSVIEW]'
GO
-- End creating view [crt].[CUSTOMERSVIEW]


GRANT SELECT ON [crt].[CUSTOMERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[GLOBALCUSTOMERSVIEW]
PRINT N'Creating view [crt].[GLOBALCUSTOMERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[GLOBALCUSTOMERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[GLOBALCUSTOMERSVIEW]
GO

CREATE VIEW [crt].[GLOBALCUSTOMERSVIEW] AS
(
    SELECT
        dpt.PARTYNUMBER,
        dpt.RECID AS RECORDID,
ISNULL(ct.ACCOUNTNUM, '') AS ACCOUNTNUMBER,
        dpt.NAME,
dpt.INSTANCERELATIONTYPE,
 cpa.ADDRESS AS FULLADDRESS,
ceap.LOCATOR AS PHONE,
ceae.LOCATOR AS EMAIL,
ISNULL(ct.ORGID, '') AS ORGID,
ISNULL(ct.DATAAREAID, '') AS DATAAREAID
    FROM [ax].DIRPARTYTABLE dpt
LEFT OUTER JOIN ax.CUSTTABLE ct ON ct.PARTY = dpt.RECID 
-- phone
LEFT OUTER JOIN [crt].CUSTOMERELECTRONICADDRESSESVIEW ceap ON dpt.RECID = ceap.DIRPARTYRECORDID AND ceap.METHODYTPE = 1 AND ceap.ISPRIMARY = 1
-- email
LEFT OUTER JOIN [crt].CUSTOMERELECTRONICADDRESSESVIEW ceae ON dpt.RECID = ceae.DIRPARTYRECORDID AND ceae.METHODYTPE = 2 AND ceae.ISPRIMARY = 1
    -- address
LEFT OUTER JOIN [crt].CUSTOMERPOSTALADDRESSESVIEW cpa ON dpt.RECID = cpa.DIRPARTYTABLERECID AND cpa.ISPRIMARY = 1
)


GO
PRINT N'Finished creating view [crt].[GLOBALCUSTOMERSVIEW]'
GO
-- End creating view [crt].[GLOBALCUSTOMERSVIEW]


GRANT SELECT ON [crt].[GLOBALCUSTOMERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[ACTIVEDEVICESVIEW]
PRINT N'Creating view [crt].[ACTIVEDEVICESVIEW]';

GO
IF OBJECT_ID(N'[crt].[ACTIVEDEVICESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ACTIVEDEVICESVIEW]
GO

CREATE VIEW [crt].[ACTIVEDEVICESVIEW] AS
(
    SELECT
        RD.DEVICEID,
        RD.MODIFIEDDATETIME,
        RD.RECID,
        RD.DESCRIPTION,
        RD.TYPE,
        RTT.RECID AS TERMINALRECID,
        RD.TERMINAL as TERMINALID,
        RST.STOREORIGINID AS CHANNELID
    FROM [ax].RETAILDEVICE RD
    INNER JOIN [ax].RETAILTERMINALTABLE RTT ON RD.TERMINAL = RTT.TERMINALID
    INNER JOIN [ax].RETAILPUBRETAILSTORETABLE RST ON RTT.STORERECID = RST.STOREORIGINID
WHERE RD.ACTIVATIONSTATUS = 1 -- 1 represents Activated status
)


GO
PRINT N'Finished creating view [crt].[ACTIVEDEVICESVIEW]'
GO
-- End creating view [crt].[ACTIVEDEVICESVIEW]


GRANT SELECT ON [crt].[ACTIVEDEVICESVIEW] TO [UsersRole];
GO

-- Creating view [crt].EMPLOYEEPERMISSIONOVERRIDESVIEW
PRINT N'Creating view [crt].EMPLOYEEPERMISSIONOVERRIDESVIEW';

GO
IF OBJECT_ID(N'[crt].EMPLOYEEPERMISSIONOVERRIDESVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].EMPLOYEEPERMISSIONOVERRIDESVIEW
GO

CREATE VIEW [crt].EMPLOYEEPERMISSIONOVERRIDESVIEW AS
(
    SELECT
        MAX(PositionPermission.ALLOWKITDISASSEMBLY) AS ALLOWKITDISASSEMBLY,
        MAX(PositionPermission.ALLOWBLINDCLOSE) AS ALLOWBLINDCLOSE,
        MAX(PositionPermission.ALLOWCHANGENOVOID) AS ALLOWCHANGENOVOID,
        MAX(PositionPermission.ALLOWCREATEORDER) AS ALLOWCREATEORDER,
        MAX(PositionPermission.ALLOWEDITORDER) AS ALLOWEDITORDER,
        MAX(PositionPermission.ALLOWFLOATINGTENDERDECLARATION) AS ALLOWFLOATINGTENDERDECLARATION,
        MAX(PositionPermission.ALLOWMULTIPLELOGINS) AS ALLOWMULTIPLELOGINS,
        MAX(PositionPermission.ALLOWMULTIPLESHIFTLOGON) AS ALLOWMULTIPLESHIFTLOGON,
        MAX(PositionPermission.ALLOWOPENDRAWERONLY) AS ALLOWOPENDRAWERONLY,
        SUM(DISTINCT(PositionPermission.ALLOWPRICEOVERRIDE)) AS ALLOWPRICEOVERRIDE,
        MAX(PositionPermission.ALLOWSALESTAXCHANGE) AS ALLOWSALESTAXCHANGE,
        MAX(PositionPermission.ALLOWTENDERDECLARATION) AS ALLOWTENDERDECLARATION,
        MAX(PositionPermission.ALLOWRETRIEVEORDER) AS ALLOWRETRIEVEORDER,
        MAX(PositionPermission.ALLOWTRANSACTIONSUSPENSION) AS ALLOWTRANSACTIONSUSPENSION,
        MAX(PositionPermission.ALLOWTRANSACTIONVOIDING) AS ALLOWTRANSACTIONVOIDING,
        MAX(PositionPermission.ALLOWXREPORTPRINTING) AS ALLOWXREPORTPRINTING,
        MAX(PositionPermission.ALLOWZREPORTPRINTING) AS ALLOWZREPORTPRINTING,
        MAX(PositionPermission.ALLOWCHANGEPERIPHERALSTATION) AS ALLOWCHANGEPERIPHERALSTATION,
        MAX(PositionPermission.MANAGERPRIVILEGES) AS MANAGERPRIVILEGES,
        MAX(PositionPermission.ALLOWPASSWORDCHANGE) AS ALLOWPASSWORDCHANGE,
        MAX(PositionPermission.ALLOWRESETPASSWORD) AS ALLOWRESETPASSWORD,
        MAX(PositionPermission.MAXIMUMDISCOUNTPCT) AS MAXIMUMDISCOUNTPCT,
        MAX(PositionPermission.MAXLINEDISCOUNTAMOUNT) AS MAXLINEDISCOUNTAMOUNT,
        MAX(PositionPermission.MAXLINERETURNAMOUNT) AS MAXLINERETURNAMOUNT,
        MAX(PositionPermission.MAXTOTALDISCOUNTAMOUNT) AS MAXTOTALDISCOUNTAMOUNT,
        MAX(PositionPermission.MAXTOTALDISCOUNTPCT) AS MAXTOTALDISCOUNTPCT,
        MAX(PositionPermission.MAXTOTALRETURNAMOUNT) AS MAXTOTALRETURNAMOUNT,
        MAX(PositionPermission.USEHANDHELD) AS USEHANDHELD,
        MAX(PositionPermission.MANAGEDEVICE) AS MANAGEDEVICE,
        MAX(PositionPermission.VIEWTIMECLOCKENTRIES) AS VIEWTIMECLOCKENTRIES,
        MAX(Staff.CONTINUEONTSERRORS) AS CONTINUEONTSERRORS,
Staff.STAFFID
    FROM [ax].HCMWORKER AS Worker
    INNER JOIN [ax].RETAILSTAFFTABLE AS Staff ON Staff.STAFFID = Worker.PERSONNELNUMBER
    INNER JOIN [ax].HCMPOSITIONWORKERASSIGNMENT AS Assignment ON Assignment.WORKER = Worker.RECID
    INNER JOIN [ax].HCMPOSITION AS Position ON Position.RECID = Assignment.POSITION
    INNER JOIN [ax].RETAILPOSITIONPOSPERMISSION AS PositionPermission ON PositionPermission.POSITION = Position.RECID
    WHERE GETUTCDATE() BETWEEN [Assignment].VALIDFROM AND [Assignment].VALIDTO
GROUP BY Staff.STAFFID
)


GO
PRINT N'Finished creating view [crt].EMPLOYEEPERMISSIONOVERRIDESVIEW'
GO
-- End creating view [crt].EMPLOYEEPERMISSIONOVERRIDESVIEW


GRANT SELECT ON [crt].EMPLOYEEPERMISSIONOVERRIDESVIEW TO [UsersRole];
GO

-- Creating view [crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW
PRINT N'Creating view [crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW';

GO
IF OBJECT_ID(N'[crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW
GO

CREATE VIEW [crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW AS
(
    SELECT
        Staff.STAFFID,
        MAX(Staff.CONTINUEONTSERRORS) AS CONTINUEONTSERRORS,
        MAX(PermissionGroup.ALLOWKITDISASSEMBLY) AS ALLOWKITDISASSEMBLY,
        MAX(PermissionGroup.ALLOWBLINDCLOSE) AS ALLOWBLINDCLOSE,
        MAX(PermissionGroup.ALLOWCHANGENOVOID) AS ALLOWCHANGENOVOID,
        MAX(PermissionGroup.ALLOWCREATEORDER) AS ALLOWCREATEORDER,
        MAX(PermissionGroup.ALLOWEDITORDER) AS ALLOWEDITORDER,
        MAX(PermissionGroup.ALLOWFLOATINGTENDERDECLARATION) AS ALLOWFLOATINGTENDERDECLARATION,
        MAX(PermissionGroup.ALLOWMULTIPLELOGINS) AS ALLOWMULTIPLELOGINS,
        MAX(PermissionGroup.ALLOWMULTIPLESHIFTLOGON) AS ALLOWMULTIPLESHIFTLOGON,
        MAX(PermissionGroup.ALLOWOPENDRAWERONLY) AS ALLOWOPENDRAWERONLY,
        SUM(DISTINCT(PermissionGroup.ALLOWPRICEOVERRIDE)) AS ALLOWPRICEOVERRIDE,
        MAX(PermissionGroup.ALLOWRETRIEVEORDER) AS ALLOWRETRIEVEORDER,
        MAX(PermissionGroup.ALLOWSALESTAXCHANGE) AS ALLOWSALESTAXCHANGE,
        MAX(PermissionGroup.ALLOWTENDERDECLARATION) AS ALLOWTENDERDECLARATION,
        MAX(PermissionGroup.ALLOWTRANSACTIONSUSPENSION) AS ALLOWTRANSACTIONSUSPENSION,
        MAX(PermissionGroup.ALLOWTRANSACTIONVOIDING) AS ALLOWTRANSACTIONVOIDING,
        MAX(PermissionGroup.ALLOWXREPORTPRINTING) AS ALLOWXREPORTPRINTING,
        MAX(PermissionGroup.ALLOWZREPORTPRINTING) AS ALLOWZREPORTPRINTING,
        MAX(PermissionGroup.ALLOWCHANGEPERIPHERALSTATION) AS ALLOWCHANGEPERIPHERALSTATION,
        MAX(PermissionGroup.MANAGERPRIVILEGES) AS MANAGERPRIVILEGES,
        MAX(PermissionGroup.ALLOWPASSWORDCHANGE) AS ALLOWPASSWORDCHANGE,
        MAX(PermissionGroup.ALLOWRESETPASSWORD) AS ALLOWRESETPASSWORD,
        MAX(PermissionGroup.MAXIMUMDISCOUNTPCT) AS MAXIMUMDISCOUNTPCT,
        MAX(PermissionGroup.MAXLINEDISCOUNTAMOUNT) AS MAXLINEDISCOUNTAMOUNT,
        MAX(PermissionGroup.MAXLINERETURNAMOUNT) AS MAXLINERETURNAMOUNT,
        MAX(PermissionGroup.MAXTOTALDISCOUNTAMOUNT) AS MAXTOTALDISCOUNTAMOUNT,
        MAX(PermissionGroup.MAXTOTALDISCOUNTPCT) AS MAXTOTALDISCOUNTPCT,
        MAX(PermissionGroup.MAXTOTALRETURNAMOUNT) AS MAXTOTALRETURNAMOUNT,
        MAX(PermissionGroup.USEHANDHELD) AS USEHANDHELD,
        MAX(PermissionGroup.MANAGEDEVICE) AS MANAGEDEVICE,
        MAX(PermissionGroup.VIEWTIMECLOCKENTRIES) AS VIEWTIMECLOCKENTRIES
FROM [ax].HCMWORKER AS Worker
INNER JOIN [ax].RETAILSTAFFTABLE AS Staff ON Staff.STAFFID = Worker.PERSONNELNUMBER
INNER JOIN [ax].HCMPOSITIONWORKERASSIGNMENT AS PositionWorkerAssignment ON PositionWorkerAssignment.WORKER = Worker.RECID
INNER JOIN [ax].HCMPOSITION AS Position ON Position.RECID = PositionWorkerAssignment.POSITION
INNER JOIN [ax].HCMPOSITIONDETAIL AS PositionDetail ON PositionDetail.POSITION = PositionWorkerAssignment.POSITION
INNER JOIN [ax].HCMJOB AS Job ON Job.RECID = PositionDetail.JOB
INNER JOIN [ax].RETAILJOBPOSPERMISSIONGROUP AS JobPermission ON JobPermission.JOB = Job.RECID
INNER JOIN [ax].RETAILPOSPERMISSIONGROUP AS PermissionGroup ON PermissionGroup.RECID = JobPermission.RETAILPOSPERMISSIONGROUP
WHERE GETUTCDATE() BETWEEN [PositionWorkerAssignment].VALIDFROM AND [PositionWorkerAssignment].VALIDTO
        AND GETUTCDATE() BETWEEN [PositionDetail].VALIDFROM AND [PositionDetail].VALIDTO
GROUP BY STAFFID
)


GO
PRINT N'Finished creating view [crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW'
GO
-- End creating view [crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW


GRANT SELECT ON [crt].EMPLOYEEPERMISSIONSPOSITIONSVIEW TO [UsersRole];
GO

-- Creating view [crt].EMPLOYEEPERMISSIONSVIEW
PRINT N'Creating view [crt].EMPLOYEEPERMISSIONSVIEW';

GO
IF OBJECT_ID(N'[crt].EMPLOYEEPERMISSIONSVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].EMPLOYEEPERMISSIONSVIEW
GO

CREATE VIEW [crt].EMPLOYEEPERMISSIONSVIEW AS
(
    SELECT
        STAFFID,
        CONTINUEONTSERRORS,
        ALLOWKITDISASSEMBLY,
        ALLOWBLINDCLOSE,
        ALLOWCHANGENOVOID,
        ALLOWCREATEORDER,
        ALLOWEDITORDER,
        ALLOWFLOATINGTENDERDECLARATION,
        ALLOWMULTIPLELOGINS,
        ALLOWMULTIPLESHIFTLOGON,
        ALLOWOPENDRAWERONLY,
        ALLOWPRICEOVERRIDE,
        ALLOWRETRIEVEORDER,
        ALLOWSALESTAXCHANGE,
        ALLOWTENDERDECLARATION,
        ALLOWTRANSACTIONSUSPENSION,
        ALLOWTRANSACTIONVOIDING,
        ALLOWXREPORTPRINTING,
        ALLOWZREPORTPRINTING,
        ALLOWCHANGEPERIPHERALSTATION,
        MANAGEDEVICE,
        MANAGERPRIVILEGES,
        ALLOWPASSWORDCHANGE,
        ALLOWRESETPASSWORD,
        MAXLINEDISCOUNTAMOUNT,
        MAXIMUMDISCOUNTPCT,
        MAXLINERETURNAMOUNT,
        MAXTOTALDISCOUNTAMOUNT,
        MAXTOTALDISCOUNTPCT,
        MAXTOTALRETURNAMOUNT,
        USEHANDHELD,
VIEWTIMECLOCKENTRIES
FROM crt.EMPLOYEEPERMISSIONSPOSITIONSVIEW POSITIONS
WHERE NOT EXISTS ( SELECT * from crt.EMPLOYEEPERMISSIONOVERRIDESVIEW OVERRIDES WHERE POSITIONS.STAFFID = OVERRIDES.STAFFID )

UNION

SELECT
        STAFFID,
CONTINUEONTSERRORS,
        ALLOWKITDISASSEMBLY,
        ALLOWBLINDCLOSE,
        ALLOWCHANGENOVOID,
        ALLOWCREATEORDER,
        ALLOWEDITORDER,
        ALLOWFLOATINGTENDERDECLARATION,
        ALLOWMULTIPLELOGINS,
        ALLOWMULTIPLESHIFTLOGON,
        ALLOWOPENDRAWERONLY,
        ALLOWPRICEOVERRIDE,
        ALLOWRETRIEVEORDER,
        ALLOWSALESTAXCHANGE,
        ALLOWTENDERDECLARATION,
        ALLOWTRANSACTIONSUSPENSION,
        ALLOWTRANSACTIONVOIDING,
        ALLOWXREPORTPRINTING,
        ALLOWZREPORTPRINTING,
        ALLOWCHANGEPERIPHERALSTATION,
        MANAGEDEVICE,
        MANAGERPRIVILEGES,
        ALLOWPASSWORDCHANGE,
        ALLOWRESETPASSWORD,
        MAXLINEDISCOUNTAMOUNT,
        MAXIMUMDISCOUNTPCT,
        MAXLINERETURNAMOUNT,
        MAXTOTALDISCOUNTAMOUNT,
        MAXTOTALDISCOUNTPCT,
        MAXTOTALRETURNAMOUNT,
        USEHANDHELD,
VIEWTIMECLOCKENTRIES
FROM crt.EMPLOYEEPERMISSIONOVERRIDESVIEW
)


GO
PRINT N'Finished creating view [crt].EMPLOYEEPERMISSIONSVIEW'
GO
-- End creating view [crt].EMPLOYEEPERMISSIONSVIEW


GRANT SELECT ON [crt].EMPLOYEEPERMISSIONSVIEW TO [UsersRole];
GO

-- Creating view [crt].EMPLOYEESVIEW
PRINT N'Creating view [crt].EMPLOYEESVIEW';

GO
IF OBJECT_ID(N'[crt].EMPLOYEESVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].EMPLOYEESVIEW
GO

CREATE VIEW [crt].EMPLOYEESVIEW AS
(
    SELECT
        Staff.STAFFID,
        Staff.NAMEONRECEIPT,
        Party.NAME,
        Staff.IMAGE,
Staff.CULTURENAME
    FROM  [ax].RETAILSTAFFTABLE Staff
    INNER JOIN [ax].HCMWORKER Worker ON Staff.STAFFID = Worker.PERSONNELNUMBER
    INNER JOIN [ax].DIRPARTYTABLE Party ON Worker.PERSON = Party.RECID
)


GO
PRINT N'Finished creating view [crt].EMPLOYEESVIEW'
GO
-- End creating view [crt].EMPLOYEESVIEW


GRANT SELECT ON [crt].EMPLOYEESVIEW TO [UsersRole];
GO

-- Creating view [crt].[DEVICECONFIGURATIONSVIEW]
PRINT N'Creating view [crt].[DEVICECONFIGURATIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[DEVICECONFIGURATIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[DEVICECONFIGURATIONSVIEW]
GO

CREATE VIEW [crt].[DEVICECONFIGURATIONSVIEW] AS
(
    SELECT
        rfp.AGGREGATEITEMS,
        rfp.AGGREGATEITEMSFORPRINTING,
        rfp.AGGREGATEPAYMENTS,
        rfp.AUDITENABLED,
        rfp.DISCOUNTATTOTAL,
        rfp.DISPLAYSECONDARYTOTALCURRENCY,
        rfp.ENDOFTRANSACTION,
        rfp.LIMITSTAFFLISTTOSTORE,
        rfp.LINEITEMTAXCHANGE,
        rfp.MAXIMUMPRICE,
        rfp.MAXIMUMQTY,
        rfp.MINIMUMPASSWORDLENGTH,
        rfp.MUSTKEYINPRICEIFZERO,
        rfp.NAME AS FUNCTIONALITYPROFILEDESCRIPTION,
        rfp.OVERRIDEPRICE,
        rfp.PRINTXREPORTONTERMINAL,
        rfp.PROFILEID,
        rfp.REFUNDSALE,
        rfp.SALESPERSON,
        rfp.SECONDARYTOTALCURRENCY,
        rfp.SHOWSTAFFLISTATLOGON,
        rfp.STAFFBARCODELOGON,
        rfp.STAFFBARCODELOGONREQUIRESPASSWORD,
        rfp.STAFFCARDLOGON,
        rfp.STAFFCARDLOGONREQUIRESPASSWORD,
        rfp.STARTOFTRANSACTION,
        rfp.TAENABLEREGISTRATION,
        rfp.TENDERDECLARATION,
        rfp.TRANSACTIONTAXCHANGE,
        rfp.VOIDISPRESSED,
        rfp.VOIDPAYMENT,
        rfp.VOIDTRANSACTION,
        rfp.INCLUDEKITCOMPONENTS,
        rfp.MAXTRANSACTIONSEARCHRESULTS,
rfp.REQUIREAMOUNTDECLARATION,
        rst.CULTURENAME,
        rst.HIDETRAININGMODE,
        rst.PHONE,
        COALESCE(rtt.STATEMENTMETHOD, rst.STATEMENTMETHOD) AS STATEMENTMETHOD,
        rst.RECID AS CHANNELID,
        rst.STORENUMBER,
        rst.TAXGROUP,
        rst.TAXIDENTIFICATIONNUMBER,
        rst.TAXOVERRIDEGROUP,
        rst.TENDERDECLARATIONCALCULATION,
        rst.USECUSTOMERBASEDTAX,
        rst.USEDESTINATIONBASEDTAX,
        rtt.AUTOLOGOFFTIMEOUT,
        rtt.CUSTOMERDISPLAYTEXT1,
        rtt.CUSTOMERDISPLAYTEXT2,
        rtt.EFTSTORERECID,
        rtt.EFTTERMINALID,
        rtt.EXITAFTEREACHTRANSACTION,
        rtt.HARDWAREPROFILE,
        rtt.LOCATION,
        rtt.NAME AS TERMINALDESCRIPTION,
        rtt.OPENDRAWERATLILO,
        rtt.PRINTVATREFUNDCHECKS,
        rtt.STANDALONE,
        rtt.TERMINALID,
        rtt.TERMINALSTATEMENT,
        rtac.COLOR,
        rvp.POSSKINNAME,
        rilb.PICTURE AS LOGONBACKGROUNDPICTURE,
        rib.PICTURE AS BACKGROUNDPICTURE,
        rct.CURRENCY,
        rct.INVENTLOCATION,
rst.STMTPOSTASBUSINESSDAY AS 'STATEMENTPOSTINGASBUSINESSDAY',
rst.STMTCALCBATCHENDTIME AS 'STATEMENTCALCULATIONBATCHENDTIMEINSECONDS'
    FROM [ax].RETAILCHANNELTABLE AS rct
    INNER JOIN [ax].RETAILSTORETABLE AS rst ON rct.RECID = rst.RECID
    INNER JOIN [ax].RETAILTERMINALTABLE AS rtt ON rtt.STORERECID = rst.RECID
    INNER JOIN [ax].RETAILFUNCTIONALITYPROFILE AS rfp ON rst.FUNCTIONALITYPROFILE = rfp.PROFILEID
    INNER JOIN [ax].RETAILVISUALPROFILE AS rvp ON rvp.PROFILEID = rtt.VISUALPROFILE
    LEFT JOIN [ax].RETAILTHEMEPALLET AS rtp ON rtp.NAME = rvp.PALLET
    LEFT JOIN [ax].RETAILTHEMEACCENTCOLOR AS rtac ON rtac.PALLET = rtp.RECID
    LEFT JOIN [ax].RETAILIMAGES as rilb ON rilb.PICTUREID = rvp.PICTUREID
    LEFT JOIN [ax].RETAILIMAGES as rib ON rib.PICTUREID = rvp.BACKGROUNDPICTUREID
)


GO
PRINT N'Finished creating view [crt].[DEVICECONFIGURATIONSVIEW]'
GO
-- End creating view [crt].[DEVICECONFIGURATIONSVIEW]


GRANT SELECT ON [crt].[DEVICECONFIGURATIONSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[HARDWAREPROFILESVIEW]
PRINT N'Creating view [crt].[HARDWAREPROFILESVIEW]';

GO
IF OBJECT_ID(N'[crt].[HARDWAREPROFILESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[HARDWAREPROFILESVIEW]
GO

CREATE VIEW [crt].[HARDWAREPROFILESVIEW] AS
(
SELECT rhp.DELAYFORLINKEDITEMS
      ,rhp.DISPLAYBALANCETEXT
      ,rhp.DISPLAYBINCONVERSION
      ,rhp.DISPLAYCHARACTERSET
      ,rhp.DISPLAYCLOSEDLINE1
      ,rhp.DISPLAYCLOSEDLINE2
      ,rhp.DISPLAYDESCRIPTION
      ,rhp.DISPLAYDEVICE
      ,rhp.DISPLAYDEVICENAME
      ,rhp.DISPLAYLINKEDITEM
      ,rhp.DISPLAYTERMINALCLOSED
      ,rhp.DISPLAYTOTALTEXT
      ,rhp.DUALDISPLAY
      ,rhp.DUALDISPLAYBROWSERURL
      ,rhp.DUALDISPLAYIMAGEINTERVAL
      ,rhp.DUALDISPLAYIMAGEPATH
      ,rhp.DUALDISPLAYRECEIPTPERCENTAGE
      ,rhp.DUALDISPLAYTYPE
      ,rhp.EFT
      ,rhp.EFTCOMPANYID
      ,rhp.EFTCONFIGURATION
      ,rhp.EFTCONNECTORNAME
      ,rhp.EFTCONNECTORPROPERTIES
      ,rhp.EFTDATA
      ,rhp.EFTDESCRIPTION
      ,rhp.EFTMERCHANTID
      ,rhp.EFTPASSWORD
      ,rhp.EFTSERVERNAME
      ,rhp.EFTSERVERPORT
      ,rhp.EFTUSERID
      ,rhp.ENDTRACK1
      ,rhp.ENDTRACK2
      ,rhp.KEYBOARDMAPPINGID
      ,rhp.KEYLOCK
      ,rhp.KEYLOCKDESCRIPTION
      ,rhp.KEYLOCKDEVICENAME
      ,rhp.MANUALINPUTALLOWED
      ,rhp.MSR
      ,rhp.MSRDESCRIPTION
      ,rhp.MSRDEVICENAME
      ,rhp.MSRMAKE
      ,rhp.MSRMODEL
      ,rhp.NAME
      ,rhp.PINPAD
      ,rhp.PINPADDESCRIPTION
      ,rhp.PINPADDEVICENAME
      ,rhp.PINPADMAKE
      ,rhp.PINPADMODEL
      ,rhp.PROFILEID
      ,rhp.RFIDDESCRIPTION
      ,rhp.RFIDDEVICENAME
      ,rhp.RFIDSCANNERTYPE
      ,rhp.SCALE
      ,rhp.SCALEDESCRIPTION
      ,rhp.SCALEDEVICENAME
      ,rhp.SEPARATOR1
      ,rhp.SIGCAP
      ,rhp.SIGCAPDESCRIPTION
      ,rhp.SIGCAPDEVICENAME
      ,rhp.SIGCAPFORMNAME
      ,rhp.SIGCAPMAKE
      ,rhp.SIGCAPMODEL
      ,rhp.STARTTRACK1
      ,rhp.TIMEOUTINSEC
  FROM [ax].[RETAILHARDWAREPROFILE] AS rhp
)


GO
PRINT N'Finished creating view [crt].[HARDWAREPROFILESVIEW]'
GO
-- End creating view [crt].[HARDWAREPROFILESVIEW]


GRANT SELECT ON [crt].[HARDWAREPROFILESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[HARDWAREPROFILEPRINTERSVIEW]
PRINT N'Creating view [crt].[HARDWAREPROFILEPRINTERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[HARDWAREPROFILEPRINTERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[HARDWAREPROFILEPRINTERSVIEW]
GO

CREATE VIEW [crt].[HARDWAREPROFILEPRINTERSVIEW] AS
(
        SELECT rhp.PROFILEID
          ,rhp.PRINTER as 'PRINTERTYPE'
          ,rhp.PRINTERMAKE as 'PRINTERMAKEVALUE'
          ,rhp.PRINTERMODEL as 'PRINTERMODELVALUE'
          ,rhp.PRINTERDESCRIPTION as 'PRINTERDESCRIPTIONVALUE'
          ,rhp.PRINTERDEVICENAME as 'PRINTERDEVICENAMEVALUE'
          ,rhp.PRINTERCHARACTERSET as 'PRINTERCHARACTERSETVALUE'
          ,rhp.PRINTERRECEIPTPROFILEID as 'PRINTERRECEIPTPROFILEIDVALUE'
          ,rhp.PRINTBINARYCONVERSION as 'PRINTERBINARYCONVERSIONVALUE'
          ,rhp.DOCINSERTREMOVALTIMEOUT as 'PRINTERDOCINSERTREMOVALTIMEOUTVALUE'
          ,rhp.LOGO as 'PRINTERLOGOVALUE'
          ,rhp.LOGOALIGNMENT as 'PRINTERLOGOALIGNMENTVALUE'
        FROM [ax].[RETAILHARDWAREPROFILE] rhp
        UNION ALL
        SELECT rhp.PROFILEID
          ,rhp.PRINTER2 as 'PRINTERTYPE'
          ,rhp.PRINTER2MAKE as 'PRINTERMAKEVALUE'
          ,rhp.PRINTER2MODEL as 'PRINTERMODELVALUE'
          ,rhp.PRINTER2DESCRIPTION as 'PRINTERDESCRIPTIONVALUE'
          ,rhp.PRINTER2DEVICENAME as 'PRINTERDEVICENAMEVALUE'
          ,rhp.PRINTER2CHARACTERSET as 'PRINTERCHARACTERSETVALUE'
          ,rhp.PRINTER2RECEIPTPROFILEID as 'PRINTERRECEIPTPROFILEIDVALUE'
          ,rhp.PRINTER2BINARYCONVERSION as 'PRINTERBINARYCONVERSIONVALUE'
          ,rhp.PRINTER2DOCINSERTREMOVALTIMEOUT as 'PRINTERDOCINSERTREMOVALTIMEOUTVALUE'
          ,rhp.PRINTER2LOGO as 'PRINTERLOGOVALUE'
          ,rhp.PRINTER2LOGOALIGNMENT as 'PRINTERLOGOALIGNMENTVALUE'
        FROM [ax].[RETAILHARDWAREPROFILE] rhp
)


GO
PRINT N'Finished creating view [crt].[HARDWAREPROFILEPRINTERSVIEW]'
GO
-- End creating view [crt].[HARDWAREPROFILEPRINTERSVIEW]


GRANT SELECT ON [crt].[HARDWAREPROFILEPRINTERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[HARDWAREPROFILESCANNERSVIEW]
PRINT N'Creating view [crt].[HARDWAREPROFILESCANNERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[HARDWAREPROFILESCANNERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[HARDWAREPROFILESCANNERSVIEW]
GO

CREATE VIEW [crt].[HARDWAREPROFILESCANNERSVIEW] AS
(
  SELECT 
    PROFILEID AS 'PROFILEID',
    SCANNER AS 'SCANNERTYPE',
    SCANNERDESCRIPTION AS 'SCANNERDESCRIPTIONVALUE',
    SCANNERDEVICENAME AS 'SCANNERDEVICENAMEVALUE'
    FROM
  [ax].[RETAILHARDWAREPROFILE] rhp
  
  UNION ALL

  SELECT
    PROFILEID AS 'PROFILEID',
    SCANNER2 AS 'SCANNERTYPE',
    SCANNER2DESCRIPTION AS 'SCANNERDESCRIPTIONVALUE',
    SCANNER2DEVICENAME AS 'SCANNERDEVICENAMEVALUE'
  FROM
  [ax].[RETAILHARDWAREPROFILE] rhp
)


GO
PRINT N'Finished creating view [crt].[HARDWAREPROFILESCANNERSVIEW]'
GO
-- End creating view [crt].[HARDWAREPROFILESCANNERSVIEW]


GRANT SELECT ON [crt].[HARDWAREPROFILESCANNERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[HARDWAREPROFILECASHDRAWERSVIEW]
PRINT N'Creating view [crt].[HARDWAREPROFILECASHDRAWERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[HARDWAREPROFILECASHDRAWERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[HARDWAREPROFILECASHDRAWERSVIEW]
GO

CREATE VIEW [crt].[HARDWAREPROFILECASHDRAWERSVIEW] AS
(
        SELECT rhp.PROFILEID
                  ,rhp.DRAWER as 'DRAWERTYPE'
                  ,rhp.DRAWERDESCRIPTION as 'DRAWERDESCRIPTIONVALUE'
                  ,rhp.DRAWERDEVICENAME as 'DRAWERDEVICENAMEVALUE'
                  ,rhp.DRAWERMAKE as 'DRAWERMAKEVALUE'
                  ,rhp.DRAWERMODEL as 'DRAWERMODELVALUE'
        FROM [ax].[RETAILHARDWAREPROFILE] rhp
        UNION ALL
        SELECT rhp.PROFILEID
                  ,rhp.DRAWER2 as 'DRAWERTYPE'
                  ,rhp.DRAWER2DESCRIPTION as 'DRAWERDESCRIPTIONVALUE'
                  ,rhp.DRAWER2DEVICENAME as 'DRAWERDEVICENAMEVALUE'
                  ,rhp.DRAWER2MAKE as 'DRAWERMAKEVALUE'
                  ,rhp.DRAWER2MODEL as 'DRAWERMODELVALUE'
        FROM [ax].[RETAILHARDWAREPROFILE] rhp
)


GO
PRINT N'Finished creating view [crt].[HARDWAREPROFILECASHDRAWERSVIEW]'
GO
-- End creating view [crt].[HARDWAREPROFILECASHDRAWERSVIEW]


GRANT SELECT ON [crt].[HARDWAREPROFILECASHDRAWERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].EMPLOYEELOGONVIEW
PRINT N'Creating view [crt].EMPLOYEELOGONVIEW';

GO
IF OBJECT_ID(N'[crt].EMPLOYEELOGONVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].EMPLOYEELOGONVIEW
GO

CREATE VIEW [crt].EMPLOYEELOGONVIEW AS
(
SELECT
StaffTable.STAFFID,
StaffTable.BLOCKED, 
StaffTable.PASSWORDDATA, 
StaffTable.NAMEONRECEIPT,
Party.NAME, 
StoreTable.RECID AS CHANNELID, 
HcmWorker.PERSONNELNUMBER, 
ExtendedLogon.LOGONKEY, 
ExtendedLogon.EXTRADATA, 
ExtendedLogon.LOGONTYPE
FROM [ax].RETAILSTAFFTABLE as StaffTable
INNER JOIN [ax].HCMWORKER as HcmWorker on HcmWorker.PERSONNELNUMBER = StaffTable.STAFFID
INNER JOIN [ax].DIRPARTYTABLE as Party on HcmWorker.PERSON = Party.RECID
INNER JOIN [ax].DIRADDRESSBOOKPARTY as DirAddressBookParty on DirAddressBookParty.PARTY = HcmWorker.PERSON
INNER JOIN [ax].RETAILSTOREADDRESSBOOK as AddressBook on addressbook.ADDRESSBOOK = DirAddressBookParty.ADDRESSBOOK
INNER JOIN [ax].RETAILSTORETABLE as StoreTable on AddressBook.STORERECID = StoreTable.RECID
LEFT OUTER JOIN  [ax].RETAILSTAFFEXTENDEDLOGON as ExtendedLogon on StaffTable.RECID = ExtendedLogon.STAFF
)

GO
PRINT N'Finished creating view [crt].EMPLOYEELOGONVIEW'
GO
-- End creating view [crt].EMPLOYEELOGONVIEW


GRANT SELECT ON [crt].EMPLOYEELOGONVIEW TO [UsersRole];
GO

-- Creating view [crt].[LOGISTICSPOSTALADDRESSESVIEW]
PRINT N'Creating view [crt].[LOGISTICSPOSTALADDRESSESVIEW]';

GO
IF OBJECT_ID(N'[crt].[LOGISTICSPOSTALADDRESSESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[LOGISTICSPOSTALADDRESSESVIEW]
GO
/********************************************************************************
    LOGISTICSPOSTALADDRESSESVIEW retrieves the logistics postal address.
The view joins with the tables: LOGISTICSPOSTALADDRESS, LOGISTICSLOCATION, LOGISTICSADDRESSCOUNTRYREGION
********************************************************************************/

CREATE VIEW [crt].[LOGISTICSPOSTALADDRESSESVIEW] AS
(
SELECT 
lpa.COUNTY AS COUNTY,
lpa.DISTRICT AS DISTRICT,
lpa.POSTBOX AS POSTBOX,
lpa.ADDRESS AS ADDRESS,
lpa.BUILDINGCOMPLIMENT AS BUILDINGCOMPLIMENT,
lpa.CITY AS CITY,
lpa.COUNTRYREGIONID AS COUNTRYREGIONID,
lpa.LATITUDE AS LATITUDE,
lpa.STATE AS STATE,
lpa.STREET AS STREET,
lpa.STREETNUMBER AS STREETNUMBER,
lpa.TIMEZONE AS TIMEZONE,
lpa.LONGITUDE AS LONGITUDE,
lpa.ZIPCODE AS ZIPCODE,
lpa.LOCATION AS LOCATION,
lpa.VALIDFROM AS VALIDFROM,
lpa.VALIDTO AS VALIDTO,
lpa.RECID AS POSTALADDRESSRECID,
lpa.RECID AS POSTALADDRESS,
lpa.DISTRICTNAME AS DISTRICTNAME,
lpa.RECID AS RECID,
LL.DESCRIPTION AS LOCATIONNAME,
LACR.CURRENCYCODE AS COUNTRYCURRENCYCODE,LACR.ISOCODE AS ISOCODE
FROM [ax].[LOGISTICSPOSTALADDRESS] lpa
CROSS JOIN [ax].[LOGISTICSLOCATION] LL
CROSS JOIN [ax].[LOGISTICSADDRESSCOUNTRYREGION] LACR
WHERE (lpa.LOCATION=LL.RECID) AND (lpa.COUNTRYREGIONID=LACR.COUNTRYREGIONID)
)

GO
PRINT N'Finished creating view [crt].[LOGISTICSPOSTALADDRESSESVIEW]'
GO
-- End creating view [crt].[LOGISTICSPOSTALADDRESSESVIEW]


GRANT SELECT ON [crt].[LOGISTICSPOSTALADDRESSESVIEW] TO [UsersRole];
GO



-- Creating view [crt].[ITEMRESERVATIONSUMVIEW]
PRINT N'Creating view [crt].[ITEMRESERVATIONSUMVIEW]';

GO
IF OBJECT_ID(N'[crt].[ITEMRESERVATIONSUMVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ITEMRESERVATIONSUMVIEW]
GO

CREATE VIEW [crt].[ITEMRESERVATIONSUMVIEW] AS
(
    SELECT
        ir.[INVENTAVAILABILITY],
        SUM(ir.[QUANTITY]) AS QUANTITY
    FROM [crt].ITEMRESERVATION ir
    WHERE ir.[ISRELEASED] = 0 AND ir.[EXPIREDATETIME] >= GETUTCDATE()
    GROUP BY ir.[INVENTAVAILABILITY]
)


GO
PRINT N'Finished creating view [crt].[ITEMRESERVATIONSUMVIEW]'
GO
-- End creating view [crt].[ITEMRESERVATIONSUMVIEW]


GRANT SELECT ON [crt].[ITEMRESERVATIONSUMVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW] AS
(
    SELECT
        rtst.ITEMID,
        rtst.INVENTDIMID,
        ISNULL(rtos.LASTINVENTTRANS, 0) AS LASTINVENTTRANS,
        SUM(rtst.QTY) AS QUANTITY,
        rtst.DATAAREAID
    FROM [ax].RETAILTRANSACTIONSALESTRANS rtst
    LEFT JOIN [ax].RETAILTRANSACTIONORDERSTATUS rtos
        ON rtos.STORE = rtst.STORE
        AND rtos.TERMINAL = rtst.TERMINALID
        AND rtos.TRANSACTIONID = rtst.TRANSACTIONID
        AND rtst.TRANSACTIONSTATUS != 1         -- exclude voided lines
    GROUP BY rtst.DATAAREAID, rtst.ITEMID, rtst.INVENTDIMID, ISNULL(rtos.LASTINVENTTRANS, 0)
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONSALESTRANSQTYSUMVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW]
PRINT N'Creating view [crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW]
GO

CREATE VIEW [crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW] AS
(
    SELECT
        ria.RECID AS INVENTAVAILABILITY,
        SUM(rtstqsv.QUANTITY) AS QUANTITY
    FROM [crt].RETAILTRANSACTIONSALESTRANSQTYSUMVIEW rtstqsv
    INNER JOIN [ax].INVENTTABLE it ON it.ITEMID = rtstqsv.ITEMID AND it.DATAAREAID = rtstqsv.DATAAREAID
    INNER JOIN [ax].INVENTDIM id on id.INVENTDIMID = rtstqsv.INVENTDIMID AND id.DATAAREAID = it.DATAAREAID
    INNER JOIN [ax].RETAILINVENTAVAILABILITY ria ON ria.ITEMRECID = it.RECID AND ria.INVENTDIMRECID = id.RECID
    WHERE
        -- Sales order creation not yet confirmed from AX
        rtstqsv.LASTINVENTTRANS = 0

        -- Sales order creation confirmed but AX availability calculated before sales order creation
        OR ria.LASTINVENTTRANS < rtstqsv.LASTINVENTTRANS
    GROUP BY ria.RECID
)


GO
PRINT N'Finished creating view [crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW]'
GO
-- End creating view [crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW]


GRANT SELECT ON [crt].[RETAILINVENTAVAILABILITYSALESORDERSUMVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILINVENTAVAILABILITYVIEW]
PRINT N'Creating view [crt].[RETAILINVENTAVAILABILITYVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILINVENTAVAILABILITYVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILINVENTAVAILABILITYVIEW]
GO

CREATE VIEW [crt].[RETAILINVENTAVAILABILITYVIEW] AS
(
    SELECT
        ria.RECID,
        it.ITEMID,
it.DATAAREAID,
        id.INVENTDIMID,
        ria.AVAILPHYSICAL - ISNULL(irv.QUANTITY, 0) + ISNULL(riasosv.QUANTITY, 0) AS AVAILPHYSICAL
    FROM [ax].RETAILINVENTAVAILABILITY ria
    INNER JOIN [ax].INVENTTABLE it ON it.RECID = ria.ITEMRECID
    INNER JOIN [ax].INVENTDIM id on  id.RECID = ria.INVENTDIMRECID AND id.DATAAREAID = it.DATAAREAID
    LEFT JOIN [crt].ITEMRESERVATIONSUMVIEW irv ON irv.INVENTAVAILABILITY = ria.RECID
    LEFT JOIN [crt].RETAILINVENTAVAILABILITYSALESORDERSUMVIEW riasosv ON riasosv.INVENTAVAILABILITY = ria.RECID
)


GO
PRINT N'Finished creating view [crt].[RETAILINVENTAVAILABILITYVIEW]'
GO
-- End creating view [crt].[RETAILINVENTAVAILABILITYVIEW]


GRANT SELECT ON [crt].[RETAILINVENTAVAILABILITYVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW] AS
(
    SELECT
        (CASE WHEN L.QTY < 0.00 THEN L.NETAMOUNT ELSE 0 END) AS SALESAMOUNT,
        (CASE WHEN L.QTY > 0.00 THEN L.NETAMOUNT ELSE 0 END) AS RETURNAMOUNT,
(CASE WHEN L.QTY < 0.00 THEN L.TAXAMOUNT ELSE 0 END) AS SALESTAXAMOUNT,
(CASE WHEN L.QTY > 0.00 THEN L.TAXAMOUNT ELSE 0 END) AS RETURNTAXAMOUNT,
        L.TAXAMOUNT,
        L.DISCAMOUNT,
        H.CHANNEL,
        H.BATCHID,
        H.BATCHTERMINALID,
        H.ENTRYSTATUS,
        H.TYPE,
        H.TRANSACTIONID
    FROM [ax].[RETAILTRANSACTIONSALESTRANS] AS L 
    INNER JOIN [ax].[RETAILTRANSACTIONTABLE] AS H 
        ON H.TRANSACTIONID = L.TRANSACTIONID 
        AND H.CHANNEL = L.CHANNEL
        AND H.STORE = L.STORE 
        AND H.TERMINAL = L.TERMINALID
        AND H.DATAAREAID = L.DATAAREAID 
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[ITEMAVAILABILITYVIEW]
PRINT N'Creating view [crt].[ITEMAVAILABILITYVIEW]';

GO
IF OBJECT_ID(N'[crt].[ITEMAVAILABILITYVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ITEMAVAILABILITYVIEW]
GO

CREATE VIEW [crt].[ITEMAVAILABILITYVIEW] AS
(
    SELECT
        RIAV.RECID
        ,RIAV.ITEMID
        ,CASE
            WHEN VID.CONFIGID = ''
                    AND VID.INVENTSIZEID = ''
                    AND VID.INVENTCOLORID = ''
                    AND VID.INVENTSTYLEID = ''
                    AND VID.INVENTBATCHID = ''
                    AND VID.WMSLOCATIONID = ''
                    AND VID.WMSPALLETID = ''
                    AND VID.INVENTSERIALID = ''
                THEN ''
            ELSE ISNULL(VID.INVENTDIMID, '')
        END AS VARIANTINVENTDIMID
        ,WID.INVENTDIMID AS WAREHOUSEINVENTDIMID
        ,WID.INVENTSITEID
        ,WID.INVENTLOCATIONID
        ,RIAV.AVAILPHYSICAL
        ,ITM.UNITID
        ,RIAV.DATAAREAID
    FROM [crt].RETAILINVENTAVAILABILITYVIEW RIAV
    JOIN [ax].INVENTTABLEMODULE ITM ON ITM.ITEMID = RIAV.ITEMID AND ITM.DATAAREAID = RIAV.DATAAREAID AND ITM.MODULETYPE = 0
    JOIN [ax].INVENTDIM WID ON WID.INVENTDIMID = RIAV.INVENTDIMID AND WID.DATAAREAID = RIAV.DATAAREAID
    LEFT JOIN [ax].INVENTDIM VID
        ON VID.CONFIGID = WID.CONFIGID
            AND VID.INVENTSIZEID = WID.INVENTSIZEID
            AND VID.INVENTCOLORID = WID.INVENTCOLORID
            AND VID.INVENTSTYLEID = WID.INVENTSTYLEID
            AND VID.INVENTBATCHID = WID.INVENTBATCHID
            AND VID.WMSLOCATIONID = WID.WMSLOCATIONID
            AND VID.WMSPALLETID = WID.WMSPALLETID
            AND VID.INVENTSERIALID = WID.INVENTSERIALID
            AND VID.INVENTLOCATIONID = ''
            AND VID.INVENTSITEID = ''
            AND VID.DATAAREAID = WID.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[ITEMAVAILABILITYVIEW]'
GO
-- End creating view [crt].[ITEMAVAILABILITYVIEW]


GRANT SELECT ON [crt].[ITEMAVAILABILITYVIEW] TO [UsersRole];
GO

-- Creating view [crt].DELIVERYMODESEXPLODEDVIEW
PRINT N'Creating view [crt].DELIVERYMODESEXPLODEDVIEW';

GO
IF OBJECT_ID(N'[crt].DELIVERYMODESEXPLODEDVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].DELIVERYMODESEXPLODEDVIEW
GO

CREATE VIEW [crt].[DELIVERYMODESEXPLODEDVIEW] AS
(
    SELECT DISTINCT
        DM.[RECID],
        RCT.[RECID] as CHANNELID,
        DM.[CODE],
        DM.[TXT],
        DM.[MARKUPGROUP],
        DMProduct.[ITEMID],
        DMProduct.[INVENTDIM],
        DMAddress.[COUNTRYREGION],
        DMAddress.[STATE]
    FROM [ax].DLVMODE DM
    INNER JOIN [ax].RETAILDLVMODECHANNELEXPLODED DMChannel ON DM.RECID = DMChannel.DLVMODE
    INNER JOIN [ax].RETAILCHANNELTABLE RCT ON RCT.OMOPERATINGUNITID = DMChannel.OMOPERATINGUNIT
    LEFT OUTER JOIN [ax].RETAILDLVMODEPRODUCTEXPLODED DMProduct ON DM.RECID = DMProduct.DLVMODE AND RCT.INVENTLOCATIONDATAAREAID = DMProduct.DATAAREAID
    LEFT OUTER JOIN [ax].RETAILDLVMODEADDRESSEXPLODED DMAddress ON DM.RECID = DMAddress.DLVMODE AND DMProduct.DATAAREAID = DMAddress.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].DELIVERYMODESEXPLODEDVIEW'
GO
-- End creating view [crt].DELIVERYMODESEXPLODEDVIEW


GRANT SELECT ON [crt].[DELIVERYMODESEXPLODEDVIEW] TO [UsersRole];
GO

-- Creating view [crt].[DELIVERYMODESVIEW]
PRINT N'Creating view [crt].[DELIVERYMODESVIEW]';

GO
IF OBJECT_ID(N'[crt].[DELIVERYMODESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[DELIVERYMODESVIEW]
GO

CREATE VIEW [crt].[DELIVERYMODESVIEW] AS
(
    SELECT
        dm.RECID,
        dm.CODE,
        dm.TXT,
        dm.MARKUPGROUP,
dm.DATAAREAID
    FROM [ax].DLVMODE dm
)


GO
PRINT N'Finished creating view [crt].[DELIVERYMODESVIEW]'
GO
-- End creating view [crt].[DELIVERYMODESVIEW]


GRANT SELECT ON [crt].[DELIVERYMODESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[GETSUPPORTEDLANGUAGEIDSVIEW]
PRINT N'Creating view [crt].[GETSUPPORTEDLANGUAGEIDSVIEW]';

GO
IF OBJECT_ID(N'[crt].[GETSUPPORTEDLANGUAGEIDSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[GETSUPPORTEDLANGUAGEIDSVIEW]
GO

CREATE VIEW [crt].[GETSUPPORTEDLANGUAGEIDSVIEW] AS
(
    SELECT
        lt.[LANGUAGEID],
        lt.[RECID],
        lt.[USERDEFINEDLANGUAGE]
    FROM [ax].[LANGUAGETABLE] lt
)


GO
PRINT N'Finished creating view [crt].[GETSUPPORTEDLANGUAGEIDSVIEW]'
GO
-- End creating view [crt].[GETSUPPORTEDLANGUAGEIDSVIEW]


GRANT SELECT ON [crt].[GETSUPPORTEDLANGUAGEIDSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETSUPPORTEDLANGUAGEIDSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[GETEMPLOYEEBREAKCATEGORIESVIEW]
PRINT N'Creating view [crt].[GETEMPLOYEEBREAKCATEGORIESVIEW]';

GO
IF OBJECT_ID(N'[crt].[GETEMPLOYEEBREAKCATEGORIESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[GETEMPLOYEEBREAKCATEGORIESVIEW]
GO

/****************************************************************************************
GETEMPLOYEEBREAKCATEGORIESVIEW will retrieve the activities with job IDs for category 'Break'
*****************************************************************************************/
CREATE VIEW [crt].[GETEMPLOYEEBREAKCATEGORIESVIEW] AS
(
SELECTjmga.RECID, 
jmga.ACTIVITY AS BREAKCATEGORY, 
jmga.JOBID
FROM [ax].[JMGIPCACTIVITY] jmga
WHERE CATEGORY = 'BREAK' AND jmga.BREAKDROP = 0 AND jmga.SIGNIN = 1
)

GO
PRINT N'Finished creating view [crt].[GETEMPLOYEEBREAKCATEGORIESVIEW]'
GO
-- End creating view [crt].[GETEMPLOYEEBREAKCATEGORIESVIEW]


GRANT SELECT ON [crt].[GETEMPLOYEEBREAKCATEGORIESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CHANNELVIEW]
PRINT N'Creating view [crt].[CHANNELVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELVIEW]
GO

CREATE VIEW [crt].[CHANNELVIEW] AS
(
    SELECT
        rprct.ORIGINID AS RECID,
        rprct.CHANNELTYPE,
        rprct.CATEGORYHIERARCHY,
        dp.NAME,
        rprct.INVENTLOCATION,
        rprct.DEFAULTCUSTACCOUNT
    FROM [ax].RETAILPUBRETAILCHANNELTABLE rprct
    INNER JOIN [ax].DIRPARTYTABLE dp ON dp.RECID = rprct.OMOPERATINGUNITID
UNION ALL
    SELECT
        rct.RECID,
        rct.CHANNELTYPE,
        0 AS CATEGORYHIERARCHY,
        dp.NAME,
        rct.INVENTLOCATION,
        rct.DEFAULTCUSTACCOUNT
    FROM [ax].RETAILCHANNELTABLE rct
    INNER JOIN [ax].DIRPARTYTABLE dp ON dp.RECID = rct.OMOPERATINGUNITID
WHERE NOT EXISTS (SELECT * FROM [ax].RETAILPUBRETAILCHANNELTABLE rprct WHERE rprct.ORIGINID = rct.RECID)
)


GO
PRINT N'Finished creating view [crt].[CHANNELVIEW]'
GO
-- End creating view [crt].[CHANNELVIEW]


GRANT SELECT ON [crt].[CHANNELVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[STOREVIEW]
PRINT N'Creating view [crt].[STOREVIEW]';

GO
IF OBJECT_ID(N'[crt].[STOREVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[STOREVIEW]
GO

CREATE VIEW [crt].[STOREVIEW] AS
(
SELECT 
rct.RECID,
rct.RECID AS 'CHANNELID',
rct.CHANNELTYPE,
rct.INVENTLOCATIONDATAAREAID AS 'DATAAREAID',
rprct.CATEGORYHIERARCHY,
rct.EVENTNOTIFICATIONPROFILEID,
rst.STORENUMBER,
dp.NAME AS STORENAME,
rst.TAXGROUP,
rst.FUNCTIONALITYPROFILE,
rst.USECUSTOMERBASEDTAX,
rst.USEDESTINATIONBASEDTAX,
rct.DEFAULTCUSTACCOUNT,
rct.CURRENCY,
rct.INVENTLOCATION,
rst.INVENTLOCATIONIDFORCUSTOMERORDER as SHIPPINGINVENTLOCATION,
rst.OPENFROM,
rst.OPENTO,
lpa.RECID AS 'POSTALADDRESSRECID',
lpa.ADDRESS AS 'STOREADDRESS',
lpa.BUILDINGCOMPLIMENT,
lpa.CITY,
lpa.CITYRECID,
lpa.COUNTRYREGIONID,
lpa.COUNTY,
lpa.DISTRICT,
lpa.DISTRICTNAME,
lpa.ISPRIVATE,
lpa.LATITUDE,
lpa.LOCATION,
lpa.LONGITUDE,
lpa.POSTBOX,
lpa.STATE,
lpa.STREET,
lpa.STREETNUMBER,
lpa.ZIPCODE,
lpa.ZIPCODERECID,
lpa.MODIFIEDDATETIME,
geography::STGeomFromText('POINT(' + CONVERT(VARCHAR(100), lpa.LONGITUDE) + ' ' +  CONVERT(VARCHAR(100), lpa.LATITUDE) + ')', 4326) AS 'GEOLOCATION',
ll.RECID AS 'ELECTRONICADDRESSLOCATIONRECID',
lea.DESCRIPTION AS 'ELECTRONICADDRESSDESCRIPTION',
lea.TYPE AS 'ELECTRONICADDRESSTYPE',
lea.LOCATOR AS 'ELECTRONICADDRESSLOCATOR',
il.INVENTSITEID,
rfp.RETAILRECEIPTPROFILE AS EMAILRECEIPTPROFILEID,
(CASE WHEN rprct.RECID IS NULL THEN 0 ELSE 1 END) AS 'ISPUBLISHED'

FROM [ax].RETAILCHANNELTABLE rct
INNER JOIN [ax].RETAILSTORETABLE rst ON rct.RECID = rst.RECID
LEFT OUTER JOIN [ax].RETAILPUBRETAILCHANNELTABLE rprct ON rprct.ORIGINID = rct.RECID
LEFT OUTER JOIN [ax].DIRPARTYTABLE dp ON dp.RECID = rct.OMOPERATINGUNITID
LEFT OUTER JOIN [ax].RETAILFUNCTIONALITYPROFILE rfp ON rfp.PROFILEID = rst.FUNCTIONALITYPROFILE
-- ADDRESS INFORMATION
LEFT OUTER JOIN [ax].DIRPARTYLOCATION AS dpl ON dpl.PARTY = dp.RECID AND dpl.ISPRIMARY = 1
LEFT OUTER JOIN [ax].LOGISTICSLOCATION AS ll ON ll.PARENTLOCATION = dpl.LOCATION
LEFT OUTER JOIN [ax].LOGISTICSELECTRONICADDRESS AS lea ON lea.LOCATION = ll.RECID AND lea.ISPRIVATE = 0
LEFT OUTER JOIN [ax].INVENTLOCATION AS il ON rprct.INVENTLOCATION = il.INVENTLOCATIONID and rprct.INVENTLOCATIONDATAAREAID = il.DATAAREAID
LEFT OUTER JOIN [ax].LOGISTICSPOSTALADDRESS AS lpa ON 
lpa.LOCATION = dpl.LOCATION 
AND lpa.ISPRIVATE = 0 
AND GETUTCDATE() BETWEEN VALIDFROM AND VALIDTO
)


GO
PRINT N'Finished creating view [crt].[STOREVIEW]'
GO
-- End creating view [crt].[STOREVIEW]


GRANT SELECT ON [crt].[STOREVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[STOREVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[ONLINECHANNELVIEW]
PRINT N'Creating view [crt].[ONLINECHANNELVIEW]';

GO
IF OBJECT_ID(N'[crt].[ONLINECHANNELVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ONLINECHANNELVIEW]
GO

CREATE VIEW [crt].[ONLINECHANNELVIEW] AS
(
    SELECT
        rprct.ORIGINID AS RECID,
        rprct.CHANNELTYPE,
        rprct.CATEGORYHIERARCHY,
rprct.INVENTLOCATION,
        rocps.PUBLISHSTATUS,
        rocps.PUBLISHSTATUSMESSAGE,
        dpl.NAME AS 'ONLINECHANNELNAME',
        rprct.DEFAULTCUSTACCOUNT
    FROM [ax].RETAILPUBRETAILONLINECHANNELTABLE rproc
    INNER JOIN [ax].RETAILPUBRETAILCHANNELTABLE rprct ON rproc.ONLINECHANNELORIGINID = rprct.ORIGINID
    INNER JOIN [ax].RETAILONLINECHANNELPUBLISHSTATUS rocps ON rproc.ONLINECHANNELORIGINID = rocps.ONLINECHANNEL
    INNER JOIN [ax].DIRPARTYTABLE dpl ON rprct.OMOPERATINGUNITID = dpl.RECID
)


GO
PRINT N'Finished creating view [crt].[ONLINECHANNELVIEW]'
GO
-- End creating view [crt].[ONLINECHANNELVIEW]


GRANT SELECT ON [crt].[ONLINECHANNELVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[ONLINECHANNELVIEW] TO [PublishersRole];
GO

-- Creating view [crt].OPERATIONPERMISSIONSVIEW
PRINT N'Creating view [crt].OPERATIONPERMISSIONSVIEW';

GO
IF OBJECT_ID(N'[crt].OPERATIONPERMISSIONSVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].OPERATIONPERMISSIONSVIEW
GO

CREATE VIEW [crt].OPERATIONPERMISSIONSVIEW AS
(
    SELECT
        ops.OPERATIONID,
        ops.CHECKUSERACCESS,
        ops.OPERATIONNAME,
ops.PERMISSIONID,
ops.PERMISSIONID2,
CASE
WHEN perms1.PERMISSIONNAME IS NOT NULL AND perms2.PERMISSIONNAME IS NOT NULL
THEN perms1.PERMISSIONNAME + ',' + perms2.PERMISSIONNAME
ELSE COALESCE(perms1.PERMISSIONNAME, perms2.PERMISSIONNAME)
END AS PERMISSIONNAME,
ops.RECID
FROM [ax].RETAILOPERATIONS ops
LEFT JOIN [ax].RETAILPERMISSIONS perms1 ON perms1.PERMISSIONID = ops.PERMISSIONID
LEFT JOIN [ax].RETAILPERMISSIONS perms2 ON perms2.PERMISSIONID = ops.PERMISSIONID2
)


GO
PRINT N'Finished creating view [crt].OPERATIONPERMISSIONSVIEW'
GO
-- End creating view [crt].OPERATIONPERMISSIONSVIEW


GRANT SELECT ON [crt].OPERATIONPERMISSIONSVIEW TO [UsersRole];
GO

-- Creating view [crt].[REFERENCEATTRIBUTEVIEW]
PRINT N'Creating view [crt].[REFERENCEATTRIBUTEVIEW]';

GO
IF OBJECT_ID(N'[crt].[REFERENCEATTRIBUTEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[REFERENCEATTRIBUTEVIEW]
GO

CREATE VIEW [crt].[REFERENCEATTRIBUTEVIEW] WITH SCHEMABINDING AS
(
    SELECT  
        era.RECID AS ATTRIBUTE,
        errv.REFRECID AS REFERENCEDATTRIBUTE
        FROM ax.ECORESATTRIBUTE era
            JOIN ax.ECORESATTRIBUTETYPE erat 
                ON erat.RECID = era.ATTRIBUTETYPE
            JOIN ax.ECORESATTRIBUTEDEFAULTVALUE eradv 
                ON era.RECID = eradv.ATTRIBUTE
            JOIN ax.ECORESREFERENCEVALUE errv 
                ON errv.RECID = eradv.VALUE
        WHERE erat.DATATYPE = 20    -- Reference attribute type
)
GO

GO
PRINT N'Finished creating view [crt].[REFERENCEATTRIBUTEVIEW]'
GO
-- End creating view [crt].[REFERENCEATTRIBUTEVIEW]



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[REFERENCEATTRIBUTEVIEW]', N'U'), N'IX_REFERENCEATTRIBUTEVIEW_ATTRIBUTE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_REFERENCEATTRIBUTEVIEW_ATTRIBUTE'


CREATE UNIQUE CLUSTERED INDEX IX_REFERENCEATTRIBUTEVIEW_ATTRIBUTE ON [crt].[REFERENCEATTRIBUTEVIEW] 
(
    ATTRIBUTE
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_REFERENCEATTRIBUTEVIEW_ATTRIBUTE'



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[REFERENCEATTRIBUTEVIEW]', N'U'), N'IX_REFERENCEATTRIBUTEVIEW_REFERENCEDATTRIBUTE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_REFERENCEATTRIBUTEVIEW_REFERENCEDATTRIBUTE'


CREATE NONCLUSTERED INDEX IX_REFERENCEATTRIBUTEVIEW_REFERENCEDATTRIBUTE ON [crt].[REFERENCEATTRIBUTEVIEW] 
(
    REFERENCEDATTRIBUTE
) 
INCLUDE
(
    ATTRIBUTE    
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_REFERENCEATTRIBUTEVIEW_REFERENCEDATTRIBUTE'


GRANT SELECT ON [crt].[REFERENCEATTRIBUTEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[REFERENCEATTRIBUTEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[ATTRIBUTEVIEW]
PRINT N'Creating view [crt].[ATTRIBUTEVIEW]';

GO
IF OBJECT_ID(N'[crt].[ATTRIBUTEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ATTRIBUTEVIEW]
GO

CREATE VIEW [crt].[ATTRIBUTEVIEW] AS
WITH AttributeDataType AS
(
    SELECT
        era.RECID AS ATTRIBUTE,
        erat.RECID AS ATTRIBUTETYPE,
        erat.DATATYPE
        FROM ax.ECORESATTRIBUTE era
            JOIN ax.ECORESATTRIBUTETYPE erat 
                ON erat.RECID = era.ATTRIBUTETYPE
        WHERE erat.DATATYPE != 20   -- Non reference attribute type

    UNION ALL

    SELECT
        rav.ATTRIBUTE,
        erat.RECID AS ATTRIBUTETYPE,
        erat.DATATYPE
        FROM crt.REFERENCEATTRIBUTEVIEW rav
            JOIN ax.ECORESATTRIBUTE era
                ON era.RECID = rav.REFERENCEDATTRIBUTE
            JOIN ax.ECORESATTRIBUTETYPE erat 
                ON erat.RECID = era.ATTRIBUTETYPE
)
SELECT 
    adt.ATTRIBUTE,
    adt.DATATYPE AS RAWDATATYPE,
    CASE adt.ATTRIBUTETYPE
        WHEN rsp.IMAGESATTRIBUTETYPE  
            THEN 41     -- Image media attribute
        WHEN rsp.VIDEOSATTRIBUTETYPE
            THEN 40     -- Video media attribute
        ELSE
            adt.DATATYPE 
    END AS DATATYPE
    FROM AttributeDataType adt
        JOIN ax.RETAILSHAREDPARAMETERS rsp ON rsp.[KEY] = 0     -- KEY = 0 to make sure it is unique


GO
PRINT N'Finished creating view [crt].[ATTRIBUTEVIEW]'
GO
-- End creating view [crt].[ATTRIBUTEVIEW]


GRANT SELECT ON [crt].[ATTRIBUTEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[ATTRIBUTEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW]
PRINT N'Creating view [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW]
GO

CREATE VIEW [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW] AS
(
    SELECT
        erc.[PARENTCATEGORY],
        erc.[NAME],
        erc.[RECID] AS RECID
    FROM [ax].ECORESCATEGORY erc -- Cannot use RetailPub version since Retail product category is not published
    INNER JOIN [ax].ECORESCATEGORYHIERARCHYROLE erchr ON erchr.CATEGORYHIERARCHY = erc.CATEGORYHIERARCHY
    WHERE erchr.NAMEDCATEGORYHIERARCHYROLE = 4 -- Retail product category
)


GO
PRINT N'Finished creating view [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW]'
GO
-- End creating view [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW]


GRANT SELECT ON [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[RETAILPRODUCTCATEGORYHIERARCHYVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELCATEGORYHIERARCHYVIEW]
PRINT N'Creating view [crt].[CHANNELCATEGORYHIERARCHYVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELCATEGORYHIERARCHYVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELCATEGORYHIERARCHYVIEW]
GO

CREATE VIEW [crt].[CHANNELCATEGORYHIERARCHYVIEW] AS
(
    SELECT
        rpec.[PARENTCATEGORY],
        rpec.[NAME],
        rpec.[ORIGINID] AS RECID,
        rpct.[ORIGINID] AS CHANNELID
    FROM [ax].RETAILPUBRETAILCHANNELTABLE rpct
    INNER JOIN [ax].RETAILPUBECORESCATEGORY rpec ON rpct.[CATEGORYHIERARCHY] = rpec.[CATEGORYHIERARCHY] AND rpct.[ORIGINID] = rpec.[CHANNEL]
)


GO
PRINT N'Finished creating view [crt].[CHANNELCATEGORYHIERARCHYVIEW]'
GO
-- End creating view [crt].[CHANNELCATEGORYHIERARCHYVIEW]


GRANT SELECT ON [crt].[CHANNELCATEGORYHIERARCHYVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELCATEGORYHIERARCHYVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELCATEGORYATTRIBUTEVIEW]
PRINT N'Creating view [crt].[CHANNELCATEGORYATTRIBUTEVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELCATEGORYATTRIBUTEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELCATEGORYATTRIBUTEVIEW]
GO

CREATE VIEW [crt].[CHANNELCATEGORYATTRIBUTEVIEW] AS
(
    SELECT
        RPRCCA.HOSTCHANNEL
        ,RPRCCA.CATEGORY
        ,RPRCCA.KEYNAME
        ,RPRCCA.ATTRIBUTEVALUE AS ATTRIBUTEVALUERECID
,ERC.NAME AS CATEGORYNAME
        ,ERCH.NAME AS CATEGORYHIERARCHYNAME
        ,[crt].GETCATEGORYPATH(RPRCCA.HOSTCHANNEL, RPRCCA.CATEGORY) AS CATEGORYPATH
        ,ERA.NAME
,CASE ERAT.RECID
    WHEN RSP.IMAGESATTRIBUTETYPE  
    THEN 41 -- 41 = IMAGE MEDIA ATTRIBUTE
WHEN RSP.VIDEOSATTRIBUTETYPE
    THEN 40 -- 40 = VIDEO MEDIA ATTRIBUTE
ELSE
ERAT.DATATYPE 
END AS [DATATYPE] 
        ,ERBV.BOOLEANVALUE
        ,ERDTV.DATETIMEVALUE
        ,ERFV.FLOATVALUE
        ,FUOM.SYMBOL AS FLOATUNITSYMBOL
        ,ERV.INTVALUE
        ,IUOM.SYMBOL AS INTUNITSYMBOL
        ,ERTV.TEXTVALUE
        ,ERCV.CURRENCYCODE
        ,ERCV.CURRENCYVALUE
    FROM [ax].RETAILPUBRETAILCHANNELCATEGORYATTRIBUTE RPRCCA
    INNER JOIN [ax].ECORESCATEGORY ERC on ERC.RECID = RPRCCA.CATEGORY
INNER JOIN [ax].RETAILPUBECORESCATEGORY RPERC ON RPERC.CHANNEL = RPRCCA.HOSTCHANNEL AND RPERC.ORIGINID = ERC.RECID
    INNER JOIN ax.ECORESCATEGORYHIERARCHY ERCH on ERCH.RECID = ERC.CATEGORYHIERARCHY
    INNER JOIN [crt].ATTRIBUTEMAPVIEW AS AMV ON AMV.ATTRIBUTE = RPRCCA.ATTRIBUTE
    INNER JOIN [ax].ECORESATTRIBUTE ERA ON AMV.ACTUALATTRIBUTE = ERA.RECID
    INNER JOIN [ax].ECORESATTRIBUTETYPE ERAT ON ERA.ATTRIBUTETYPE =ERAT.RECID
    INNER JOIN [ax].RETAILSHAREDPARAMETERS RSP ON RSP.[KEY] = 0 -- KEY = 0 to make sure it is unique
    LEFT OUTER JOIN [ax].ECORESBOOLEANVALUE ERBV ON RPRCCA.ATTRIBUTEVALUE = ERBV.RECID
    LEFT OUTER JOIN [ax].ECORESDATETIMEVALUE ERDTV ON RPRCCA.ATTRIBUTEVALUE = ERDTV.RECID
    LEFT OUTER JOIN [ax].ECORESFLOATVALUE ERFV ON RPRCCA.ATTRIBUTEVALUE = ERFV.RECID
    LEFT OUTER JOIN [ax].UNITOFMEASURE FUOM ON erfv.FLOATUNITOFMEASURE = FUOM.RECID
    LEFT OUTER JOIN [ax].ECORESINTVALUE ERV ON RPRCCA.ATTRIBUTEVALUE = ERV.RECID
    LEFT OUTER JOIN [ax].UNITOFMEASURE IUOM ON ERV.INTUNITOFMEASURE = IUOM.RECID
    LEFT OUTER JOIN [ax].ECORESTEXTVALUE ERTV ON RPRCCA.ATTRIBUTEVALUE = ERTV.RECID
    LEFT OUTER JOIN [ax].ECORESCURRENCYVALUE ERCV ON RPRCCA.ATTRIBUTEVALUE = ERCV.RECID
)


GO
PRINT N'Finished creating view [crt].[CHANNELCATEGORYATTRIBUTEVIEW]'
GO
-- End creating view [crt].[CHANNELCATEGORYATTRIBUTEVIEW]


GRANT SELECT ON [crt].[CHANNELCATEGORYATTRIBUTEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELCATEGORYATTRIBUTEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELPRODUCTATTRIBUTEVIEW]
PRINT N'Creating view [crt].[CHANNELPRODUCTATTRIBUTEVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELPRODUCTATTRIBUTEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELPRODUCTATTRIBUTEVIEW]
GO

CREATE VIEW [crt].[CHANNELPRODUCTATTRIBUTEVIEW] AS
(
    SELECT
        rpracm.ORIGINID AS RECID,
        rpracm.HOSTCHANNEL,
        era.NAME,
        av.DATATYPE,
        rpracm.KEYNAME,
        rpracm.METADATA,
        rpracm.METADATAVERSION,
        rpracm.ATTRIBUTERELATIONTYPE,
        era.RECID AS 'ATTRIBUTE'
    FROM [ax].RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA rpracm
    INNER JOIN [ax].ECORESATTRIBUTE era ON era.RECID = rpracm.ATTRIBUTE
    INNER JOIN [crt].ATTRIBUTEVIEW av ON av.ATTRIBUTE = rpracm.ATTRIBUTE
)


GO
PRINT N'Finished creating view [crt].[CHANNELPRODUCTATTRIBUTEVIEW]'
GO
-- End creating view [crt].[CHANNELPRODUCTATTRIBUTEVIEW]


GRANT SELECT ON [crt].[CHANNELPRODUCTATTRIBUTEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELPRODUCTATTRIBUTEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELPROFILEVIEW]
PRINT N'Creating view [crt].[CHANNELPROFILEVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELPROFILEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELPROFILEVIEW]
GO

CREATE VIEW [crt].[CHANNELPROFILEVIEW] AS
(
SELECT 
        cp.[RECID],
        cp.[NAME],
        channelExt.[CHANNEL],
        cpp.[KEY],
        cpp.[VALUE],
        cp.[CHANNELPROFILETYPE]
    FROM [ax].RETAILCHANNELPROFILE AS cp
    INNER JOIN [ax].RETAILCHANNELTABLEEXT AS channelExt ON channelExt.CHANNELPROFILE = cp.RECID
    LEFT OUTER JOIN [ax].RETAILCHANNELPROFILEPROPERTY AS cpp ON cpp.CHANNELPROFILE = cp.RECID
)


GO
PRINT N'Finished creating view [crt].[CHANNELPROFILEVIEW]'
GO
-- End creating view [crt].[CHANNELPROFILEVIEW]


GRANT SELECT ON [crt].[CHANNELPROFILEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELPROFILEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELATTRIBUTEVIEW]
PRINT N'Creating view [crt].[CHANNELATTRIBUTEVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELATTRIBUTEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELATTRIBUTEVIEW]
GO

CREATE VIEW [crt].[CHANNELATTRIBUTEVIEW] AS
(
    SELECT
        rpca.RECID,
        rpca.CHANNEL,
        rpca.ATTRIBUTEVALUE AS ATTRIBUTEVALUERECID,
        era.NAME,
        erat.DATATYPE,
        erbv.BOOLEANVALUE,
        erdtv.DATETIMEVALUE,
        erfv.FLOATVALUE,
        fuom.SYMBOL AS FLOATUNITSYMBOL,
        eriv.INTVALUE,
        iuom.SYMBOL AS INTUNITSYMBOL,
        ertv.TEXTVALUE,
        ercv.CURRENCYCODE,
        ercv.CURRENCYVALUE
    FROM [ax].RETAILPUBCHANNELATTRIBUTE rpca
    INNER JOIN [ax].ECORESATTRIBUTE era ON era.RECID = rpca.ATTRIBUTE
    INNER JOIN [ax].ECORESATTRIBUTETYPE erat ON era.ATTRIBUTETYPE = erat.RECID
    LEFT OUTER JOIN [ax].ECORESBOOLEANVALUE erbv ON rpca.ATTRIBUTEVALUE = erbv.RECID
    LEFT OUTER JOIN [ax].ECORESDATETIMEVALUE erdtv ON rpca.ATTRIBUTEVALUE = erdtv.RECID
    LEFT OUTER JOIN [ax].ECORESFLOATVALUE erfv ON rpca.ATTRIBUTEVALUE = erfv.RECID
    LEFT OUTER JOIN [ax].UNITOFMEASURE AS fuom ON erfv.FLOATUNITOFMEASURE = fuom.RECID
    LEFT OUTER JOIN [ax].ECORESINTVALUE eriv ON rpca.ATTRIBUTEVALUE = eriv.RECID
    LEFT OUTER JOIN [ax].UNITOFMEASURE AS iuom ON eriv.INTUNITOFMEASURE = iuom.RECID
    LEFT OUTER JOIN [ax].ECORESTEXTVALUE ertv ON rpca.ATTRIBUTEVALUE = ertv.RECID
    LEFT OUTER JOIN [ax].ECORESCURRENCYVALUE ercv ON rpca.ATTRIBUTEVALUE = ercv.RECID
)


GO
PRINT N'Finished creating view [crt].[CHANNELATTRIBUTEVIEW]'
GO
-- End creating view [crt].[CHANNELATTRIBUTEVIEW]


GRANT SELECT ON [crt].[CHANNELATTRIBUTEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CHANNELPROPERTIESVIEW]
PRINT N'Creating view [crt].[CHANNELPROPERTIESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELPROPERTIESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELPROPERTIESVIEW]
GO

CREATE VIEW [crt].[CHANNELPROPERTIESVIEW] AS
(
    SELECT
        rcp.RECID,
        rcp.CHANNEL,
        rcp.NAME,
        rcp.VALUE
    FROM [crt].RETAILCHANNELPROPERTIES AS rcp
)


GO
PRINT N'Finished creating view [crt].[CHANNELPROPERTIESVIEW]'
GO
-- End creating view [crt].[CHANNELPROPERTIESVIEW]


GRANT SELECT ON [crt].[CHANNELPROPERTIESVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELPROPERTIESVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[PRICEGROUPSVIEW]
PRINT N'Creating view [crt].[PRICEGROUPSVIEW]';

GO
IF OBJECT_ID(N'[crt].[PRICEGROUPSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PRICEGROUPSVIEW]
GO

CREATE VIEW [crt].[PRICEGROUPSVIEW] AS
(
    SELECT
        [rcpg].[RECID],
        [rcpg].[PRICEGROUP],
        [pdg].[GROUPID],
        [rcpg].[RETAILCHANNEL] AS CHANNELID
    FROM [ax].PRICEDISCGROUP pdg
    INNER JOIN [ax].RETAILCHANNELPRICEGROUP rcpg ON rcpg.PRICEGROUP = pdg.RECID
)


GO
PRINT N'Finished creating view [crt].[PRICEGROUPSVIEW]'
GO
-- End creating view [crt].[PRICEGROUPSVIEW]


GRANT SELECT ON [crt].[PRICEGROUPSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PRICEGROUPSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[POSTALADDRESSESVIEW]
PRINT N'Creating view [crt].[POSTALADDRESSESVIEW]';

GO
IF OBJECT_ID(N'[crt].[POSTALADDRESSESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[POSTALADDRESSESVIEW]
GO
/********************************************************************************
    POSTALADDRESSESVIEW retrieves the postal address and location of the Stores.
The view joins with the tables: DIRPARTYLOCATION, LOGISTICSPOSTALADDRESSVIEW, DIRPARTYLOCATIONROLE, LOGISTICSLOCATIONROLE
********************************************************************************/

CREATE VIEW [crt].[POSTALADDRESSESVIEW] AS
(
    SELECT
        dpl.PARTY AS PARTY,
        dpl.RECID AS PARTYLOCATION,
        dpl.ISPRIMARY AS ISPRIMARY,
        dpl.ISPRIVATE AS ISPRIVATE,
        dpl.ISLOCATIONOWNER AS ISLOCATIONOWNER,
        dpl.RECID AS RECID,
        LPA.LOCATIONNAME AS LOCATIONNAME,
        LPA.ADDRESS AS ADDRESS,
        LPA.STREETNUMBER AS STREETNUMBER,
        LPA.STREET AS STREET,
        LPA.CITY AS CITY,
        LPA.ZIPCODE AS ZIPCODE,
        LPA.STATE AS STATE,
        LPA.COUNTY AS COUNTY,
        LPA.COUNTRYREGIONID AS COUNTRYREGIONID,
        LPA.DISTRICT AS DISTRICT,
        LPA.POSTBOX AS POSTBOX,
        LPA.BUILDINGCOMPLIMENT AS BUILDINGCOMPLIMENT,
        LPA.TIMEZONE AS TIMEZONE,
        LPA.LONGITUDE AS LONGITUDE,
        LPA.LATITUDE AS LATITUDE,
        LPA.LOCATION AS LOCATION,
        LPA.VALIDFROM AS VALIDFROM,
        LPA.VALIDTO AS VALIDTO,
        LPA.COUNTRYCURRENCYCODE AS COUNTRYCURRENCYCODE,
        LPA.DISTRICTNAME AS DISTRICTNAME,
        LPA.POSTALADDRESS AS POSTALADDRESS,
        LPA.ISOCODE AS ISOCODE
    FROM  [ax].[DIRPARTYLOCATION] dpl
    LEFT OUTER JOIN [crt].[LOGISTICSPOSTALADDRESSESVIEW] LPA ON (dpl.LOCATION = LPA.LOCATION)
    WHERE (dpl.ISPOSTALADDRESS = 1)
        AND NOT EXISTS (
            SELECT 1 FROM [ax].[DIRPARTYLOCATIONROLE] dplR
            WHERE (dplR.PARTYLOCATION = dpl.RECID)
        AND EXISTS (
            SELECT 1 FROM [ax].[LOGISTICSLOCATIONROLE] LLR
            WHERE ((LLR.TYPE=16) AND (dplR.LOCATIONROLE=LLR.RECID))))
)


GO
PRINT N'Finished creating view [crt].[POSTALADDRESSESVIEW]'
GO
-- End creating view [crt].[POSTALADDRESSESVIEW]


GRANT SELECT ON [crt].[POSTALADDRESSESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CATALOGPRICEGROUPSVIEW]
PRINT N'Creating view [crt].[CATALOGPRICEGROUPSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATALOGPRICEGROUPSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATALOGPRICEGROUPSVIEW]
GO

CREATE VIEW [crt].[CATALOGPRICEGROUPSVIEW] AS
(
    SELECT
        [rcpg].[RECID],
        [rcpg].[PRICEDISCGROUP] AS 'PRICEGROUP',
        [pdg].[GROUPID],
        [rcpg].[CATALOG] AS CATALOGID,
[c].[RECID] AS CHANNELID
    FROM [ax].PRICEDISCGROUP pdg
    INNER JOIN [ax].RETAILPUBRETAILCATALOGPRICEGROUP rcpg ON rcpg.PRICEDISCGROUP = pdg.RECID
    INNER JOIN [ax].RETAILCHANNELTABLE c on c.INVENTLOCATIONDATAAREAID = pdg.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[CATALOGPRICEGROUPSVIEW]'
GO
-- End creating view [crt].[CATALOGPRICEGROUPSVIEW]


GRANT SELECT ON [crt].[CATALOGPRICEGROUPSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CATALOGPRICEGROUPSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[AFFILIATIONPRICEGROUPSVIEW]
PRINT N'Creating view [crt].[AFFILIATIONPRICEGROUPSVIEW]';

GO
IF OBJECT_ID(N'[crt].[AFFILIATIONPRICEGROUPSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[AFFILIATIONPRICEGROUPSVIEW]
GO

CREATE VIEW [crt].[AFFILIATIONPRICEGROUPSVIEW] AS
(
    SELECT
        [rapg].[RECID],
        [rapg].[PRICEDISCGROUP],
        [pdg].[GROUPID],
        [rapg].[RETAILAFFILIATION] AS AFFILIATIONID,
        [c].[RECID] AS CHANNELID

    FROM [ax].PRICEDISCGROUP pdg
    INNER JOIN [ax].RETAILAFFILIATIONPRICEGROUP rapg ON rapg.PRICEDISCGROUP = pdg.RECID
    INNER JOIN [ax].RETAILCHANNELTABLE c on c.INVENTLOCATIONDATAAREAID = pdg.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[AFFILIATIONPRICEGROUPSVIEW]'
GO
-- End creating view [crt].[AFFILIATIONPRICEGROUPSVIEW]


GRANT SELECT ON [crt].[AFFILIATIONPRICEGROUPSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[AFFILIATIONPRICEGROUPSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[RETAILDISCOUNTPRICEGROUPSVIEW]
PRINT N'Creating view [crt].[RETAILDISCOUNTPRICEGROUPSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILDISCOUNTPRICEGROUPSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILDISCOUNTPRICEGROUPSVIEW]
GO

CREATE VIEW [crt].[RETAILDISCOUNTPRICEGROUPSVIEW] AS
(
    SELECT
        [rdpg].[RECID],
        [rdpg].[PRICEDISCGROUP] AS 'PRICEGROUP',
        [pdg].[GROUPID],
        [rdpg].[OFFERID],
[pdg].[DATAAREAID]
    FROM [ax].PRICEDISCGROUP pdg
    INNER JOIN [ax].RETAILDISCOUNTPRICEGROUP rdpg ON rdpg.PRICEDISCGROUP = pdg.RECID AND rdpg.DATAAREAID = pdg.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[RETAILDISCOUNTPRICEGROUPSVIEW]'
GO
-- End creating view [crt].[RETAILDISCOUNTPRICEGROUPSVIEW]


GRANT SELECT ON [crt].[RETAILDISCOUNTPRICEGROUPSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[RETAILDISCOUNTPRICEGROUPSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW]
PRINT N'Creating view [crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW]
GO

CREATE VIEW [crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW] AS
(
    SELECT
       pd.[OFFERID]
       ,pd.[NAME]
       ,pd.[PERIODICDISCOUNTTYPE]
       ,pd.[PRICEDISCGROUP]
       ,pd.[VALIDATIONPERIODID]
       ,pd.[DATEVALIDATIONTYPE]
       ,pd.[VALIDFROM]
       ,pd.[VALIDTO]
       ,pd.[CONCURRENCYMODE]
       ,pd.[CURRENCYCODE]
       ,pd.[STATUS]
       ,pd.[ISDISCOUNTCODEREQUIRED]
   ,pd.[DATAAREAID]
       ,ISNULL(pdmm.MIXANDMATCHDISCOUNTTYPE
       ,ISNULL(pdmb.MULTIBUYDISCOUNTTYPE, pd.PERIODICDISCOUNTTYPE)) AS DISCOUNTTYPE
       ,0 AS DIFFERENTSAMEMANDMLINES
       ,0 AS NOOFLINESTOTRIGGER
       ,0 AS PRIORITY
       ,pd.[DISCOUNTPERCENTVALUE]
       ,ISNULL(pdmm.[DEALPRICEVALUE],0.0) AS DEALPRICEVALUE
       ,ISNULL(pdmm.[DISCOUNTAMOUNTVALUE],0.0) AS DISCOUNTAMOUNTVALUE
       ,ISNULL(pdmm.[NOOFLEASTEXPENSIVELINES],0) AS NOOFLEASTEXPENSIVELINES
       ,ISNULL(pdmm.[NUMBEROFTIMESAPPLICABLE],0) AS NUMBEROFTIMESAPPLICABLE
       ,pdl.[RETAILGROUPMEMBERLINE]
       ,pdl.[RECID] AS DISCOUNTLINEID
       ,pdl.[LINENUM]
       ,pdl.[DISCOUNTPERCENTORVALUE]
       ,pdl.[UNITOFMEASURE]
       ,pdt.[COUNTNONDISCOUNTITEMS]
    FROM [ax].[RETAILPERIODICDISCOUNT] AS pd
    INNER JOIN [ax].[RETAILPERIODICDISCOUNTLINE] AS pdl ON pd.OFFERID = pdl.OFFERID AND pd.DATAAREAID = pdl.DATAAREAID
    LEFT OUTER JOIN [ax].[RETAILDISCOUNTMIXANDMATCH] AS pdmm ON pd.RECID = pdmm.RECID
    LEFT OUTER JOIN [ax].[RETAILDISCOUNTMULTIBUY] AS pdmb ON pd.RECID = pdmb.RECID
    LEFT OUTER JOIN [ax].[RETAILDISCOUNTTHRESHOLD] AS pdt ON pd.RECID = pdt.RECID
)


GO
PRINT N'Finished creating view [crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW]'
GO
-- End creating view [crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW]


GRANT SELECT ON [crt].[RETAILPERIODICDISCOUNTSFLATTENEDVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILMIXANDMATCHLINEGROUPSVIEW]
PRINT N'Creating view [crt].[RETAILMIXANDMATCHLINEGROUPSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILMIXANDMATCHLINEGROUPSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILMIXANDMATCHLINEGROUPSVIEW]
GO

CREATE VIEW [crt].[RETAILMIXANDMATCHLINEGROUPSVIEW] AS
(
    SELECT DISTINCT
        lg.MIXANDMATCHID AS OFFERID,
        lg.MIXANDMATCHLINEGROUP AS LINEGROUP,
        lg.NUMBEROFITEMSNEEDED AS NUMBEROFITEMSNEEDED,
        lg.RECID AS RECID,
c.RECID AS CHANNELID
    FROM [ax].[RETAILMIXANDMATCHLINEGROUPS] AS lg
    INNER JOIN [ax].[RETAILPERIODICDISCOUNTLINE] AS dl ON dl.OFFERID = lg.MIXANDMATCHID AND dl.DATAAREAID = lg.DATAAREAID 
    INNER JOIN [ax].[RETAILDISCOUNTLINEMIXANDMATCH] AS mml ON dl.RECID = mml.RECID AND lg.MIXANDMATCHLINEGROUP = mml.LINEGROUP AND lg.DATAAREAID = mml.DATAAREAID
INNER JOIN [ax].RETAILCHANNELTABLE c on c.INVENTLOCATIONDATAAREAID = lg.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[RETAILMIXANDMATCHLINEGROUPSVIEW]'
GO
-- End creating view [crt].[RETAILMIXANDMATCHLINEGROUPSVIEW]


GRANT SELECT ON [crt].[RETAILMIXANDMATCHLINEGROUPSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW]
PRINT N'Creating view [crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW]';

GO
IF OBJECT_ID(N'[crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW]
GO

CREATE VIEW [crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW] AS
(
    SELECT
        dlv.CODE AS DELIVERYMODEID,
        'Name' AS KEYNAME,
        rsci.CARRIERADAPTERID AS KEYVALUE,
        dlv.RECID AS RECID,
dlv.DATAAREAID
    FROM [ax].DLVMODE dlv
    INNER JOIN [ax].SHIPCARRIERTABLE sct ON dlv.SHIPCARRIERID = sct.CARRIERID AND dlv.DATAAREAID = sct.DATAAREAID
    INNER JOIN [ax].RETAILSHIPCARRIERINTERFACE rsci ON rsci.RECID = sct.RETAILSHIPCARRIERINTERFACE AND rsci.DATAAREAID = sct.DATAAREAID

    UNION

    SELECT
        dlv.CODE AS DELIVERYMODEID,
        rscac.PROPERTYKEY AS KEYNAME,
        rscac.VALUE AS KEYVALUE,
        rscac.RECID AS RECID,
dlv.DATAAREAID
    FROM [ax].DLVMODE dlv
    INNER JOIN [ax].SHIPCARRIERCOMPANYACCOUNTS scca ON scca.CARRIERNAME = dlv.SHIPCARRIERNAME AND scca.ACCOUNTCODE = dlv.SHIPCARRIERACCOUNTCODE AND scca.DATAAREAID = dlv.DATAAREAID
    INNER JOIN [ax].RETAILSHIPCARRIERACCOUNTCONFIGURATION rscac ON rscac.SHIPCARRIERCOMPANYACCOUNTS = scca.RECID AND rscac.DATAAREAID = scca.DATAAREAID

    UNION

    SELECT
        dlv.CODE AS DELIVERYMODEID,
        'CurrencyCode' AS KEYNAME,
        scca.CURRENCYCODE AS KEYVALUE,
        scca.RECID AS RECID,
dlv.DATAAREAID
    FROM [ax].DLVMODE dlv
    INNER JOIN [ax].SHIPCARRIERCOMPANYACCOUNTS scca ON scca.CARRIERNAME = dlv.SHIPCARRIERNAME AND scca.ACCOUNTCODE = dlv.SHIPCARRIERACCOUNTCODE AND scca.DATAAREAID = dlv.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW]'
GO
-- End creating view [crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW]


GRANT SELECT ON [crt].[SHIPPINGADAPTERCONFIGURATIONBYDELIVERYMODEIDVIEW] TO [UsersRole];
GO

-- Creating view [crt].[SHIPMENTLINEMATCHINGVIEW]
PRINT N'Creating view [crt].[SHIPMENTLINEMATCHINGVIEW]';

GO
IF OBJECT_ID(N'[crt].[SHIPMENTLINEMATCHINGVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SHIPMENTLINEMATCHINGVIEW]
GO

CREATE VIEW [crt].[SHIPMENTLINEMATCHINGVIEW] AS
(
    SELECT
        RTOS.SALESID,
        PST.PACKINGSLIPID,
        RTS.LINENUM SALESLINENUM,
        PST.LINENUM PACKINGSLIPLINENUM
    FROM [ax].CUSTPACKINGSLIPTRANS PST
    LEFT JOIN [ax].INVENTDIM IVD_PST on IVD_PST.INVENTDIMID = PST.INVENTDIMID AND IVD_PST.DATAAREAID = PST.DATAAREAID    -- get packing slip item dimensions
    INNER JOIN [ax].RETAILTRANSACTIONORDERSTATUS RTOS ON RTOS.SALESID = PST.SALESID AND RTOS.DATAAREAID = PST.DATAAREAID -- get transactionId
    INNER JOIN [ax].RETAILTRANSACTIONSALESTRANS RTS ON RTOS.TRANSACTIONID = RTS.TRANSACTIONID  AND PST.ITEMID = RTS.ITEMID AND RTOS.DATAAREAID = RTS.DATAAREAID -- get sales lines
    LEFT JOIN [ax].INVENTDIM IVD_RTS ON IVD_RTS.INVENTDIMID = RTS.INVENTDIMID AND IVD_RTS.DATAAREAID = RTS.DATAAREAID  -- get sales line item dimensions
)


GO
PRINT N'Finished creating view [crt].[SHIPMENTLINEMATCHINGVIEW]'
GO
-- End creating view [crt].[SHIPMENTLINEMATCHINGVIEW]


GRANT SELECT ON [crt].[SHIPMENTLINEMATCHINGVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[SHIPMENTLINEMATCHINGVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[SHIFTACCOUNTSVIEW]
PRINT N'Creating view [crt].[SHIFTACCOUNTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[SHIFTACCOUNTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SHIFTACCOUNTSVIEW]
GO

CREATE VIEW [crt].[SHIFTACCOUNTSVIEW]
AS
(
SELECTACCOUNTLINE.ACCOUNTNUM AS INCOMEEXEPENSEACCOUNT,
ACCOUNTLINE.ACCOUNTTYPE,
ACCOUNTLINE.AMOUNT,
ACCOUNTLINE.CHANNEL,
ACCOUNTLINE.BATCHID AS SHIFTID,
ACCOUNTLINE.TERMINALID,
ACCOUNTLINE.STOREID

FROM [ax].[RETAILPOSBATCHACCOUNTTRANS] ACCOUNTLINE
)
GO


GO
PRINT N'Finished creating view [crt].[SHIFTACCOUNTSVIEW]'
GO
-- End creating view [crt].[SHIFTACCOUNTSVIEW]


GRANT SELECT ON [crt].[SHIFTACCOUNTSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[WAREHOUSEADDRESSVIEW]
PRINT N'Creating view [crt].[WAREHOUSEADDRESSVIEW]';

GO
IF OBJECT_ID(N'[crt].[WAREHOUSEADDRESSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[WAREHOUSEADDRESSVIEW]
GO

CREATE VIEW [crt].[WAREHOUSEADDRESSVIEW] AS
(
    SELECT
       il.[DATAAREAID],
       il.[INVENTLOCATIONID],
       lpa.[COUNTRYREGIONID],
       lpa.[ZIPCODE],
       lpa.[STATE],
       lpa.[COUNTY],
       lpa.[CITY],
       lpa.[STREET],
       lpa.[STREETNUMBER],
       lpa.[DISTRICTNAME],
       lpa.[RECID],
       ISNULL(lacr.ISOCODE, '') AS ISOCODE,
       lpa.[VALIDFROM],
       lpa.[VALIDTO]
    FROM [ax].INVENTLOCATION il
    INNER JOIN [ax].INVENTLOCATIONLOGISTICSLOCATION illl ON il.RECID = illl.INVENTLOCATION
    INNER JOIN [ax].LOGISTICSLOCATION ll ON ll.RECID = illl.LOCATION
    INNER JOIN [ax].LOGISTICSPOSTALADDRESS lpa ON lpa.LOCATION = ll.RECID
    LEFT JOIN [ax].LOGISTICSADDRESSCOUNTRYREGION lacr ON lacr.COUNTRYREGIONID = lpa.COUNTRYREGIONID
    WHERE
        lpa.ISPRIVATE = 0
        AND illl.ISPRIMARY = 1
        AND illl.ISPOSTALADDRESS = 1
)


GO
PRINT N'Finished creating view [crt].[WAREHOUSEADDRESSVIEW]'
GO
-- End creating view [crt].[WAREHOUSEADDRESSVIEW]


GRANT SELECT ON [crt].[WAREHOUSEADDRESSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[ITEMPHYSICALDIMENSIONSVIEW]
PRINT N'Creating view [crt].[ITEMPHYSICALDIMENSIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[ITEMPHYSICALDIMENSIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ITEMPHYSICALDIMENSIONSVIEW]
GO

CREATE VIEW [crt].[ITEMPHYSICALDIMENSIONSVIEW] AS
(
    SELECT
       it.[RECID],
       it.[ITEMID],
       it.[GROSSDEPTH],
       it.[GROSSHEIGHT],
       it.[GROSSWIDTH],
       it.[NETWEIGHT],
       it.[TARAWEIGHT],
       it.[DATAAREAID]
    FROM [ax].INVENTTABLE it
)


GO
PRINT N'Finished creating view [crt].[ITEMPHYSICALDIMENSIONSVIEW]'
GO
-- End creating view [crt].[ITEMPHYSICALDIMENSIONSVIEW]


GRANT SELECT ON [crt].[ITEMPHYSICALDIMENSIONSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW] AS
(
    SELECT
        AT.TRANSACTIONID
        ,AT.NAME
        ,AT.TEXTVALUE
    FROM [ax].[RETAILTRANSACTIONATTRIBUTETRANS] AT
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONATTRIBUTETRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW] AS
(
    SELECT
DT.[AMOUNT],
DT.[CUSTOMERDISCOUNTTYPE],
DT.[DISCOUNTCODE],
DT.[DEALPRICE],
DT.[DISCOUNTAMOUNT],
DT.[DISCOUNTORIGINTYPE] AS [DISCOUNTLINETYPE],
DT.[LINENUM],
DT.[MANUALDISCOUNTTYPE],
DT.[PERCENTAGE],
DT.[PERIODICDISCOUNTOFFERID],                
RPD.[NAME] AS [OFFERNAME],
DT.[SALELINENUM],
DT.[TRANSACTIONID]
    FROM [ax].RETAILTRANSACTIONDISCOUNTTRANS DT
LEFT JOIN [ax].RETAILPERIODICDISCOUNT RPD ON RPD.OFFERID = DT.PERIODICDISCOUNTOFFERID
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONDISCOUNTTRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONINFOCODETRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONINFOCODETRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONINFOCODETRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONINFOCODETRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONINFOCODETRANSVIEW] AS
(
    SELECT
      IT.AMOUNT AS 'AMOUNT'
      ,IT.CHANNEL AS 'CHANNEL'
      ,IT.COUNTER AS 'COUNTER'
      ,IT.INFOAMOUNT AS 'INFOAMOUNT'
      ,IT.INFOCODEID AS 'INFOCODEID'
      ,IT.INFORMATION AS 'INFORMATION'
      ,IT.INPUTTYPE AS 'INPUTTYPE'
      ,IT.ITEMTENDER AS 'ITEMTENDER'
      ,IT.LINENUM AS 'LINENUM'
      ,IT.PARENTLINENUM AS 'PARENTLINENUM'
      ,IT.REPLICATED AS 'REPLICATED'
      ,IT.REPLICATIONCOUNTERFROMORIGIN AS 'REPLICATIONCOUNTERFROMORIGIN'
      ,IT.SOURCECODE AS 'SOURCECODE'
      ,IT.SOURCECODE2 AS 'SOURCECODE2'
      ,IT.SOURCECODE3 AS 'SOURCECODE3'
      ,IT.STAFF AS 'STAFF'
      ,IT.STATEMENTCODE AS 'STATEMENTCODE'
      ,IT.STORE AS 'STORE'
      ,IT.SUBINFOCODEID AS 'SUBINFOCODEID'
      ,IT.TERMINAL AS 'TERMINAL'
      ,IT.TRANSACTIONID AS 'TRANSACTIONID'
      ,IT.TRANSDATE AS 'TRANSDATE'
      ,IT.TRANSTIME AS 'TRANSTIME'
      ,IT.TYPE AS 'TYPE'
      ,IT.DATAAREAID AS 'DATAAREAID'
      ,IT.ROWVERSION AS 'ROWVERSION'
    FROM [ax].RETAILTRANSACTIONINFOCODETRANS IT
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONINFOCODETRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONINFOCODETRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONINFOCODETRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW] AS
(
SELECT
 RPT.[AMOUNTCUR] AS [AMOUNTINTENDEREDCURRENCY]
,RPT.[AMOUNTMST] AS [AMOUNTINCOMPANYCURRENCY]
,RPT.[AMOUNTTENDERED] AS [AMOUNTINSTORECURRENCY]
,RPT.[AUTHENTICATIONCODE]
,RPT.[CARDORACCOUNT]
,RPT.[CARDTYPEID]
,RPT.[CHANGELINE] AS [ISCHANGELINE]
,RPT.[CHANNEL] AS [CHANNELID]
,RPT.[COUNTER]
,RPT.[CREDITVOUCHERID] AS [CREDITMEMOID]
,RPT.[CURRENCY]
,RPT.[EXCHRATE]/100.00 AS [EXCHANGERATE]  --ePOS behaviour
,RPT.[EXCHRATEMST]/100.00 AS [COMPANYCURRENCYEXCHANGERATE] --ePOS behaviour
,RPT.[GIFTCARDID]
,RPT.[ISPREPAYMENT]
,RPT.[LINENUM]
,RPT.[LOYALTYCARDID]
,RPT.[MANAGERKEYLIVE]
,RPT.[MESSAGENUM]
,RPT.[PAYMENTAUTHORIZATION]
,RPT.[QTY]
,RPT.[RECEIPTID]
,RPT.[SIGCAPDATA] AS [SIGNATUREDATA]
,RPT.[STAFF]
,RPT.[STATEMENTCODE]
,RPT.[STORE]
,RPT.[TENDERTYPE] AS [TENDERTYPEID]
,RPT.[TERMINAL]
,RPT.[TRANSACTIONID]
,CASE RPT.[TRANSACTIONSTATUS] WHEN 0 THEN 4 ELSE 3 END AS [STATUS] -- if (TransactionStatus == TransactionStatus.Normal)  Status = TenderLineStatus.Comitted  else  Status = TenderLineStatus.Voided 
,RPT.[CREATEDDATETIME]
,RPT.[MODIFIEDDATETIME]
,RPT.[DATAAREAID]
,DATEADD(SECOND, RPT.[TRANSTIME], CAST(RPT.[TRANSDATE] as DATETIME)) AS 'TENDERDATE'
FROM [ax].[RETAILTRANSACTIONPAYMENTTRANS] RPT
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONPAYMENTTRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONSALESTRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONSALESTRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONSALESTRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONSALESTRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONSALESTRANSVIEW] AS
(
    SELECT
        ST.TRANSACTIONID AS 'TRANSACTIONID'
        ,ST.LINENUM AS 'LINENUM'
        ,ST.ITEMID AS 'ITEMID'
        ,ST.BARCODE AS 'BARCODE'
        ,ST.INVENTSERIALID
        ,(ST.QTY * -1.0) AS 'QUANTITY'
        ,ST.PRICE AS 'PRICE'
        ,ST.UNIT AS 'UNIT'
        ,(ST.NETAMOUNT * -1.0) AS 'NETAMOUNT'
        ,(ST.NETAMOUNTINCLTAX * -1.0) AS 'NETAMOUNTINCLTAX'
        ,ST.TAXITEMGROUP AS 'ITEMTAXGROUPID'
        ,ST.TAXGROUP AS 'SALESTAXGROUPID'
        ,(ST.TAXAMOUNT * -1.0) AS 'TAXAMOUNT'
        ,ST.DLVMODE AS 'DELIVERYMODE'
        ,IDC.INVENTDIMID AS 'INVENTORYDIMENSIONID'
        ,ST.INVENTLOCATIONID AS 'INVENTLOCATIONID'
        ,ST.INVENTSITEID AS 'INVENTORYSITEID'
        ,ST.LOGISTICSPOSTALADDRESS AS 'LOGISTICSPOSTALADDRESS'
        ,(ST.RETURNQTY * -1.0) AS 'RETURNQTY'
        ,ST.STORE AS 'STORE'
        ,ST.TERMINALID AS 'TERMINALID'
        ,ST.RETURNNOSALE AS 'RETURNNOSALE'
        ,ST.RETURNTRANSACTIONID AS 'RETURNTRANSACTIONID'
        ,ST.RETURNLINENUM AS 'RETURNLINENUM'
        ,ST.RETURNSTORE AS 'RETURNSTORE'
        ,ST.RETURNTERMINALID AS 'RETURNTERMINALID'
        ,ST.DISCAMOUNT AS 'DISCOUNTAMOUNT'
        ,ST.TOTALDISCAMOUNT AS 'TOTALDISCOUNTAMOUNT'
        ,ST.TOTALDISCPCT AS 'TOTALDISCOUNTPERCENTAGE'
        ,ST.LINEDSCAMOUNT AS 'LINEDISCOUNTAMOUNT'
        ,ST.GIFTCARD AS 'GIFTCARD'
        ,ST.COMMENT AS 'COMMENT'
        ,ST.ORIGINALPRICE AS 'ORIGINALPRICE'
        ,ST.PERIODICDISCAMOUNT AS 'PERIODICDISCOUNTAMOUNT'
        ,ST.PERIODICPERCENTAGEDISCOUNT 
        ,ST.LINEMANUALDISCOUNTAMOUNT
        ,ST.LINEMANUALDISCOUNTPERCENTAGE        
        ,COALESCE(CAST(NULLIF(ST.LISTINGID, '') AS BIGINT), IDC.DISTINCTPRODUCTVARIANT, IT.PRODUCT, 0)  AS 'LISTINGID'
        ,ST.TRANSACTIONSTATUS as 'TRANSACTIONSTATUS'
        ,DATEADD(ss, ST.TRANSTIME, CAST(ST.TRANSDATE as DATETIME)) as 'SALESDATETIME'
    FROM [ax].RETAILTRANSACTIONSALESTRANS ST
    LEFT OUTER JOIN [ax].INVENTTABLE IT ON ST.LISTINGID = '' AND IT.DATAAREAID = ST.DATAAREAID AND ST.VARIANTID = '' AND IT.ITEMID = ST.ITEMID
    LEFT OUTER JOIN [ax].INVENTDIMCOMBINATION IDC ON ST.ITEMID = IDC.ITEMID AND ST.VARIANTID <> '' AND ST.VARIANTID = IDC.RETAILVARIANTID AND ST.DATAAREAID = IDC.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONSALESTRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONSALESTRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONSALESTRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[EXCHANGERATEVIEW]
PRINT N'Creating view [crt].[EXCHANGERATEVIEW]';

GO
IF OBJECT_ID(N'[crt].[EXCHANGERATEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[EXCHANGERATEVIEW]
GO

CREATE VIEW [crt].[EXCHANGERATEVIEW] AS
(
    SELECT
cc.RECID AS 'CHANNELID',
        er.EXCHANGERATE,
        cp.FROMCURRENCYCODE,
        cp.TOCURRENCYCODE,
        er.VALIDFROM,
        er.VALIDTO,
        er.RECID
    FROM [ax].EXCHANGERATE er
    INNER JOIN [ax].EXCHANGERATECURRENCYPAIR cp ON cp.RECID = er.EXCHANGERATECURRENCYPAIR
    INNER JOIN [crt].CHANNELCONFIGURATIONVIEW cc ON cc.EXCHANGERATETYPE = cp.EXCHANGERATETYPE
    WHERE GETUTCDATE() BETWEEN cc.VALIDFROM AND cc.VALIDTO
)


GO
PRINT N'Finished creating view [crt].[EXCHANGERATEVIEW]'
GO
-- End creating view [crt].[EXCHANGERATEVIEW]


GRANT SELECT ON [crt].[EXCHANGERATEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONADDRESSTRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONADDRESSTRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONADDRESSTRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONADDRESSTRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONADDRESSTRANSVIEW] AS
(
    SELECT
        [rtat].CITY,
        [rtat].COUNTRYREGIONID,
        [rtat].COUNTY,
        [rtat].DELIVERYNAME AS NAME,
        [rtat].EMAIL,
        [rtat].PHONE,
        [rtat].SALESNAME,
        [rtat].STATE,
        [rtat].STREET,
        [rtat].ZIPCODE,
        [rtat].TRANSACTIONID,
        [rtat].SALELINENUM,
        [rtat].STREETNUMBER,
        [rtat].DISTRICTNAME
    FROM [ax].RETAILTRANSACTIONADDRESSTRANS rtat
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONADDRESSTRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONADDRESSTRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONADDRESSTRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[VALIDATIONPERIODVIEW]
PRINT N'Creating view [crt].[VALIDATIONPERIODVIEW]';

GO
IF OBJECT_ID(N'[crt].[VALIDATIONPERIODVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[VALIDATIONPERIODVIEW]
GO

CREATE VIEW [crt].[VALIDATIONPERIODVIEW] AS
(
    SELECT
        vp.RECID,
        vp.PERIODID,
        vp.NAME,
        vp.VALIDFROM,
        vp.VALIDTO,
        vp.STARTINGTIME,
        vp.ENDINGTIME,
        vp.TIMEWITHINBOUNDS,
        vp.MONDAYSTARTINGTIME,
        vp.MONDAYENDINGTIME,
        vp.MONDAYTIMEWITHINBOUNDS,
        vp.THUESDAYSTARTINGTIME,
        vp.THUESDAYENDINGTIME,
        vp.THUESDAYTIMEWITHINBOUNDS,
        vp.WEDNESDAYSTARTINGTIME,
        vp.WEDNESDAYENDINGTIME,
        vp.WEDNESDAYTIMEWITHINBOUNDS,
        vp.THURSDAYSTARTINGTIME,
        vp.THURSDAYENDINGTIME,
        vp.THURSDAYTIMEWITHINBOUNDS,
        vp.FRIDAYSTARTINGTIME,
        vp.FRIDAYENDINGTIME,
        vp.FRIDAYTIMEWITHINBOUNDS,
        vp.SATURDAYSTARTINGTIME,
        vp.SATURDAYENDINGTIME,
        vp.SATURDAYTIMEWITHINBOUNDS,
        vp.SUNDAYSTARTINGTIME,
        vp.SUNDAYENDINGTIME,
        vp.SUNDAYTIMEWITHINBOUNDS,
        vp.MONDAYENDINGTIMEAFTERMIDNIGHT,
        vp.THUESDAYENDINGTIMEAFTERMIDNIGHT,
        vp.WEDNESDAYENDINGTIMEAFTERMIDNIGHT,
        vp.THURSDAYENDINGTIMEAFTERMIDNIGHT,
        vp.FRIDAYENDINGTIMEAFTERMIDNIGHT,
        vp.SATURDAYENDINGTIMEAFTERMIDNIGHT,
        vp.SUNDAYENDINGTIMEAFTERMIDNIGHT,
        vp.ENDINGTIMEAFTERMIDNIGHT,
c.RECID AS CHANNELID
    FROM [ax].RETAILDISCOUNTVALIDATIONPERIOD vp
INNER JOIN [ax].RETAILCHANNELTABLE c on c.INVENTLOCATIONDATAAREAID = vp.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[VALIDATIONPERIODVIEW]'
GO
-- End creating view [crt].[VALIDATIONPERIODVIEW]


GRANT SELECT ON [crt].[VALIDATIONPERIODVIEW] TO [UsersRole];
GO

-- Creating view [crt].[DISCOUNTCODEVIEW]
PRINT N'Creating view [crt].[DISCOUNTCODEVIEW]';

GO
IF OBJECT_ID(N'[crt].[DISCOUNTCODEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[DISCOUNTCODEVIEW]
GO

CREATE VIEW [crt].[DISCOUNTCODEVIEW] AS
(
    SELECT
        rdc.[RECID],
        rdc.[BARCODE],
        rdc.[DISCOUNTCODE],
        rdc.[DISCOUNTOFFERID],
        rpd.[NAME],
        rpd.[DESCRIPTION],
        rpd.[DISCLAIMER],
        rpd.[PERIODICDISCOUNTTYPE],
        rpd.[VALIDATIONPERIODID],
        rpd.[DATEVALIDATIONTYPE],
        rpd.[VALIDFROM],
        rpd.[VALIDTO],
        rpd.[CONCURRENCYMODE],
        rpd.[CURRENCYCODE],
        rpd.[STATUS],
        rpd.[ISDISCOUNTCODEREQUIRED],
rdc.[DATAAREAID]
    FROM [ax].[RETAILDISCOUNTCODE] AS rdc
    INNER JOIN [ax].[RETAILPERIODICDISCOUNT] AS rpd ON rpd.[OFFERID] = rdc.[DISCOUNTOFFERID] AND rpd.DATAAREAID = rdc.DATAAREAID
INNER JOIN [ax].[RETAILPERIODICDISCOUNT] pd ON pd.OFFERID = rdc.DISCOUNTOFFERID AND pd.DATAAREAID = rdc.DATAAREAID
WHERE pd.STATUS = 1
    AND (pd.PERIODICDISCOUNTTYPE != 3) -- Don't fetch promotions
)


GO
PRINT N'Finished creating view [crt].[DISCOUNTCODEVIEW]'
GO
-- End creating view [crt].[DISCOUNTCODEVIEW]


GRANT SELECT ON [crt].[DISCOUNTCODEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[PRICEPARAMETERSVIEW]
PRINT N'Creating view [crt].[PRICEPARAMETERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[PRICEPARAMETERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PRICEPARAMETERSVIEW]
GO

CREATE VIEW [crt].[PRICEPARAMETERSVIEW] AS
(
    SELECT
        pp.RECID,
        pp.SALESPRICEACCOUNTITEM,
        pp.SALESPRICEGROUPITEM,
        pp.SALESPRICEALLITEM,
        pp.SALESLINEACCOUNTITEM,
        pp.SALESLINEACCOUNTGROUP,
        pp.SALESLINEACCOUNTALL,
        pp.SALESLINEGROUPITEM,
        pp.SALESLINEGROUPGROUP,
        pp.SALESLINEGROUPALL,
        pp.SALESLINEALLITEM,
        pp.SALESLINEALLGROUP,
        pp.SALESLINEALLALL,
        pp.SALESMULTILNACCOUNTGROUP,
        pp.SALESMULTILNACCOUNTALL,
        pp.SALESMULTILNGROUPGROUP,
        pp.SALESMULTILNGROUPALL,
        pp.SALESMULTILNALLGROUP,
        pp.SALESMULTILNALLALL,
        pp.SALESENDACCOUNTALL,
        pp.SALESENDGROUPALL,
        pp.SALESENDALLALL,
c.RECID AS CHANNELID
    FROM [ax].PRICEPARAMETERS pp
INNER JOIN [ax].RETAILCHANNELTABLE c on c.INVENTLOCATIONDATAAREAID = pp.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[PRICEPARAMETERSVIEW]'
GO
-- End creating view [crt].[PRICEPARAMETERSVIEW]


GRANT SELECT ON [crt].[PRICEPARAMETERSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PRICEPARAMETERSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[UNITOFMEASUREVIEW]
PRINT N'Creating view [crt].[UNITOFMEASUREVIEW]';

GO
IF OBJECT_ID(N'[crt].[UNITOFMEASUREVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[UNITOFMEASUREVIEW]
GO

CREATE VIEW [crt].[UNITOFMEASUREVIEW] AS
(
    SELECT
        [uom].SYMBOL,
        [uom].DECIMALPRECISION,
        [uom].RECID,
[uomt].DESCRIPTION
    FROM [ax].UNITOFMEASURE uom
INNER JOIN [ax].UNITOFMEASURETRANSLATION uomt
ON uom.RECID = uomt.UNITOFMEASURE
)


GO
PRINT N'Finished creating view [crt].[UNITOFMEASUREVIEW]'
GO
-- End creating view [crt].[UNITOFMEASUREVIEW]


GRANT SELECT ON [crt].[UNITOFMEASUREVIEW] TO [UsersRole];
GO

-- Creating view [crt].[INVENTDIMVIEW]
PRINT N'Creating view [crt].[INVENTDIMVIEW]';

GO
IF OBJECT_ID(N'[crt].[INVENTDIMVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[INVENTDIMVIEW]
GO

CREATE VIEW [crt].[INVENTDIMVIEW] AS
(
    SELECT
        id.RECID,
        id.INVENTDIMID,
        id.CONFIGID,
        id.INVENTCOLORID AS COLORID,
        id.INVENTSIZEID AS SIZEID,
        id.INVENTSTYLEID AS STYLEID,
id.DATAAREAID
    FROM [ax].INVENTDIM id
)


GO
PRINT N'Finished creating view [crt].[INVENTDIMVIEW]'
GO
-- End creating view [crt].[INVENTDIMVIEW]


GRANT SELECT ON [crt].[INVENTDIMVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[INVENTDIMVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELTENDERTYPEVIEW]
PRINT N'Creating view [crt].[CHANNELTENDERTYPEVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELTENDERTYPEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELTENDERTYPEVIEW]
GO

CREATE VIEW [crt].[CHANNELTENDERTYPEVIEW] AS
(
    SELECT
        rsttt.CHANNEL,
        rsttt.RECID,
        rsttt.TENDERTYPEID,
        rsttt.NAME,
        ro.OPERATIONNAME,
        rsttt.POSOPERATION AS OPERATIONID,
        rsttt.CHANGETENDERID,
rsttt.[FUNCTION],
        rsttt.OPENDRAWER,
        rsttt.SIGCAPENABLED AS USESIGNATURECAPTUREDEVICE,
        rsttt.SIGCAPMINAMOUNT AS MINIMUMSIGNATURECAPTUREAMOUNT,
        rsttt.ALLOWOVERTENDER,
        rsttt.ALLOWUNDERTENDER,        
        rsttt.MAXIMUMOVERTENDERAMOUNT,
        rsttt.UNDERTENDERAMOUNT AS MAXIMUMUNDERTENDERAMOUNT,
        rsttt.MAXIMUMAMOUNTALLOWED AS MAXIMUMAMOUNTPERTRANSACTION,
        rsttt.MAXIMUMAMOUNTENTERED AS MAXIMUMAMOUNTPERLINE,
        rsttt.MINIMUMAMOUNTALLOWED AS MINIMUMAMOUNTPERTRANSACTION,
        rsttt.MINIMUMAMOUNTENTERED AS MINIMUMAMOUNTPERLINE,
        rsttt.MINIMUMCHANGEAMOUNT,
        rsttt.ROUNDINGMETHOD,
        rsttt.ROUNDING AS ROUNDOFF,
rsttt.COUNTINGREQUIRED,
rsttt.TAKENTOBANK,
rsttt.TAKENTOSAFE
    FROM [ax].RETAILSTORETENDERTYPETABLE rsttt
    LEFT OUTER JOIN [ax].RETAILOPERATIONS ro ON ro.OPERATIONID = rsttt.POSOPERATION
)


GO
PRINT N'Finished creating view [crt].[CHANNELTENDERTYPEVIEW]'
GO
-- End creating view [crt].[CHANNELTENDERTYPEVIEW]


GRANT SELECT ON [crt].[CHANNELTENDERTYPEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELTENDERTYPEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[STORECASHDECLARATIONVIEW]
PRINT N'Creating view [crt].[STORECASHDECLARATIONVIEW]';

GO
IF OBJECT_ID(N'[crt].[STORECASHDECLARATIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[STORECASHDECLARATIONVIEW]
GO

CREATE VIEW [crt].[STORECASHDECLARATIONVIEW] AS
(
    SELECT
        rpst.[STOREORIGINID] AS CHANNELID,
        rscdt.[RECID],
        rscdt.[STOREID],
        rscdt.[TYPE],
        rscdt.[CURRENCY],
        rscdt.[AMOUNT]
    FROM [ax].RETAILSTORECASHDECLARATIONTABLE rscdt
INNER JOIN [ax].RETAILPUBRETAILSTORETABLE rpst
ON rscdt.STOREID = rpst.STORENUMBER
)


GO
PRINT N'Finished creating view [crt].[STORECASHDECLARATIONVIEW]'
GO
-- End creating view [crt].[STORECASHDECLARATIONVIEW]


GRANT SELECT ON [crt].[STORECASHDECLARATIONVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[STORECASHDECLARATIONVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[SHIFTSVIEW]
PRINT N'Creating view [crt].[SHIFTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[SHIFTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SHIFTSVIEW]
GO

CREATE VIEW [crt].[SHIFTSVIEW] AS
(
    SELECT
        SHIFT.SHIFTID,
        SHIFT.CASHDRAWER,
        SHIFT.CHANNEL,
        SHIFT.CURRENTTERMINALID,
        NULL AS [CLOSEDATE],
        NULL AS [CLOSEDATETIMEUTC],
        NULL AS [CLOSEDATETIMEUTCTZID],
        0 AS [CLOSETIME],
        0 AS [CUSTOMERSCOUNT],
        0.0 AS [DISCOUNTTOTAL],
        0 AS [LOGONSCOUNT],
        0 AS [NOSALECOUNT],
        0.0 AS [PAIDTOACCOUNTTOTAL],
        0.0 AS [RETURNSTOTAL],
        0.0 AS [ROUNDEDAMOUNTTOTAL],
        0 AS [SALESCOUNT],
        0.0 AS [SALESTOTAL],
        SHIFT.STAFFID,
SHIFT.CURRENTSTAFFID,
        NULL AS [STARTDATE],
        SHIFT.STARTDATETIMEUTC,
        NULL AS [STARTDATETIMEUTCTZID],
        0 AS [STARTTIME],
        SHIFT.[STATUS],
        SHIFT.STATUSDATETIMEUTC,
        STORE.STORENUMBER AS STOREID,
        0.0 AS [TAXTOTAL],
        SHIFT.TERMINALID,
        0 AS [TRANSACTIONSCOUNT],
        0 AS [VOIDSCOUNT],
        SHIFT.[DATAAREAID],
        SHIFT.[ROWVERSION]
    FROM [crt].RETAILSHIFTSTAGINGTABLE SHIFT
    INNER JOIN [ax].RETAILPUBRETAILSTORETABLE STORE ON SHIFT.CHANNEL = STORE.STOREORIGINID

    UNION

    SELECT
        SHIFT.[BATCHID] AS SHIFTID,
        '' AS [CASHDRAWER],
        SHIFT.[CHANNEL],
        '' AS CURRENTTERMINALID,
        SHIFT.[CLOSEDATE],
        SHIFT.[CLOSEDATETIMEUTC],
        SHIFT.[CLOSEDATETIMEUTCTZID],
        SHIFT.[CLOSETIME],
        SHIFT.[CUSTOMERSCOUNT],
        SHIFT.[DISCOUNTTOTAL],
        SHIFT.[LOGONSCOUNT],
        SHIFT.[NOSALECOUNT],
        SHIFT.[PAIDTOACCOUNTTOTAL],
        SHIFT.[RETURNSTOTAL],
        SHIFT.[ROUNDEDAMOUNTTOTAL],
        SHIFT.[SALESCOUNT],
        SHIFT.[SALESTOTAL],
        SHIFT.[STAFFID],
        '' AS [CURRENTSTAFFID],
        SHIFT.[STARTDATE],
        SHIFT.[STARTDATETIMEUTC],
        SHIFT.[STARTDATETIMEUTCTZID],
        SHIFT.[STARTTIME],
        SHIFT.[STATUS],
        NULL AS [STATUSDATETIMEUTC],
        SHIFT.[STOREID],
        SHIFT.[TAXTOTAL],
        SHIFT.[TERMINALID],
        SHIFT.[TRANSACTIONSCOUNT],
        SHIFT.[VOIDSCOUNT],
        SHIFT.[DATAAREAID],
        SHIFT.[ROWVERSION]
    FROM [ax].RETAILPOSBATCHTABLE SHIFT
)
GO


GO
PRINT N'Finished creating view [crt].[SHIFTSVIEW]'
GO
-- End creating view [crt].[SHIFTSVIEW]


GRANT SELECT ON [crt].[SHIFTSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[SHIFTTENDERLINESVIEW]
PRINT N'Creating view [crt].[SHIFTTENDERLINESVIEW]';

GO
IF OBJECT_ID(N'[crt].[SHIFTTENDERLINESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SHIFTTENDERLINESVIEW]
GO

CREATE VIEW [crt].[SHIFTTENDERLINESVIEW]
AS
(
    SELECT
        TENDERLINE.[ADDTOTENDERAMOUNT],
        TENDERLINE.[ADDTOTENDERAMOUNTCUR],
        TENDERLINE.[BANKDROPAMOUNT],
        TENDERLINE.[BANKDROPAMOUNTCUR],
        TENDERLINE.[CARDTYPEID],
        CARDTYPE.[NAME] AS CARDTYPENAME,
        TENDERLINE.[CHANGEAMOUNT],
        TENDERLINE.[CHANGEAMOUNTCUR],
        TENDERLINE.[CHANNEL],
        TENDERLINE.[COUNT],
        CAST(TENDERLINE.[COUNTINGREQUIRED] AS BIT) AS [COUNTINGREQUIRED],
        TENDERLINE.[CURRENCY],
        TENDERLINE.[DECLARETENDERAMOUNT],
        TENDERLINE.[DECLARETENDERAMOUNTCUR],
        TENDERLINE.[REMOVETENDERAMOUNT],
        TENDERLINE.[REMOVETENDERAMOUNTCUR],
        TENDERLINE.[SAFEDROPAMOUNT],
        TENDERLINE.[SAFEDROPAMOUNTCUR],
        TENDERLINE.[BATCHID] AS [SHIFTID],
        TENDERLINE.[STARTINGAMOUNT],
        TENDERLINE.[STARTINGAMOUNTCUR],
        TENDERLINE.[STOREID],
        TENDERLINE.[TENDEREDAMOUNT],
        TENDERLINE.[TENDEREDAMOUNTCUR],
        TENDERLINE.[TENDERTYPEID],
        TENDERTYPE.[NAME] AS TENDERTYPENAME,
        TENDERLINE.[TERMINALID],
        TENDERLINE.[DATAAREAID],
        TENDERLINE.[ROWVERSION]
    FROM [ax].RETAILPOSBATCHTENDERTRANS TENDERLINE
    INNER JOIN [ax].RETAILSTORETENDERTYPETABLE TENDERTYPE ON TENDERLINE.CHANNEL = TENDERTYPE.CHANNEL AND TENDERLINE.TENDERTYPEID = TENDERTYPE.TENDERTYPEID
LEFT OUTER JOIN [ax].RETAILSTORETENDERTYPECARDTABLE CARDTYPE ON TENDERLINE.CHANNEL = CARDTYPE.CHANNEL AND TENDERLINE.TENDERTYPEID = CARDTYPE.TENDERTYPEID AND TENDERLINE.CARDTYPEID = CARDTYPE.CARDTYPEID
)
GO


GO
PRINT N'Finished creating view [crt].[SHIFTTENDERLINESVIEW]'
GO
-- End creating view [crt].[SHIFTTENDERLINESVIEW]


GRANT SELECT ON [crt].[SHIFTTENDERLINESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RECEIPTMASKVIEW]
PRINT N'Creating view [crt].[RECEIPTMASKVIEW]';

GO
IF OBJECT_ID(N'[crt].[RECEIPTMASKVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RECEIPTMASKVIEW]
GO

CREATE VIEW [crt].[RECEIPTMASKVIEW] AS
(
    SELECT
        rrm.[FUNCPROFILEID],
        rrm.[RECEIPTTRANSTYPE],
        rrm.[MASK],
        rrm.[ISINDEPENDENT]
    FROM [ax].RETAILRECEIPTMASKS rrm
)


GO
PRINT N'Finished creating view [crt].[RECEIPTMASKVIEW]'
GO
-- End creating view [crt].[RECEIPTMASKVIEW]


GRANT SELECT ON [crt].[RECEIPTMASKVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CURRENCIESVIEW]
PRINT N'Creating view [crt].[CURRENCIESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CURRENCIESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CURRENCIESVIEW]
GO

CREATE VIEW [crt].[CURRENCIESVIEW] AS
(
    SELECT
        c.[RECID],
        c.[ROUNDOFFPRICE],
        c.[ROUNDOFFSALES],
        c.[CURRENCYCODE],
        c.[ROUNDOFFTYPEPRICE],
        c.[ROUNDOFFTYPESALES],
        c.[SYMBOL]
    FROM [ax].CURRENCY c
)


GO
PRINT N'Finished creating view [crt].[CURRENCIESVIEW]'
GO
-- End creating view [crt].[CURRENCIESVIEW]


GRANT SELECT ON [crt].[CURRENCIESVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CURRENCIESVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[TAXCODESVIEW]
PRINT N'Creating view [crt].[TAXCODESVIEW]';

GO
IF OBJECT_ID(N'[crt].[TAXCODESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TAXCODESVIEW]
GO

CREATE VIEW [crt].[TAXCODESVIEW] AS
(
    SELECT
        [tt].TAXCODE,
        [tt].TAXROUNDOFF,
        [tt].TAXROUNDOFFTYPE,
[tt].DATAAREAID
    FROM [ax].TAXTABLE tt
)


GO
PRINT N'Finished creating view [crt].[TAXCODESVIEW]'
GO
-- End creating view [crt].[TAXCODESVIEW]


GRANT SELECT ON [crt].[TAXCODESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILSTOCKCOUNTJOURNALSVIEW]
PRINT N'Creating view [crt].[RETAILSTOCKCOUNTJOURNALSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILSTOCKCOUNTJOURNALSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILSTOCKCOUNTJOURNALSVIEW]
GO

CREATE VIEW [crt].[RETAILSTOCKCOUNTJOURNALSVIEW] AS
(
    SELECT
        scj.[ID],
        scj.[RECID],
        scj.[JOURNALID],
        scj.[DESCRIPTION]
    FROM [crt].RETAILSTOCKCOUNTJOURNALS scj
)


GO
PRINT N'Finished creating view [crt].[RETAILSTOCKCOUNTJOURNALSVIEW]'
GO
-- End creating view [crt].[RETAILSTOCKCOUNTJOURNALSVIEW]


GRANT SELECT ON [crt].[RETAILSTOCKCOUNTJOURNALSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILSTOCKCOUNTVIEW]
PRINT N'Creating view [crt].[RETAILSTOCKCOUNTVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILSTOCKCOUNTVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILSTOCKCOUNTVIEW]
GO

CREATE VIEW [crt].[RETAILSTOCKCOUNTVIEW] AS
(
    SELECT
        DISTINCT (rsc.ID),
        rsc.ITEMID,
        rsc.JOURNALID,
        rsc.RECID,
        rsc.TRACKINGGUID,
        rsc.COUNTED,
        rsc.QUANTITY,
        rsc.UNIT,
        rsc.USERID,
        rsc.TERMINALID,
        rsc.COUNTDATE,
        rsc.STATUS,
        rsc.OPERATIONTYPE,
        rsc.ITEMNAME,
        rsc.INVENTSIZEID,
        rsc.INVENTCOLORID,
        rsc.INVENTSTYLEID,
        rsc.CONFIGID
    FROM [crt].RETAILSTOCKCOUNT rsc
    INNER JOIN [ax].INVENTTABLE it ON rsc.ITEMID = it.ITEMID
    LEFT OUTER JOIN [ax].ECORESCOLOR ON ECORESCOLOR.NAME = rsc.INVENTCOLORID
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERCOLOR ON (ECORESPRODUCTMASTERCOLOR.COLOR = ECORESCOLOR.RECID) AND (ECORESPRODUCTMASTERCOLOR.COLORPRODUCTMASTER = it.PRODUCT)
    LEFT OUTER JOIN [ax].ECORESSIZE ON ECORESSIZE.NAME = rsc.INVENTSIZEID
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERSIZE ON (ECORESPRODUCTMASTERSIZE.SIZE = ECORESSIZE.RECID) AND (ECORESPRODUCTMASTERSIZE.SIZEPRODUCTMASTER = it.PRODUCT)
    LEFT OUTER JOIN [ax].ECORESSTYLE ON (ECORESSTYLE.NAME = rsc.INVENTSTYLEID)
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERSTYLE ON (ECORESPRODUCTMASTERSTYLE.STYLE = ECORESSTYLE.RECID) AND (ECORESPRODUCTMASTERSTYLE.STYLEPRODUCTMASTER = it.PRODUCT)
    LEFT OUTER JOIN [ax].ECORESCONFIGURATION ON (ECORESCONFIGURATION.NAME = rsc.CONFIGID)
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERCONFIGURATION ON (ECORESPRODUCTMASTERCONFIGURATION.CONFIGURATION = ECORESCONFIGURATION.RECID) AND (ECORESPRODUCTMASTERCONFIGURATION.CONFIGPRODUCTMASTER = it.PRODUCT)
)


GO
PRINT N'Finished creating view [crt].[RETAILSTOCKCOUNTVIEW]'
GO
-- End creating view [crt].[RETAILSTOCKCOUNTVIEW]


GRANT SELECT ON [crt].[RETAILSTOCKCOUNTVIEW] TO [UsersRole];
GO

-- Creating view [crt].[INFOCODEVIEW]
PRINT N'Creating view [crt].[INFOCODEVIEW]';

GO
IF OBJECT_ID(N'[crt].[INFOCODEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[INFOCODEVIEW]
GO

CREATE VIEW [crt].[INFOCODEVIEW] AS
(
SELECT
        rict.[INFOCODEID],
        rict.[RECID],
        rict.[ONCEPERTRANSACTION],
        rict.[PRINTPROMPTONRECEIPT],
        rict.[PRINTINPUTONRECEIPT],
        rict.[PRINTINPUTNAMEONRECEIPT],
        rict.[INPUTTYPE],
        rict.[MINIMUMVALUE],
        rict.[MAXIMUMVALUE],
        rict.[MINIMUMLENGTH],
        rict.[MAXIMUMLENGTH],
        rict.[INPUTREQUIRED],
        rict.[LINKEDINFOCODEID],
        rict.[RANDOMFACTOR],
        rict.[RETAILUSEINFOCODE],
rc.[GROUPID],
rc.[PRIORITY],
rc.[DATAAREAID]
FROM
(
SELECT
rict.INFOCODEID,
rict.INFOCODEID AS 'GROUPID',
rict.DATAAREAID,
0  AS 'PRIORITY'
FROM [ax].RETAILINFOCODETABLE ric
INNER JOIN [ax].[RETAILINFOCODETABLE] rict
ON rict.[INFOCODEID] = ric.[INFOCODEID] AND rict.[DATAAREAID] = ric.[DATAAREAID]

UNION

SELECT
rict.[INFOCODEID],
ricgs.[GROUPID] as 'GROUPID',
ricgs.[DATAAREAID],
ricgs.[PRIORITY] as 'PRIORITY'
FROM [ax].[RETAILINFOCODE] ric
INNER JOIN [ax].[RETAILINFOCODEGROUP] rig
ON ric.[INFOCODEID] = rig.[GROUPID] AND ric.[DATAAREAID] = rig.[DATAAREAID]
INNER JOIN [ax].[RETAILINFOCODEGROUPSPECIFIC] ricgs
ON ricgs.[GROUPID] = rig.[GROUPID] AND ricgs.[DATAAREAID] = rig.[DATAAREAID]
LEFT JOIN [ax].[RETAILINFOCODETABLE] rict
ON rict.[INFOCODEID] = ricgs.[INFOCODEID] AND rict.[DATAAREAID] = ricgs.[DATAAREAID]
) rc

LEFT JOIN [ax].[RETAILINFOCODETABLE] rict 
ON rc.[INFOCODEID] = rict.[INFOCODEID] AND rc.[DATAAREAID] = rict.[DATAAREAID]
)


GO
PRINT N'Finished creating view [crt].[INFOCODEVIEW]'
GO
-- End creating view [crt].[INFOCODEVIEW]


GRANT SELECT ON [crt].[INFOCODEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[INFOSUBCODEVIEW]
PRINT N'Creating view [crt].[INFOSUBCODEVIEW]';

GO
IF OBJECT_ID(N'[crt].[INFOSUBCODEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[INFOSUBCODEVIEW]
GO

CREATE VIEW [crt].[INFOSUBCODEVIEW] AS
(
SELECT
rist.[INFOCODEID],
rist.[SUBCODEID],
rist.[RECID],
rist.[TRIGGERFUNCTION],
rist.[TRIGGERCODE],
rist.[NEWSALESLINE],
rist.[PRICETYPE],
rist.[AMOUNTPERCENT],
rist.[DATAAREAID]
FROM [ax].[RETAILINFORMATIONSUBCODETABLE] AS rist
)


GO
PRINT N'Finished creating view [crt].[INFOSUBCODEVIEW]'
GO
-- End creating view [crt].[INFOSUBCODEVIEW]


GRANT SELECT ON [crt].[INFOSUBCODEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[INFOCODESETTINGSVIEW]
PRINT N'Creating view [crt].[INFOCODESETTINGSVIEW]';

GO
IF OBJECT_ID(N'[crt].[INFOCODESETTINGSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[INFOCODESETTINGSVIEW]
GO

CREATE VIEW [crt].[INFOCODESETTINGSVIEW] AS
(
    SELECT
        RST.STOREORIGINID AS CHANNELID,
        RFP.RECID AS RECID,
        RFP.PROFILEID,
        RFP.SALESPERSON AS ADDSALESPERSON,
        RFP.ENDOFTRANSACTION,
        RFP.MARKDOWN AS ITEMDISCOUNT,
        RFP.ITEMNOTONFILE,
        RFP.LINEITEMTAXCHANGE,
        RFP.NEGATIVEADJUSTMENT,
        RFP.OVERRIDEPRICE,
        RFP.NEGATIVESALESLINE AS RETURNITEM,
        RFP.REFUNDSALE AS RETURNTRANSACTION,
        RFP.SERIALNUMBER,
        RFP.STARTOFTRANSACTION,
        RFP.TENDERDECLARATION,
        RFP.DISCOUNTATTOTAL AS TOTALDISCOUNT,
        RFP.TRANSACTIONTAXCHANGE,
        RFP.VOIDISPRESSED AS VOIDITEM,
        RFP.VOIDPAYMENT,
        RFP.VOIDTRANSACTION
    FROM [ax].RETAILFUNCTIONALITYPROFILE AS RFP
    INNER JOIN [ax].RETAILPUBRETAILSTORETABLE AS RST ON RFP.PROFILEID = RST.FUNCTIONALITYPROFILE
)


GO
PRINT N'Finished creating view [crt].[INFOCODESETTINGSVIEW]'
GO
-- End creating view [crt].[INFOCODESETTINGSVIEW]


GRANT SELECT ON [crt].[INFOCODESETTINGSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[INFOCODETABLESPECIFICVIEW]
PRINT N'Creating view [crt].[INFOCODETABLESPECIFICVIEW]';

GO
IF OBJECT_ID(N'[crt].[INFOCODETABLESPECIFICVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[INFOCODETABLESPECIFICVIEW]
GO

CREATE VIEW [crt].[INFOCODETABLESPECIFICVIEW] AS
(
    SELECT ricts.[INFOCODEID]
      ,ricts.[INPUTREQUIRED]
      ,ricts.[REFRELATION]
      ,ricts.[REFRELATION2]
      ,ricts.[REFRELATION3]
      ,ricts.[REFTABLEID]
      ,ricts.[SEQUENCE]
      ,ricts.[WHENREQUIRED]
    FROM [ax].[RETAILINFOCODETABLESPECIFIC] ricts
)


GO
PRINT N'Finished creating view [crt].[INFOCODETABLESPECIFICVIEW]'
GO
-- End creating view [crt].[INFOCODETABLESPECIFICVIEW]


GRANT SELECT ON [crt].[INFOCODETABLESPECIFICVIEW] TO [UsersRole];
GO

-- Creating view [crt].[INFOCODESPECIFICVIEW]
PRINT N'Creating view [crt].[INFOCODESPECIFICVIEW]';

GO
IF OBJECT_ID(N'[crt].[INFOCODESPECIFICVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[INFOCODESPECIFICVIEW]
GO

CREATE VIEW [crt].[INFOCODESPECIFICVIEW] AS
(
SELECT 
ic.[RECID],
ic.[INFOCODEID],
ic.[DATAAREAID],
ic.[PRIORITY],
ic.[ONCEPERTRANSACTION],
ic.[PRINTPROMPTONRECEIPT],
ic.[PRINTINPUTONRECEIPT],
ic.[PRINTINPUTNAMEONRECEIPT],
ic.[INPUTTYPE],
ic.[MINIMUMVALUE],
ic.[MAXIMUMVALUE],
ic.[MINIMUMLENGTH],
ic.[MAXIMUMLENGTH],
ic.[INPUTREQUIRED],
ic.[LINKEDINFOCODEID],
ic.[RANDOMFACTOR],
ic.[INPUTREQUIREDSPECIFIC],
ic.[WHENREQUIRED],
ic.[SEQUENCE],
ic.[REFRELATION],
ic.[REFRELATION2],
ic.[REFRELATION3],
ic.[REFTABLEID]
 FROM 
 (
SELECT 
icw.[GROUPID],
icw.[RECID],
icw.[INFOCODEID],
icw.[DATAAREAID],
icw.[PRIORITY],
icw.[ONCEPERTRANSACTION],
icw.[PRINTPROMPTONRECEIPT],
icw.[PRINTINPUTONRECEIPT],
icw.[PRINTINPUTNAMEONRECEIPT],
icw.[INPUTTYPE],
icw.[MINIMUMVALUE],
icw.[MAXIMUMVALUE],
icw.[MINIMUMLENGTH],
icw.[MAXIMUMLENGTH],
icw.[INPUTREQUIRED],
icw.[LINKEDINFOCODEID],
icw.[RANDOMFACTOR],
icts.[INPUTREQUIRED] AS 'INPUTREQUIREDSPECIFIC',
icts.[WHENREQUIRED],
icts.[SEQUENCE],
icts.[REFRELATION],
icts.[REFRELATION2],
icts.[REFRELATION3],
icts.[REFTABLEID],
row_number() OVER (PARTITION BY icw.[DATAAREAID], icts.[REFRELATION], icts.[REFRELATION2], icts.[REFRELATION3], icw.[INFOCODEID] ORDER BY icts.[SEQUENCE]) AS 'ROLLINGNUMBER'
FROM [crt].[INFOCODETABLESPECIFICVIEW] icts
INNER JOIN [crt].[INFOCODEVIEW] icw
ON icts.[INFOCODEID] = icw.[GROUPID]
) ic 
-- select only first entry of specific info code
WHERE ic.[ROLLINGNUMBER] = 1
)


GO
PRINT N'Finished creating view [crt].[INFOCODESPECIFICVIEW]'
GO
-- End creating view [crt].[INFOCODESPECIFICVIEW]


GRANT SELECT ON [crt].[INFOCODESPECIFICVIEW] TO [UsersRole];
GO

-- Creating view [crt].[LISTINGPUBLISHSTATUSVIEW]
PRINT N'Creating view [crt].[LISTINGPUBLISHSTATUSVIEW]';

GO
IF OBJECT_ID(N'[crt].[LISTINGPUBLISHSTATUSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[LISTINGPUBLISHSTATUSVIEW]
GO

CREATE VIEW [crt].[LISTINGPUBLISHSTATUSVIEW] AS
    WITH [LISTING_STATUS] AS
    (
        SELECT
            [ACTIONSTATUS],
            [APPLIEDACTION],
            [CHANNEL],
            [CHANNELBATCHID],
            [CHANNELLISTINGID],
            [CHANNELSTATE],
            [LISTINGMODIFIEDDATETIME],
            [LISTINGMODIFIEDDATETIMETZID],
            [PROCESSED],
            [PRODUCT],
            [STATUSDATETIME],
            [STATUSDATETIMETZID],
            [STATUSMESSAGE],
            RANK() OVER
            (
                PARTITION BY PRODUCT
                ORDER BY STATUSDATETIME DESC, REPLICATIONCOUNTERFROMORIGIN DESC
            ) AS [RANK]
        FROM [ax].RETAILLISTINGSTATUSLOG
    )
    SELECT
        [ACTIONSTATUS],
        [APPLIEDACTION],
        [CHANNEL],
        [CHANNELBATCHID],
        [CHANNELLISTINGID],
        [CHANNELSTATE],
        [LISTINGMODIFIEDDATETIME],
        [LISTINGMODIFIEDDATETIMETZID],
        [PROCESSED],
        [PRODUCT],
        [STATUSDATETIME],
        [STATUSDATETIMETZID],
        [STATUSMESSAGE]
    FROM [LISTING_STATUS]
    WHERE RANK = 1


GO
PRINT N'Finished creating view [crt].[LISTINGPUBLISHSTATUSVIEW]'
GO
-- End creating view [crt].[LISTINGPUBLISHSTATUSVIEW]


GRANT SELECT ON [crt].[LISTINGPUBLISHSTATUSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[SHIPMENTSVIEW]
PRINT N'Creating view [crt].[SHIPMENTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[SHIPMENTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SHIPMENTSVIEW]
GO

CREATE VIEW [crt].[SHIPMENTSVIEW] AS
(
    SELECT
        CPJ.[PACKINGSLIPID],
        CPJ.[SALESID],
        RTOS.[CHANNEL],
        RTOS.[TRANSACTIONID],
        CPJ.[SHIPCARRIERID],
        SCT.[CARRIERNAME],
        SST.[SHIPDATE],
        SST.[TRACKINGNUMBER],
        SST.[ROWVERSION]
    FROM [ax].SHIPCARRIERSTAGING SST
    INNER JOIN [ax].CUSTPACKINGSLIPJOUR CPJ ON CPJ.PACKINGSLIPID = SST.PACKINGSLIPID
    INNER JOIN [ax].RETAILTRANSACTIONORDERSTATUS RTOS ON RTOS.SALESID = CPJ.SALESID AND RTOS.DATAAREAID = CPJ.DATAAREAID
    INNER JOIN [ax].SHIPCARRIERTABLE SCT ON SCT.CARRIERID = CPJ.SHIPCARRIERID AND SCT.DATAAREAID = CPJ.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[SHIPMENTSVIEW]'
GO
-- End creating view [crt].[SHIPMENTSVIEW]


GRANT SELECT ON [crt].[SHIPMENTSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[SHIPMENTSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[ATTRIBUTENAMETRANSLATIONSVIEW]
PRINT N'Creating view [crt].[ATTRIBUTENAMETRANSLATIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[ATTRIBUTENAMETRANSLATIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ATTRIBUTENAMETRANSLATIONSVIEW]
GO

CREATE VIEW [crt].[ATTRIBUTENAMETRANSLATIONSVIEW] AS
(
    SELECT
        erat.[ATTRIBUTE],
        erat.[FRIENDLYNAME],
        erat.[LANGUAGE]
    FROM [ax].ECORESATTRIBUTETRANSLATION erat
)


GO
PRINT N'Finished creating view [crt].[ATTRIBUTENAMETRANSLATIONSVIEW]'
GO
-- End creating view [crt].[ATTRIBUTENAMETRANSLATIONSVIEW]


GRANT SELECT ON [crt].[ATTRIBUTENAMETRANSLATIONSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[ATTRIBUTENAMETRANSLATIONSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CATEGORYNAMETRANSLATIONSVIEW]
PRINT N'Creating view [crt].[CATEGORYNAMETRANSLATIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATEGORYNAMETRANSLATIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATEGORYNAMETRANSLATIONSVIEW]
GO

CREATE VIEW [crt].[CATEGORYNAMETRANSLATIONSVIEW] AS
(
    SELECT
        rpect.[CHANNEL],
        rpect.[CATEGORY],
        rpect.[FRIENDLYNAME],
        rpect.[LANGUAGEID]
    FROM [ax].RETAILPUBECORESCATEGORYTRANSLATION rpect
)


GO
PRINT N'Finished creating view [crt].[CATEGORYNAMETRANSLATIONSVIEW]'
GO
-- End creating view [crt].[CATEGORYNAMETRANSLATIONSVIEW]


GRANT SELECT ON [crt].[CATEGORYNAMETRANSLATIONSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CATEGORYNAMETRANSLATIONSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[TEXTVALUETRANSLATIONSVIEW]
PRINT N'Creating view [crt].[TEXTVALUETRANSLATIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[TEXTVALUETRANSLATIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TEXTVALUETRANSLATIONSVIEW]
GO

CREATE VIEW [crt].[TEXTVALUETRANSLATIONSVIEW] AS
(
    SELECT
        ertvt.RECID,
        ertvt.LANGUAGE,
        ertvt.TEXTVALUE,
        ertvt.TEXTVALUETABLE
    FROM [ax].ECORESTEXTVALUETRANSLATION ertvt
)


GO
PRINT N'Finished creating view [crt].[TEXTVALUETRANSLATIONSVIEW]'
GO
-- End creating view [crt].[TEXTVALUETRANSLATIONSVIEW]


GRANT SELECT ON [crt].[TEXTVALUETRANSLATIONSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[TEXTVALUETRANSLATIONSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[SALESPARAMETERSVIEW]
PRINT N'Creating view [crt].[SALESPARAMETERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[SALESPARAMETERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SALESPARAMETERSVIEW]
GO

CREATE VIEW [crt].[SALESPARAMETERSVIEW] AS
(
    SELECT
        sp.RECID,
        sp.MARKUPHEADING,
        sp.MARKUPLINE,
        sp.DISC,
        sp.DATAAREAID
    FROM [ax].SALESPARAMETERS sp
    WHERE sp.[KEY] = 0 -- This ensures that filtering by DATAAREAID is the PK
)


GO
PRINT N'Finished creating view [crt].[SALESPARAMETERSVIEW]'
GO
-- End creating view [crt].[SALESPARAMETERSVIEW]


GRANT SELECT ON [crt].[SALESPARAMETERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[TRANSACTIONPROPERTIESVIEW]
PRINT N'Creating view [crt].[TRANSACTIONPROPERTIESVIEW]';

GO
IF OBJECT_ID(N'[crt].[TRANSACTIONPROPERTIESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TRANSACTIONPROPERTIESVIEW]
GO

CREATE VIEW [crt].[TRANSACTIONPROPERTIESVIEW] AS
(
    SELECT
        [rtp].[DATAAREAID],
        [rtp].[CHANNEL],
        [rtp].[STOREID],
        [rtp].[TERMINALID],
        [rtp].[TRANSACTIONID],
        [rtp].[SALELINENUM],
        [rtp].[NAME],
        [rtp].[VALUE]
    FROM [crt].RETAILTRANSACTIONPROPERTIES rtp
)


GO
PRINT N'Finished creating view [crt].[TRANSACTIONPROPERTIESVIEW]'
GO
-- End creating view [crt].[TRANSACTIONPROPERTIESVIEW]


GRANT SELECT ON [crt].[TRANSACTIONPROPERTIESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[TERMINALSVIEW]
PRINT N'Creating view [crt].[TERMINALSVIEW]';

GO
IF OBJECT_ID(N'[crt].[TERMINALSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TERMINALSVIEW]
GO

CREATE VIEW [crt].[TERMINALSVIEW] AS
(
    SELECT
        rtt.RECID,
        rtt.STORERECID,
        rtt.NAME,
        rtt.TERMINALID,
        rtt.HARDWAREPROFILE
        FROM [ax].RETAILTERMINALTABLE rtt
)


GO
PRINT N'Finished creating view [crt].[TERMINALSVIEW]'
GO
-- End creating view [crt].[TERMINALSVIEW]


GRANT SELECT ON [crt].[TERMINALSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[LOCALIZEDSTRINGSVIEW]
PRINT N'Creating view [crt].[LOCALIZEDSTRINGSVIEW]';

GO
IF OBJECT_ID(N'[crt].[LOCALIZEDSTRINGSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[LOCALIZEDSTRINGSVIEW]
GO

CREATE VIEW [crt].[LOCALIZEDSTRINGSVIEW] AS
(
    SELECT
        rlt.[RECID],
        rlt.[ACTIVE],
        rlt.[LANGUAGEID],
        rlt.[TEXTID],
        rlt.[TEXT],
rlt.[DATAAREAID]
    FROM [ax].RETAILLANGUAGETEXT rlt
    WHERE rlt.ACTIVE = 1
)


GO
PRINT N'Finished creating view [crt].[LOCALIZEDSTRINGSVIEW]'
GO
-- End creating view [crt].[LOCALIZEDSTRINGSVIEW]


GRANT SELECT ON [crt].[LOCALIZEDSTRINGSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[INVENTITEMBARCODESVIEW]
PRINT N'Creating view [crt].[INVENTITEMBARCODESVIEW]';

GO
IF OBJECT_ID(N'[crt].[INVENTITEMBARCODESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[INVENTITEMBARCODESVIEW]
GO

CREATE VIEW [crt].[INVENTITEMBARCODESVIEW] AS
(
    SELECT
        B.[RECID],
        B.[BARCODESETUPID],
        B.[BLOCKED],
        B.[DESCRIPTION],
        B.[INVENTDIMID],
        B.[ITEMBARCODE],
        B.[ITEMID],
        B.[QTY],
        B.[RETAILSHOWFORITEM],
        B.[RETAILVARIANTID],
        B.[UNITID],
        B.[USEFORINPUT],
        B.[USEFORPRINTING],
B.[DATAAREAID],
        ISNULL(D.CONFIGID, '') AS CONFIGID,
        ISNULL(D.INVENTSTYLEID, '') AS INVENTSTYLEID,
        ISNULL(D.INVENTCOLORID, '') AS INVENTCOLORID,
        ISNULL(D.INVENTSIZEID, '') AS INVENTSIZEID
    FROM [ax].INVENTITEMBARCODE B
    LEFT JOIN [ax].INVENTDIM D ON B.INVENTDIMID = D.INVENTDIMID
)


GO
PRINT N'Finished creating view [crt].[INVENTITEMBARCODESVIEW]'
GO
-- End creating view [crt].[INVENTITEMBARCODESVIEW]


GRANT SELECT ON [crt].[INVENTITEMBARCODESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[BARCODEMASKSEGMENTSVIEW]
PRINT N'Creating view [crt].[BARCODEMASKSEGMENTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[BARCODEMASKSEGMENTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[BARCODEMASKSEGMENTSVIEW]
GO

CREATE VIEW [crt].[BARCODEMASKSEGMENTSVIEW] AS
(
    SELECT
        rbms.[RECID],
        rbms.[DECIMALS],
        rbms.[LENGTH],
        rbms.[MASKID],
        rbms.[SEGMENTNUM],
        rbms.[TYPE],
        rbms.[ROWVERSION],
rbms.[DATAAREAID]
    FROM [ax].RETAILBARCODEMASKSEGMENT rbms
)


GO
PRINT N'Finished creating view [crt].[BARCODEMASKSEGMENTSVIEW]'
GO
-- End creating view [crt].[BARCODEMASKSEGMENTSVIEW]


GRANT SELECT ON [crt].[BARCODEMASKSEGMENTSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[BARCODEMASKSVIEW]
PRINT N'Creating view [crt].[BARCODEMASKSVIEW]';

GO
IF OBJECT_ID(N'[crt].[BARCODEMASKSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[BARCODEMASKSVIEW]
GO

CREATE VIEW [crt].[BARCODEMASKSVIEW] AS
(
    SELECT
        LEN(rbmt.[PREFIX]) AS LENGTH,
        rbmt.[RECID],
        rbmt.[DESCRIPTION],
        rbmt.[MASK],
        rbmt.[MASKID],
        rbmt.[PREFIX],
        rbmt.[SYMBOLOGY],
        rbmt.[TYPE],
rbmt.[DATAAREAID]
    FROM [ax].RETAILBARCODEMASKTABLE rbmt
)


GO
PRINT N'Finished creating view [crt].[BARCODEMASKSVIEW]'
GO
-- End creating view [crt].[BARCODEMASKSVIEW]


GRANT SELECT ON [crt].[BARCODEMASKSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CARDTYPESVIEW]
PRINT N'Creating view [crt].[CARDTYPESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CARDTYPESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CARDTYPESVIEW]
GO
/********************************************************************************
    CardTypesView retrieves the card type information by joining with three tables:
    RETAILTENDERTYPECARDTABLE - Global AX table that are available to all Channels.
    RETAILSTORETENDERTYPECARDTABLE - Store Specific tender type card table.
    RETAILTENDERTYPECARDNUMBERS - Global AX table that stores the tender type card numbers.
********************************************************************************/
CREATE VIEW [crt].[CARDTYPESVIEW] AS
(
    SELECT
        rst.[CHANNEL] AS 'CHANNELID',
        rtcn.[RECID],
        rtc.[CARDTYPEID],
        rtc.[NAME],
        rtc.[CARDTYPES],
        rtc.[CARDISSUER],
        rst.[TENDERTYPEID],
        rst.[CASHBACKLIMIT],
        rst.[ALLOWMANUALINPUT],
        rst.[CHECKMODULUS],
        rtcn.[CARDNUMBERTO],
        rtcn.[CARDNUMBERFROM]
    FROM [ax].RETAILSTORETENDERTYPECARDTABLE rst
    INNER JOIN [ax].RETAILTENDERTYPECARDTABLE rtc ON rtc.CARDTYPEID = rst.CARDTYPEID
    INNER JOIN [ax].RETAILTENDERTYPECARDNUMBERS rtcn ON rtcn.CARDTYPEID = rst.CARDTYPEID
)


GO
PRINT N'Finished creating view [crt].[CARDTYPESVIEW]'
GO
-- End creating view [crt].[CARDTYPESVIEW]


GRANT SELECT ON [crt].[CARDTYPESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RECEIPTPROFILESVIEW]
PRINT N'Creating view [crt].[RECEIPTPROFILESVIEW]';

GO
IF OBJECT_ID(N'[crt].[RECEIPTPROFILESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RECEIPTPROFILESVIEW]
GO

CREATE VIEW [crt].[RECEIPTPROFILESVIEW] AS
(
    SELECT
        rrpl.[FORMLAYOUTID],
        rrpl.[PROFILEID],
        rrpl.[RECEIPTTYPE]
    FROM [ax].RETAILRECEIPTPROFILELINE rrpl
)


GO
PRINT N'Finished creating view [crt].[RECEIPTPROFILESVIEW]'
GO
-- End creating view [crt].[RECEIPTPROFILESVIEW]


GRANT SELECT ON [crt].[RECEIPTPROFILESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RECEIPTINFOVIEW]
PRINT N'Creating view [crt].[RECEIPTINFOVIEW]';

GO
IF OBJECT_ID(N'[crt].[RECEIPTINFOVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RECEIPTINFOVIEW]
GO

CREATE VIEW [crt].[RECEIPTINFOVIEW] AS
(
    SELECT
        rfl.[TITLE],
        rfl.[DESCRIPTION],
        rfl.[UPPERCASE],
        rfl.[PRINTASSLIP],
        rfl.[PRINTBEHAVIOUR],
        rfl.[HEADERXML],
        rfl.[LINESXML],
        rfl.[FOOTERXML],
        rfl.[FORMLAYOUTID]
    FROM [ax].RETAILFORMLAYOUT rfl
)


GO
PRINT N'Finished creating view [crt].[RECEIPTINFOVIEW]'
GO
-- End creating view [crt].[RECEIPTINFOVIEW]


GRANT SELECT ON [crt].[RECEIPTINFOVIEW] TO [UsersRole];
GO

-- Creating view [crt].[STOREADDRESSESVIEW]
PRINT N'Creating view [crt].[STOREADDRESSESVIEW]';

GO
IF OBJECT_ID(N'[crt].[STOREADDRESSESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[STOREADDRESSESVIEW]
GO

CREATE VIEW [crt].[STOREADDRESSESVIEW] AS
(
    SELECT DISTINCT
        rprct.ORIGINID AS RECID,
        rprst.STORENUMBER,
        lpa.ADDRESS,
        lpa.STREETNUMBER,
        lpa.STREET,
        lpa.DISTRICTNAME,
        lpa.CITY,
        lpa.COUNTY,
        lpa.ZIPCODE,
        lpa.STATE
    FROM [ax].RETAILPUBRETAILSTORETABLE rprst
    INNER JOIN [ax].RETAILPUBRETAILCHANNELTABLE rprct ON rprct.ORIGINID = rprst.STOREORIGINID
    INNER JOIN [ax].DIRPARTYLOCATION dpl ON dpl.PARTY = rprct.OMOPERATINGUNITID AND dpl.ISPOSTALADDRESS = 1
    INNER JOIN [ax].LOGISTICSPOSTALADDRESS lpa ON lpa.LOCATION = dpl.LOCATION
    WHERE GETUTCDATE() BETWEEN lpa.VALIDFROM AND lpa.VALIDTO
)


GO
PRINT N'Finished creating view [crt].[STOREADDRESSESVIEW]'
GO
-- End creating view [crt].[STOREADDRESSESVIEW]


GRANT SELECT ON [crt].[STOREADDRESSESVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[STOREADDRESSESVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW]
PRINT N'Creating view [crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW]
GO

CREATE VIEW [crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW] AS
(
    SELECT
        tiers.RECID,
        tiers.AMOUNTTHRESHOLD,
        tiers.DISCOUNTMETHOD,
        tiers.DISCOUNTVALUE,
        tiers.OFFERID,
        tiers.DATAAREAID
    FROM [ax].RETAILDISCOUNTTHRESHOLDTIERS tiers
INNER JOIN [ax].[RETAILPERIODICDISCOUNT] pd ON pd.OFFERID = tiers.OFFERID AND pd.DATAAREAID = tiers.DATAAREAID
WHERE pd.STATUS = 1
    AND (pd.PERIODICDISCOUNTTYPE != 3) -- Don't fetch promotions
)


GO
PRINT N'Finished creating view [crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW]'
GO
-- End creating view [crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW]


GRANT SELECT ON [crt].[RETAILDISCOUNTTHRESHOLDTIERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILMULTIBUYDISCOUNTLINESVIEW]
PRINT N'Creating view [crt].[RETAILMULTIBUYDISCOUNTLINESVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILMULTIBUYDISCOUNTLINESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILMULTIBUYDISCOUNTLINESVIEW]
GO

CREATE VIEW [crt].[RETAILMULTIBUYDISCOUNTLINESVIEW] AS
(
    SELECT
        mbl.RECID,
        mbl.MULTIBUYID,
        mbl.PRICEDISCPCT, 
        mbl.QTYLOWEST,             
        mbl.DATAAREAID
    FROM [ax].RETAILMULTIBUYDISCOUNTLINE mbl
INNER JOIN [ax].[RETAILPERIODICDISCOUNT] pd ON pd.OFFERID = mbl.MULTIBUYID AND pd.DATAAREAID = mbl.DATAAREAID
WHERE pd.STATUS = 1
    AND (pd.PERIODICDISCOUNTTYPE != 3) -- Don't fetch promotions
)


GO
PRINT N'Finished creating view [crt].[RETAILMULTIBUYDISCOUNTLINESVIEW]'
GO
-- End creating view [crt].[RETAILMULTIBUYDISCOUNTLINESVIEW]


GRANT SELECT ON [crt].[RETAILMULTIBUYDISCOUNTLINESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILCHANNELREPORTVIEW]
PRINT N'Creating view [crt].[RETAILCHANNELREPORTVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILCHANNELREPORTVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILCHANNELREPORTVIEW]
GO
/************************************************************************************************************************************
    RetailChannelReportView: This view contains reports data for the channels.
    RETAILCHANNELREPORT - AX table that stores channel reports.
*************************************************************************************************************************************/
CREATE VIEW [crt].[RETAILCHANNELREPORTVIEW] AS
(
    SELECT
        RCP.[REPORTID],
        RCP.[REPORTDEFINITIONXML],
        RCP.[RECID],
        RPPG.[RECID] AS POSPERMISSIONGROUPRECID,
        RPPG.[POSPERMISSIONGROUPID]
    FROM [ax].RETAILCHANNELREPORT RCP INNER JOIN [ax].RETAILREPORTPERMISSIONGROUP RRPG ON RCP.RECID = RRPG.RETAILCHANNELREPORTRECID
    INNER JOIN [ax].RETAILPOSPERMISSIONGROUP RPPG ON RRPG.RETAILPOSPERMISSIONGROUPRECID = RPPG.RECID
)


GO
PRINT N'Finished creating view [crt].[RETAILCHANNELREPORTVIEW]'
GO
-- End creating view [crt].[RETAILCHANNELREPORTVIEW]


GRANT SELECT ON [crt].[RETAILCHANNELREPORTVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILREPORTLOCALIZEDSTRINGVIEW]
PRINT N'Creating view [crt].[RETAILREPORTLOCALIZEDSTRINGVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILREPORTLOCALIZEDSTRINGVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILREPORTLOCALIZEDSTRINGVIEW]
GO
/************************************************************************************************************************************
    RetailReportLocalizedStringView: This view contains localized strings for reports.
    RETAILREPORTLOCALIZEDSTRING - AX table that stores localized strings for reports.
*************************************************************************************************************************************/
CREATE VIEW [crt].[RETAILREPORTLOCALIZEDSTRINGVIEW] AS
(
    SELECT
        RRLS.[STRINGID],
        RRLS.[STRINGVALUE],
        RRLS.[LOCALECODE],
        RRLS.[RECID]
    FROM [ax].[RETAILREPORTLOCALIZEDSTRING] AS RRLS
)


GO
PRINT N'Finished creating view [crt].[RETAILREPORTLOCALIZEDSTRINGVIEW]'
GO
-- End creating view [crt].[RETAILREPORTLOCALIZEDSTRINGVIEW]


GRANT SELECT ON [crt].[RETAILREPORTLOCALIZEDSTRINGVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RECEIPTPRINTERSVIEW]
PRINT N'Creating view [crt].[RECEIPTPRINTERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RECEIPTPRINTERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RECEIPTPRINTERSVIEW]
GO

CREATE VIEW [crt].[RECEIPTPRINTERSVIEW] AS
(
    SELECT DISTINCT
        rhp.RECID,
        rtt.RECID AS TERMINALID,
        rhp.PRINTER AS PRINTER,
        rhp.PRINTERDEVICENAME AS PRINTERDEVICENAME,
        rfl.PRINTBEHAVIOUR,
        rrpl.FORMLAYOUTID,
        rrpl.RECEIPTTYPE,
rtt.HARDWAREPROFILE AS HARDWAREPROFILEID
    FROM ax.RETAILHARDWAREPROFILE rhp
    INNER JOIN ax.RETAILTERMINALTABLE rtt ON rtt.HARDWAREPROFILE = rhp.PROFILEID AND rhp.PRINTER <> 0
    INNER JOIN ax.RETAILRECEIPTPROFILE rrp ON rrp.PROFILEID = rhp.PRINTERRECEIPTPROFILEID
    INNER JOIN ax.RETAILRECEIPTPROFILELINE rrpl ON rrpl.PROFILEID = rrp.PROFILEID AND rrpl.PROFILEID = rhp.PRINTERRECEIPTPROFILEID
    INNER JOIN ax.RETAILFORMLAYOUT rfl ON rfl.FORMLAYOUTID = rrpl.FORMLAYOUTID

    UNION ALL

    SELECT DISTINCT
        rhp.RECID,
        rtt.RECID AS TERMINALID,
        rhp.PRINTER2 AS PRINTER,
        rhp.PRINTER2DEVICENAME AS PRINTERDEVICENAME,
        rfl.PRINTBEHAVIOUR,
        rrpl.FORMLAYOUTID,
        rrpl.RECEIPTTYPE,
rtt.HARDWAREPROFILE AS HARDWAREPROFILEID
    FROM ax.RETAILHARDWAREPROFILE rhp
    INNER JOIN ax.RETAILTERMINALTABLE rtt ON rtt.HARDWAREPROFILE = rhp.PROFILEID AND rhp.PRINTER2 <> 0
    INNER JOIN ax.RETAILRECEIPTPROFILE rrp ON rrp.PROFILEID = rhp.PRINTER2RECEIPTPROFILEID
    INNER JOIN ax.RETAILRECEIPTPROFILELINE rrpl ON rrpl.PROFILEID = rrp.PROFILEID AND rrpl.PROFILEID = rhp.PRINTER2RECEIPTPROFILEID
    INNER JOIN ax.RETAILFORMLAYOUT rfl ON rfl.FORMLAYOUTID = rrpl.FORMLAYOUTID
)


GO
PRINT N'Finished creating view [crt].[RECEIPTPRINTERSVIEW]'
GO
-- End creating view [crt].[RECEIPTPRINTERSVIEW]


GRANT SELECT ON [crt].[RECEIPTPRINTERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[SALESTAXOVERRIDESVIEW]
PRINT N'Creating view [crt].[SALESTAXOVERRIDESVIEW]';

GO
IF OBJECT_ID(N'[crt].[SALESTAXOVERRIDESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SALESTAXOVERRIDESVIEW]
GO

CREATE VIEW [crt].[SALESTAXOVERRIDESVIEW] AS
(
SELECT 
T.[CODE], 
T.[DESCRIPTION],
    T.[OVERRIDEBY],
CASE 
WHEN T.[OVERRIDETYPE] = 0 
THEN T.[SOURCEITEMTAXGROUP] 
ELSE T.[SOURCETAXGROUP] 
END 
AS SOURCETAXGROUP,  
CASE 
WHEN T.[OVERRIDETYPE] = 0 
THEN T.[DESTINATIONITEMTAXGROUP] 
ELSE T.[DESTINATIONTAXGROUP] 
END 
AS [DESTINATIONTAXGROUP],
T.[STOREORIGINID] AS CHANNELID
FROM (SELECT 
          STO.[CODE], 
  STO.[DESCRIPTION], 
  STO.[SOURCETAXGROUP], 
  STO.[DESTINATIONTAXGROUP], 
  STO.[SOURCEITEMTAXGROUP],     
  STO.[DESTINATIONITEMTAXGROUP], 
  STO.[OVERRIDETYPE], 
  STO.[OVERRIDEBY], 
  RPRST.[STOREORIGINID]     
    FROM [ax].RETAILSALESTAXOVERRIDE STO       
INNER JOIN [ax].RETAILSALESTAXOVERRIDEGROUPMEMBER 
       GM ON STO.[CODE] = GM.[RBOSALESTAXOVERRIDECODE]       
    INNER JOIN [ax].RETAILSALESTAXOVERRIDEGROUP 
       ROG ON ROG.[CODE] = GM.[RBOSALESTAXOVERRIDEGROUPCODE]   
INNER JOIN [ax].RETAILPUBRETAILSTORETABLE 
   RPRST ON RPRST.[TAXOVERRIDEGROUP] = ROG.[RECID] ) T
)
GO

GO
PRINT N'Finished creating view [crt].[SALESTAXOVERRIDESVIEW]'
GO
-- End creating view [crt].[SALESTAXOVERRIDESVIEW]


GRANT SELECT ON [crt].[SALESTAXOVERRIDESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[SALESTAXOVERRIDEDETAILSVIEW]
PRINT N'Creating view [crt].[SALESTAXOVERRIDEDETAILSVIEW]';

GO
IF OBJECT_ID(N'[crt].[SALESTAXOVERRIDEDETAILSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SALESTAXOVERRIDEDETAILSVIEW]
GO

CREATE VIEW [crt].[SALESTAXOVERRIDEDETAILSVIEW] AS
(
SELECT     [RECID]
  ,[ADDITIONALDESCRIPTION]
  ,[CODE]
  ,[DESCRIPTION]
  ,[DESTINATIONITEMTAXGROUP]
  ,[DESTINATIONTAXGROUP]
  ,[OVERRIDEBY]
  ,[OVERRIDEFROM]
  ,[OVERRIDETO]
  ,[OVERRIDETYPE]
  ,[SOURCEITEMTAXGROUP]
  ,[SOURCETAXGROUP]
  ,[STATUS]
  ,[DATAAREAID]
  FROM [ax].[RETAILSALESTAXOVERRIDE]
)
 

GO
PRINT N'Finished creating view [crt].[SALESTAXOVERRIDEDETAILSVIEW]'
GO
-- End creating view [crt].[SALESTAXOVERRIDEDETAILSVIEW]

 
GRANT SELECT ON [crt].[SALESTAXOVERRIDEDETAILSVIEW] TO [UsersRole];
GO


-- Creating view [crt].[CARTSVIEW]
PRINT N'Creating view [crt].[CARTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CARTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CARTSVIEW]
GO

CREATE VIEW [crt].[CARTSVIEW] AS
(
    SELECT
        st.[TRANSACTIONID],
        st.[CHANNELID],
        st.[TERMINALID],
        st.[STAFF],
        st.[CUSTOMERID],
        st.[TYPE],
        st.[NAME],
        st.[ISSUSPENDED],
        st.[TRANSACTIONDATA],
        st.[BYTELENGTH],
        st.[AMOUNT],
        st.[COMMENT],
        st.[CREATEDDATETIME],
        st.[MODIFIEDDATETIME]
    FROM [crt].SALESTRANSACTION st
    WHERE st.[DELETEDDATETIME] IS NULL
)


GO
PRINT N'Finished creating view [crt].[CARTSVIEW]'
GO
-- End creating view [crt].[CARTSVIEW]


GRANT SELECT ON [crt].[CARTSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CATEGORYITEMSVIEW]
PRINT N'Creating view [crt].[CATEGORYITEMSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATEGORYITEMSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATEGORYITEMSVIEW]
GO

CREATE VIEW [crt].[CATEGORYITEMSVIEW] AS
(
    -- get items assigned to a retail category
    SELECT
        catlookup.CATEGORY AS CATEGORYID,
        item.ITEMID AS ITEMID,
        NULL AS INVENTDIMID,
        item.DATAAREAID
    FROM [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] AS catlookup
    INNER JOIN [ax].[ECORESPRODUCTCATEGORY] AS prodcat ON prodcat.CATEGORY = catlookup.CONTAINEDCATEGORY
    INNER JOIN [ax].[INVENTTABLE] AS item ON item.PRODUCT = prodcat.PRODUCT

    UNION ALL

    -- get variants assigned to a supplemental category
    SELECT
        catlookup.CATEGORY as CATEGORYID,
        dim.ITEMID as ITEMID,
        dim.INVENTDIMID as INVENTDIMID,
        dim.DATAAREAID
    FROM [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] AS catlookup
    INNER JOIN [ax].[RETAILSPECIALCATEGORYMEMBER] AS spmem ON spmem.CATEGORY = catlookup.CONTAINEDCATEGORY
    INNER JOIN [ax].[RETAILGROUPMEMBERLINE] AS srgl ON srgl.RECID = spmem.RETAILGROUPMEMBER
    INNER JOIN [ax].[INVENTDIMCOMBINATION] AS dim ON dim.DISTINCTPRODUCTVARIANT = srgl.VARIANT
)


GO
PRINT N'Finished creating view [crt].[CATEGORYITEMSVIEW]'
GO
-- End creating view [crt].[CATEGORYITEMSVIEW]


GRANT SELECT ON [crt].[CATEGORYITEMSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[RETAILGROUPMEMBERITEMSVIEW]
PRINT N'Creating view [crt].[RETAILGROUPMEMBERITEMSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILGROUPMEMBERITEMSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILGROUPMEMBERITEMSVIEW]
GO

CREATE VIEW [crt].[RETAILGROUPMEMBERITEMSVIEW] AS
(
    -- get items assigned to member line
    SELECT
        rgl.RECID AS RETAILGROUPMEMBERLINE,
        item.ITEMID AS ITEMID,
        NULL AS INVENTDIMID,
        item.DATAAREAID
    FROM [ax].[RETAILGROUPMEMBERLINE] AS rgl
    INNER JOIN [ax].[INVENTTABLE] AS item ON item.PRODUCT = rgl.PRODUCT
    WHERE rgl.PRODUCT <> 0 AND rgl.VARIANT = 0

    UNION ALL

    -- get variants assigned to member line
    SELECT
        rgl.RECID AS RETAILGROUPMEMBERLINE,
        dim.ITEMID AS ITEMID,
        dim.INVENTDIMID AS INVENTDIMID,
        dim.DATAAREAID
    FROM [ax].[RETAILGROUPMEMBERLINE] AS rgl
    INNER JOIN [ax].[INVENTDIMCOMBINATION] AS dim ON dim.DISTINCTPRODUCTVARIANT = rgl.VARIANT
    WHERE rgl.VARIANT <> 0

    UNION ALL

    -- items and variants assigned to category member line
    SELECT
        rgl.RECID AS RETAILGROUPMEMBERLINE,
        cti.ITEMID AS ITEMID,
        cti.INVENTDIMID AS INVENTDIMID,
        cti.DATAAREAID
    FROM [ax].[RETAILGROUPMEMBERLINE] AS rgl
    INNER JOIN [crt].[CATEGORYITEMSVIEW] AS cti ON cti.CATEGORYID = rgl.CATEGORY
    WHERE rgl.PRODUCT = 0 AND rgl.VARIANT = 0
)


GO
PRINT N'Finished creating view [crt].[RETAILGROUPMEMBERITEMSVIEW]'
GO
-- End creating view [crt].[RETAILGROUPMEMBERITEMSVIEW]


GRANT SELECT ON [crt].[RETAILGROUPMEMBERITEMSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CATEGORYPRICEADJUSTMENTSVIEW]
PRINT N'Creating view [crt].[CATEGORYPRICEADJUSTMENTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATEGORYPRICEADJUSTMENTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATEGORYPRICEADJUSTMENTSVIEW]
GO

CREATE VIEW [crt].[CATEGORYPRICEADJUSTMENTSVIEW] AS
(
    SELECT
        catlookup.CATEGORY AS CATEGORYID,
        pd.RECID AS PRICEADJUSTMENTID,
        pd.OFFERID AS OFFERID,
        pd.DATAAREAID
    FROM [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] AS catlookup
    INNER JOIN [ax].[RETAILGROUPMEMBERLINE] AS rgl ON rgl.CATEGORY = catlookup.CONTAINEDCATEGORY AND rgl.PRODUCT = 0 AND rgl.VARIANT = 0
    INNER JOIN [ax].[RETAILPERIODICDISCOUNTLINE] AS pdl ON pdl.RETAILGROUPMEMBERLINE = rgl.RECID
    INNER JOIN [ax].[RETAILPERIODICDISCOUNT] AS pd ON pd.OFFERID = pdl.OFFERID AND pd.DATAAREAID = pdl.DATAAREAID AND pd.PERIODICDISCOUNTTYPE = 3
)


GO
PRINT N'Finished creating view [crt].[CATEGORYPRICEADJUSTMENTSVIEW]'
GO
-- End creating view [crt].[CATEGORYPRICEADJUSTMENTSVIEW]


GRANT SELECT ON [crt].[CATEGORYPRICEADJUSTMENTSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[PRICEADJUSTMENTITEMSVIEW]
PRINT N'Creating view [crt].[PRICEADJUSTMENTITEMSVIEW]';

GO
IF OBJECT_ID(N'[crt].[PRICEADJUSTMENTITEMSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PRICEADJUSTMENTITEMSVIEW]
GO

CREATE VIEW [crt].[PRICEADJUSTMENTITEMSVIEW] AS
(
    SELECT
        pa.OFFERID,
        pa.RECID,
        rgl.ITEMID,
        rgl.INVENTDIMID,
        rgl.DATAAREAID
    FROM [ax].RETAILPERIODICDISCOUNT AS pa
    INNER JOIN [ax].RETAILPERIODICDISCOUNTLINE AS pal ON pal.OFFERID = pa.OFFERID AND pal.DATAAREAID = pa.DATAAREAID
    INNER JOIN [crt].RETAILGROUPMEMBERITEMSVIEW AS rgl ON rgl.RETAILGROUPMEMBERLINE = pal.RETAILGROUPMEMBERLINE AND rgl.DATAAREAID = pal.DATAAREAID
    WHERE pa.PERIODICDISCOUNTTYPE = 3
)


GO
PRINT N'Finished creating view [crt].[PRICEADJUSTMENTITEMSVIEW]'
GO
-- End creating view [crt].[PRICEADJUSTMENTITEMSVIEW]


GRANT SELECT ON [crt].[PRICEADJUSTMENTITEMSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELPRICEGROUPITEMSVIEW]
PRINT N'Creating view [crt].[CHANNELPRICEGROUPITEMSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELPRICEGROUPITEMSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELPRICEGROUPITEMSVIEW]
GO

CREATE VIEW [crt].[CHANNELPRICEGROUPITEMSVIEW] AS
(
    SELECT
        cpg.PRICEGROUP,
        ta.ITEMRELATION AS ITEMID,
        ta.INVENTDIMID,
        pdg.GROUPID AS OFFERID,
        pdg.DATAAREAID
    FROM [ax].[RETAILCHANNELPRICEGROUP] AS cpg
    INNER JOIN [ax].[PRICEDISCGROUP] AS pdg ON pdg.RECID = cpg.PRICEGROUP
    INNER JOIN [ax].[PRICEDISCTABLE] AS ta ON ta.ACCOUNTRELATION = pdg.GROUPID AND ta.ACCOUNTCODE = 1 AND ta.RELATION = 4 AND ta.ITEMCODE = 0 and ta.DATAAREAID = pdg.DATAAREAID

    UNION ALL

    SELECT
        cpg.PRICEGROUP,
        rgl.ITEMID,
        rgl.INVENTDIMID,
        pd.OFFERID,
        pd.DATAAREAID
    FROM [ax].[RETAILCHANNELPRICEGROUP] AS cpg
    INNER JOIN [ax].[RETAILPERIODICDISCOUNT] AS pd ON pd.PRICEDISCGROUP = cpg.PRICEGROUP AND pd.PERIODICDISCOUNTTYPE = 3
    INNER JOIN [ax].[RETAILPERIODICDISCOUNTLINE] AS pdl ON pdl.OFFERID = pd.OFFERID AND pdl.DATAAREAID = pd.DATAAREAID
    INNER JOIN [crt].[RETAILGROUPMEMBERITEMSVIEW] AS rgl ON rgl.RETAILGROUPMEMBERLINE = pdl.RETAILGROUPMEMBERLINE AND rgl.DATAAREAID = pdl.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[CHANNELPRICEGROUPITEMSVIEW]'
GO
-- End creating view [crt].[CHANNELPRICEGROUPITEMSVIEW]


GRANT SELECT ON [crt].[CHANNELPRICEGROUPITEMSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CATALOGLISTDEFINITIONVIEW]
PRINT N'Creating view [crt].[CATALOGLISTDEFINITIONVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATALOGLISTDEFINITIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATALOGLISTDEFINITIONVIEW]
GO

CREATE VIEW [crt].[CATALOGLISTDEFINITIONVIEW] AS
(
    SELECT
    cd.CHANNELID,
        cd.LISTID,
        cd.ATTRIBUTERECID,
        cd.ATTRIBUTEKEYNAME,
        cd.LISTGROUPID,
        COUNT(*) AS LISTLENGTH
    FROM [crt].CATALOGDEFINITION cd
    INNER JOIN [crt].CATALOGLISTMAPPING cm ON cm.LISTID = cd.LISTID
    GROUP BY cd.CHANNELID, cd.LISTID, cd.ATTRIBUTERECID, cd.ATTRIBUTEKEYNAME, cd.LISTGROUPID
)


GO
PRINT N'Finished creating view [crt].[CATALOGLISTDEFINITIONVIEW]'
GO
-- End creating view [crt].[CATALOGLISTDEFINITIONVIEW]


GRANT SELECT ON [crt].[CATALOGLISTDEFINITIONVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CATALOGLISTDEFINITIONVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELCURRENCIESVIEW]
PRINT N'Creating view [crt].[CHANNELCURRENCIESVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELCURRENCIESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELCURRENCIESVIEW]
GO

CREATE VIEW [crt].[CHANNELCURRENCIESVIEW] AS
(
    SELECT
        rccur.CHANNEL AS 'CHANNELID',
        cur.RECID,
        cur.CURRENCYCODE,
        cur.SYMBOL
    FROM [ax].CURRENCY cur
    INNER JOIN [ax].RETAILCHANNELCURRENCY rccur ON cur.CURRENCYCODE = rccur.CURRENCYCODE
)


GO
PRINT N'Finished creating view [crt].[CHANNELCURRENCIESVIEW]'
GO
-- End creating view [crt].[CHANNELCURRENCIESVIEW]


GRANT SELECT ON [crt].[CHANNELCURRENCIESVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELCURRENCIESVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[SALESTAXGROUPSVIEW]
PRINT N'Creating view [crt].[SALESTAXGROUPSVIEW]';

GO
IF OBJECT_ID(N'[crt].[SALESTAXGROUPSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SALESTAXGROUPSVIEW]
GO

CREATE VIEW [crt].[SALESTAXGROUPSVIEW] AS
(
    SELECT RECID,
   TAXGROUP, 
   TAXGROUPNAME ,
   DATAAREAID
   FROM [ax].TAXGROUPHEADING 
)


GO
PRINT N'Finished creating view [crt].[SALESTAXGROUPSVIEW]'
GO
-- End creating view [crt].[SALESTAXGROUPSVIEW]


GRANT SELECT ON [crt].[SALESTAXGROUPSVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[SALESTAXGROUPSVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[LOYALTYTIERSVIEW]
PRINT N'Creating view [crt].[LOYALTYTIERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[LOYALTYTIERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[LOYALTYTIERSVIEW]
GO

CREATE VIEW [crt].[LOYALTYTIERSVIEW] AS
(
    select
rlt.RECID,
rlt.AFFILIATION as LoyaltyGroupRecordId,
rlt.TIERID,
rlt.TIERLEVEL
from [ax].[RETAILLOYALTYTIER] rlt
)


GO
PRINT N'Finished creating view [crt].[LOYALTYTIERSVIEW]'
GO
-- End creating view [crt].[LOYALTYTIERSVIEW]


GRANT SELECT ON [crt].[LOYALTYTIERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[PRODUCTIDENTITIESVIEW]
PRINT N'Creating view [crt].[PRODUCTIDENTITIESVIEW]';

GO
IF OBJECT_ID(N'[crt].[PRODUCTIDENTITIESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PRODUCTIDENTITIESVIEW]
GO

CREATE VIEW [crt].PRODUCTIDENTITIESVIEW AS
(
    ---!!!!!!!! If you are changing this view, make sure that the view GetProductIdentities is also changed. !!!!!!

        -- This select retrieves only standalone products and products' masters
    SELECT
        DISTINCT p.RECID,
        [p].RECID AS LOOKUPID,
        [apv].CHANNELID,
        CASE
            WHEN (([pv].RECID IS NULL) AND ([pv2].RECID IS NOT NULL)) THEN 1
            ELSE 0
        END AS ISMASTER,
        CASE 
            WHEN ([rk].RECID IS NULL) THEN 0
            ELSE 1
        END AS ISKIT,
        0 AS MASTERPRODUCT,
        [p].DISPLAYPRODUCTNUMBER,
        [p].SEARCHNAME,
        [it].ITEMID,
        '' AS INVENTDIMID,
        [apv].VALIDFROM,
        [apv].VALIDTO
    FROM [ax].ECORESPRODUCT p
        INNER JOIN [crt].ASSORTEDPRODUCTSVIEW apv ON [apv].PRODUCTID = [p].RECID
        INNER JOIN [ax].INVENTTABLE it ON [it].PRODUCT = [p].RECID
        LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON [pv].RECID = [p].RECID
        LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv2 ON [pv2].PRODUCTMASTER = [p].RECID
        LEFT OUTER JOIN [ax].RETAILKIT rk ON [rk].PRODUCTMASTER = [p].RECID

    UNION ALL

    -- This select returns only variants (no standalone and no product masters)
    SELECT
        DISTINCT p.RECID,
        [pv].PRODUCTMASTER AS LOOKUPID,
        [apv].CHANNELID,
        0 AS ISMASTER,
        0 AS ISKIT,
        [pv].PRODUCTMASTER AS MASTERPRODUCT,
        [p].DISPLAYPRODUCTNUMBER,
        [p].SEARCHNAME,
        [idc].ITEMID,
        [idc].INVENTDIMID,
        [apv].VALIDFROM,
        [apv].VALIDTO
    FROM [ax].[ECORESPRODUCT] p
        INNER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON [pv].RECID = [p].RECID
        INNER JOIN [crt].ASSORTEDPRODUCTSVIEW apv ON [apv].PRODUCTID = [pv].PRODUCTMASTER
        INNER JOIN [ax].INVENTDIMCOMBINATION idc ON [idc].DISTINCTPRODUCTVARIANT = [p].RECID
        INNER JOIN [ax].INVENTTABLE it ON [it].ITEMID = [idc].ITEMID AND [idc].DATAAREAID = [it].DATAAREAID
)

GO
PRINT N'Finished creating view [crt].[PRODUCTIDENTITIESVIEW]'
GO
-- End creating view [crt].[PRODUCTIDENTITIESVIEW]


GRANT SELECT ON [crt].[PRODUCTIDENTITIESVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PRODUCTIDENTITIESVIEW] TO [PublishersRole];
GO
-- Creates a view which joins the RetailKit table with RetailListing table 
-- so as to get the listing Id of the Kit product

-- Creating view [crt].[RETAILKITLISTINGVIEW]
PRINT N'Creating view [crt].[RETAILKITLISTINGVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILKITLISTINGVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILKITLISTINGVIEW]
GO
CREATE VIEW [crt].[RETAILKITLISTINGVIEW] AS
(
SELECT
PIV.RECID as KITPRODUCTMASTERLISTING,   -- Listing Id of the kit
PIV.CHANNELID AS CHANNEL,
RK.DISASSEMBLYATREGISTERALLOWED,
RK.RECID as KITRECID
FROM [crt].PRODUCTIDENTITIESVIEW PIV
INNER JOIN [ax].RETAILKIT RK ON PIV.LOOKUPID = RK.PRODUCTMASTER
WHERE PIV.MASTERPRODUCT = 0
)


GO
PRINT N'Finished creating view [crt].[RETAILKITLISTINGVIEW]'
GO
-- End creating view [crt].[RETAILKITLISTINGVIEW]


GRANT SELECT ON [crt].[RETAILKITLISTINGVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[RETAILKITLISTINGVIEW] TO [PublishersRole];
GO
-- Creates a view which is used to read the quantity and unit properties of the components and substitutes of a kit
-- Since the component and substitutes have the same type of property (like unit qty etc) the view contains a union 
-- of the queries that gives the property of the components and the property of the substitutes

-- Creating view [crt].[RETAILKITLINEDEFINITIONVIEW]
PRINT N'Creating view [crt].[RETAILKITLINEDEFINITIONVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILKITLINEDEFINITIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILKITLINEDEFINITIONVIEW]
GO

CREATE VIEW [crt].[RETAILKITLINEDEFINITIONVIEW] AS
(
    SELECT
        PIV.RECID as KITLINEPRODUCTLISTING,                 -- Listing Id of the product used as component
        PIV.CHANNELID AS CHANNEL,
        PIV.MASTERPRODUCT as KITLINEPRODUCTMASTERLISTING,   -- Parent Listing Id of the product used as component
        RKC.QUANTITY,
        UOM.SYMBOL as UNIT,
0 AS CHARGE,
        1 AS ISDEFAULTCOMPONENT,
        RKLV.KITPRODUCTMASTERLISTING,
        RKC.RECID as KITLINEIDENTIFIER
    FROM [crt].PRODUCTIDENTITIESVIEW PIV
        INNER JOIN [ax].RETAILKITCOMPONENT RKC ON PIV.RECID = RKC.COMPONENT 
        INNER JOIN [ax].UNITOFMEASURE UOM ON UOM.RECID = RKC.UNITOFMEASURE  
        INNER JOIN [crt].RETAILKITLISTINGVIEW RKLV ON RKLV.KITRECID = RKC.KIT AND RKLV.CHANNEL = PIV.CHANNELID

    UNION

    SELECT 
        PIV.RECID AS KITLINEPRODUCTLISTING,                 -- Listing Id of the product used as substitute
        PIV.CHANNELID AS CHANNEL,
        PIV.MASTERPRODUCT AS KITLINEPRODUCTMASTERLISTING,   -- Parent listing Id of the product used as substitute
        RKCS.QUANTITY,
        UOM.SYMBOL as UNIT,  
ISNULL(RKRSC.SUBSTITUTECHARGE, 0) AS CHARGE,   
        0 AS ISDEFAULTCOMPONENT,
        RKLV.KITPRODUCTMASTERLISTING,
        RKCS.KITCOMPONENT AS KITLINEIDENTIFIER              -- This identifies each kit component lines uniquely
    FROM 
    [ax].RETAILKITCOMPONENTSUBSTITUTE RKCS
        INNER JOIN [ax].RETAILKITCOMPONENT RKC ON RKC.RECID = RKCS.KITCOMPONENT
        INNER JOIN [ax].UNITOFMEASURE UOM ON UOM.RECID = RKCS.UNITOFMEASURE     
        INNER JOIN [crt].RETAILKITLISTINGVIEW RKLV ON RKLV.KITRECID = RKC.KIT 
        INNER JOIN [crt].PRODUCTIDENTITIESVIEW PIV ON PIV.RECID = RKCS.SUBSTITUTEPRODUCT AND PIV.CHANNELID = RKLV.CHANNEL
INNER JOIN [ax].RETAILCHANNELTABLE RCT ON RCT.RECID = RKLV.CHANNEL
LEFT JOIN [ax].RETAILKITRELEASEDSUBSTITUTECHARGE RKRSC ON RKRSC.KITCOMPONENTSUBSTITUTE = RKCS.RECID AND RKRSC.DATAAREAID = RCT.INVENTLOCATIONDATAAREAID
)



GO
PRINT N'Finished creating view [crt].[RETAILKITLINEDEFINITIONVIEW]'
GO
-- End creating view [crt].[RETAILKITLINEDEFINITIONVIEW]


GRANT SELECT ON [crt].[RETAILKITLINEDEFINITIONVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[RETAILKITLINEDEFINITIONVIEW] TO [PublishersRole];
GO
-- Creates a view which joins the RETAILKITVARIANTCOMPONENT table with RetailListing table 
-- so as to get the inventDimId of the kit configuration(kit variants) specified in RetailKitVariantComponent and 
-- also to get the listing Id of the kit variant and the components contained in the various kit configurations (kit variants)
-- This view is then used to generate the kit configuration to component product mapping

-- Creating view [crt].[RETAILKITVARIANTMAPVIEW]
PRINT N'Creating view [crt].[RETAILKITVARIANTMAPVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILKITVARIANTMAPVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILKITVARIANTMAPVIEW]
GO

CREATE VIEW [crt].[RETAILKITVARIANTMAPVIEW] AS
(
SELECT 
PIV.CHANNELID AS CHANNEL,
PIV2.RECID AS COMPONENTPRODUCTLISTING,    -- Listing Id of the product used as component in a kitvariant
PIV.RECID AS KITPRODUCTVARIANTLISTING,
PIV.MASTERPRODUCT AS KITPRODUCTMASTERLISTING,
PIV.INVENTDIMID,
    ID.CONFIGID,
RKVC.COMPONENTRECID AS KITLINEIDENTIFIER
FROM [ax].RETAILKITVARIANTCOMPONENT RKVC
INNER JOIN [crt].PRODUCTIDENTITIESVIEW PIV ON RKVC.KITVARIANT = PIV.RECID
INNER JOIN [ax].RETAILCHANNELTABLE RCT ON PIV.CHANNELID = RCT.RECID
INNER JOIN [ax].INVENTDIM ID ON ID.INVENTDIMID = PIV.INVENTDIMID AND ID.DATAAREAID = RCT.INVENTLOCATIONDATAAREAID
INNER JOIN [crt].PRODUCTIDENTITIESVIEW PIV2 ON PIV2.RECID = RKVC.COMPONENT AND PIV2.CHANNELID = PIV.CHANNELID 
)


GO
PRINT N'Finished creating view [crt].[RETAILKITVARIANTMAPVIEW]'
GO
-- End creating view [crt].[RETAILKITVARIANTMAPVIEW]


GRANT SELECT ON [crt].[RETAILKITVARIANTMAPVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[RETAILKITVARIANTMAPVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[FORMULADESIGNERSINDIANVIEW]
PRINT N'Creating view [crt].[FORMULADESIGNERSINDIANVIEW]';

GO
IF OBJECT_ID(N'[crt].[FORMULADESIGNERSINDIANVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[FORMULADESIGNERSINDIANVIEW]
GO

CREATE VIEW [crt].[FORMULADESIGNERSINDIANVIEW] AS
(
    SELECT
        fd.[RECID],
fd.[CALCEXP],
fd.[CALCEXP1],
fd.[ID],
fd.[PRICEINCLTAX],
fd.[TAXABLEBASIS],
fd.[TAXCODE],
fd.[TAXITEMGROUP],
rct.[RECID] as [CHANNELID]
    FROM [ax].FORMULADESIGNER_IN fd
INNER JOIN [ax].RETAILCHANNELTABLE rct on rct.INVENTLOCATIONDATAAREAID = fd.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[FORMULADESIGNERSINDIANVIEW]'
GO
-- End creating view [crt].[FORMULADESIGNERSINDIANVIEW]


GRANT SELECT ON [crt].[FORMULADESIGNERSINDIANVIEW] TO [UsersRole];
GO

-- Creating view [crt].[TAXPARAMETERSVIEW]
PRINT N'Creating view [crt].[TAXPARAMETERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[TAXPARAMETERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TAXPARAMETERSVIEW]
GO

CREATE VIEW [crt].[TAXPARAMETERSVIEW] AS
(
    SELECT
        tp.[RECID],
        tp.[SALESTAX_IN],
tp.[SERVICETAX_IN],
tp.[VAT_IN],
rct.[RECID] AS [CHANNELID]
    FROM [ax].TAXPARAMETERS tp
INNER JOIN [ax].RETAILCHANNELTABLE rct ON rct.INVENTLOCATIONDATAAREAID = tp.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[TAXPARAMETERSVIEW]'
GO
-- End creating view [crt].[TAXPARAMETERSVIEW]


GRANT SELECT ON [crt].[TAXPARAMETERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[ITEMSMAXRETAILPRICESINDIAVIEW]
PRINT N'Creating view [crt].[ITEMSMAXRETAILPRICESINDIAVIEW]';

GO
IF OBJECT_ID(N'[crt].[ITEMSMAXRETAILPRICESINDIAVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ITEMSMAXRETAILPRICESINDIAVIEW]
GO

CREATE VIEW [crt].[ITEMSMAXRETAILPRICESINDIAVIEW] AS
(
    SELECT
        it.[RECID],
        it.[ITEMID],
        it.[DATAAREAID],
        itm.[MAXIMUMRETAILPRICE_IN]
    FROM [ax].INVENTTABLE it
    INNER JOIN [ax].INVENTTABLEMODULE itm ON itm.ITEMID = it.ITEMID AND itm.MODULETYPE = 2 AND itm.DATAAREAID = it.DATAAREAID -- 2 = Sales
)


GO
PRINT N'Finished creating view [crt].[ITEMSMAXRETAILPRICESINDIAVIEW]'
GO
-- End creating view [crt].[ITEMSMAXRETAILPRICESINDIAVIEW]


GRANT SELECT ON [crt].[ITEMSMAXRETAILPRICESINDIAVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[ITEMSMAXRETAILPRICESINDIAVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[RETAILDISCOUNTLINESVIEW]
PRINT N'Creating view [crt].[RETAILDISCOUNTLINESVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILDISCOUNTLINESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILDISCOUNTLINESVIEW]
GO
/********************************************************************************
    RetailDiscountLinesView retrieves the discount detail line information by joining six tables.
RETAILPERIODICDISCOUNTLINE - AX table that stores the discount line definitions.
    RETAILPERIODICDISCOUNT - AX table that stores the discount definitions.
RETAILGROUPMEMBERLINE - AX table that contains category/product/variants for a group.
    RETAILDISCOUNTLINEMIXANDMATCH - AX table that holds mix and match discount line groups.
    RETAILDISCOUNTLINEOFFER - AX table that holds the amount values for line-specific discounts.
UNITOFMEASURE - AX table that holds units of measurement for products.
********************************************************************************/
CREATE VIEW crt.RETAILDISCOUNTLINESVIEW
AS
(
SELECT
pdl.DATAAREAID,
pdl.OFFERID,
pdl.LINENUM,
        pdl.DISCOUNTPERCENTORVALUE,

        ISNULL(mmol.LINEGROUP, '') AS LINEGROUP,
        ISNULL(mmol.DISCOUNTTYPE, 0) AS MIXANDMATCHLINEDISCOUNTTYPE,
        ISNULL(mmlg.NUMBEROFITEMSNEEDED, 0) AS NUMBEROFITEMSNEEDED,

        ISNULL(dol.DISCOUNTMETHOD, 0) AS DISCOUNTMETHOD,
        ISNULL(dol.DISCAMOUNT, 0) AS DISCAMOUNT,
        ISNULL(dol.DISCPCT, 0) AS DISCPCT,
        ISNULL(dol.OFFERPRICE, 0) AS OFFERPRICE,
        ISNULL(dol.OFFERPRICEINCLTAX, 0) AS OFFERPRICEINCLTAX,

        ISNULL(uom.SYMBOL,'') AS SYMBOL,
rgl.CATEGORY,
rgl.PRODUCT,
rgl.VARIANT
FROM [ax].[RETAILPERIODICDISCOUNTLINE] pdl
INNER JOIN [ax].RETAILPERIODICDISCOUNT pd ON pd.OFFERID = pdl.OFFERID AND pd.DATAAREAID = pdl.DATAAREAID
INNER JOIN [ax].RETAILGROUPMEMBERLINE rgl ON rgl.RECID = pdl.RETAILGROUPMEMBERLINE
LEFT OUTER JOIN [ax].RETAILDISCOUNTLINEMIXANDMATCH mmol ON mmol.RECID = pdl.RECID AND mmol.DATAAREAID = pdl.DATAAREAID
LEFT OUTER JOIN [ax].RETAILMIXANDMATCHLINEGROUPS mmlg ON mmlg.MIXANDMATCHID = pdl.OFFERID AND mmlg.MIXANDMATCHLINEGROUP = mmol.LINEGROUP AND mmlg.DATAAREAID = mmol.DATAAREAID
LEFT OUTER JOIN [ax].RETAILDISCOUNTLINEOFFER dol ON dol.RECID = pdl.RECID AND dol.DATAAREAID = pdl.DATAAREAID
LEFT OUTER JOIN [ax].UNITOFMEASURE uom ON uom.RECID = pdl.UNITOFMEASURE
WHERE pd.STATUS = 1
        AND (pd.PERIODICDISCOUNTTYPE != 3) -- Don't fetch promotions
)


GO
PRINT N'Finished creating view [crt].[RETAILDISCOUNTLINESVIEW]'
GO
-- End creating view [crt].[RETAILDISCOUNTLINESVIEW]


GRANT SELECT ON [crt].[RETAILDISCOUNTLINESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILDISCOUNTSVIEW]
PRINT N'Creating view [crt].[RETAILDISCOUNTSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILDISCOUNTSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILDISCOUNTSVIEW]
GO
/********************************************************************************
    RetailDiscountsView retrieves the discount header information by joining four tables.
    RETAILPERIODICDISCOUNT - AX table that stores the discount definitions.
    RETAILDISCOUNTMIXANDMATCH - AX table that holds mix and match discount parameters.
    RETAILDISCOUNTMULTIBUY - AX table that holds multibuy (quantity) discount parameters.
RETAILDISCOUNTTHRESHOLD - AX table that holds threshold (amount) discount parameters.
********************************************************************************/
CREATE VIEW crt.RETAILDISCOUNTSVIEW
AS
(
    SELECT
pd.DATAAREAID,
pd.CURRENCYCODE,
pd.PRICEDISCGROUP,
        pd.OFFERID,
        pd.NAME,
        pd.PERIODICDISCOUNTTYPE,
        pd.CONCURRENCYMODE,
        pd.ISDISCOUNTCODEREQUIRED,
        pd.VALIDATIONPERIODID,
        pd.DATEVALIDATIONTYPE,
        pd.VALIDFROM,
        pd.VALIDTO,
        ISNULL(pdmm.MIXANDMATCHDISCOUNTTYPE, ISNULL(pdmb.MULTIBUYDISCOUNTTYPE, pd.PERIODICDISCOUNTTYPE)) AS DISCOUNTTYPE,
        ISNULL(pdmm.[DEALPRICEVALUE],0.0) AS DEALPRICEVALUE,
        pd.DISCOUNTPERCENTVALUE,
ISNULL(pdmm.[DISCOUNTAMOUNTVALUE],0.0) AS DISCOUNTAMOUNTVALUE,
ISNULL(pdmm.[NOOFLEASTEXPENSIVELINES],0) AS NOOFLEASTEXPENSIVELINES,
ISNULL(pdmm.[NUMBEROFTIMESAPPLICABLE],0) AS NUMBEROFTIMESAPPLICABLE,
pdt.COUNTNONDISCOUNTITEMS
FROM [ax].[RETAILPERIODICDISCOUNT] AS pd
LEFT OUTER JOIN [ax].[RETAILDISCOUNTMIXANDMATCH] AS pdmm ON pd.RECID = pdmm.RECID AND pd.DATAAREAID = pdmm.DATAAREAID
LEFT OUTER JOIN [ax].[RETAILDISCOUNTMULTIBUY] AS pdmb ON pd.RECID = pdmb.RECID AND pd.DATAAREAID = pdmb.DATAAREAID
LEFT OUTER JOIN [ax].[RETAILDISCOUNTTHRESHOLD] AS pdt ON pd.RECID = pdt.RECID AND pd.DATAAREAID = pdt.DATAAREAID
    WHERE pd.STATUS = 1
        AND (pd.PERIODICDISCOUNTTYPE != 3) -- Don't fetch promotions
)


GO
PRINT N'Finished creating view [crt].[RETAILDISCOUNTSVIEW]'
GO
-- End creating view [crt].[RETAILDISCOUNTSVIEW]


GRANT SELECT ON [crt].[RETAILDISCOUNTSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]
PRINT N'Creating view [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]';

GO
IF OBJECT_ID(N'[crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]
GO

CREATE VIEW [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW] WITH SCHEMABINDING AS
(
    SELECT
        rprct.ORIGINID AS CHANNEL,
rpcio.CATALOG,
COUNT_BIG(*) AS ANCESTORCOUNT
        FROM ax.RETAILPUBCATALOGINTERNALORG rpcio
        JOIN ax.RETAILPUBINTORGINHERITANCEEXPLODED rpioie
ON rpioie.ANCESTORINTERNALORG = rpcio.INTERNALORGANIZATION
JOIN ax.RETAILPUBRETAILCHANNELTABLE rprct
ON rprct.INTERNALORGANIZATION = rpioie.INTERNALORGANIZATION
            JOIN ax.RETAILPUBCATALOG rpc 
                ON rpc.ORIGIN = rpcio.CATALOG
        WHERE rpc.VALIDFROMDATETIME BETWEEN rpioie.VALIDFROM AND rpioie.VALIDTO -- VALIDFROMDATETIME is in UTC
GROUP BY rprct.ORIGINID, rpcio.CATALOG
)


GO
PRINT N'Finished creating view [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]'
GO
-- End creating view [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]', N'U'), N'IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CHANNEL_CATALOG', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CHANNEL_CATALOG'


CREATE UNIQUE CLUSTERED INDEX IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CHANNEL_CATALOG ON [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW] 
(
CHANNEL,
    CATALOG
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CHANNEL_CATALOG'



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW]', N'U'), N'IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CATALOG', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CATALOG'


CREATE NONCLUSTERED INDEX IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CATALOG ON [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW] 
(
    CATALOG
)
INCLUDE
(
CHANNEL
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW_CATALOG'


GRANT SELECT ON [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[PUBCATALOGCHANNELVIEW]
PRINT N'Creating view [crt].[PUBCATALOGCHANNELVIEW]';

GO
IF OBJECT_ID(N'[crt].[PUBCATALOGCHANNELVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PUBCATALOGCHANNELVIEW]
GO

CREATE VIEW [crt].[PUBCATALOGCHANNELVIEW] WITH SCHEMABINDING AS
(
    SELECT
        rprct.ORIGINID AS CHANNEL,
        rpcio.CATALOG,
        COUNT_BIG(*) AS ANCESTORCOUNT
    FROM ax.RETAILPUBCATALOGINTERNALORG rpcio
    JOIN ax.RETAILPUBCATALOG rpc ON rpc.ORIGIN = rpcio.CATALOG
    JOIN ax.RETAILINTERNALORGANIZATION rio ON rio.RECID = rpcio.INTERNALORGANIZATION
    JOIN ax.OMEXPLODEDORGANIZATIONSECURITYGRAPH omeosg ON omeosg.ANCESTORORGANIZATION = rio.INTERNALORGANIZATION
    JOIN ax.OMHIERARCHYPURPOSE omhp ON omhp.HIERARCHYTYPE = omeosg.OMHIERARCHYTYPE AND omhp.HIERARCHYPURPOSE = 9 /* RetailAssortment */ AND omhp.ISDEFAULT = 1
    JOIN ax.RETAILPUBRETAILCHANNELTABLE rprct ON rprct.OMOPERATINGUNITID = omeosg.ORGANIZATION
    WHERE rpc.VALIDFROMDATETIME BETWEEN omeosg.VALIDFROM AND omeosg.VALIDTO -- VALIDFROMDATETIME is in UTC
    GROUP BY rprct.ORIGINID, rpcio.CATALOG
)


GO
PRINT N'Finished creating view [crt].[PUBCATALOGCHANNELVIEW]'
GO
-- End creating view [crt].[PUBCATALOGCHANNELVIEW]



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[PUBCATALOGCHANNELVIEW]', N'U'), N'IX_PUBCATALOGCHANNELVIEW_CHANNEL_CATALOG', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_PUBCATALOGCHANNELVIEW_CHANNEL_CATALOG'


CREATE UNIQUE CLUSTERED INDEX IX_PUBCATALOGCHANNELVIEW_CHANNEL_CATALOG ON [crt].[PUBCATALOGCHANNELVIEW]
(
    CHANNEL,
    CATALOG
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_PUBCATALOGCHANNELVIEW_CHANNEL_CATALOG'



IF INDEXPROPERTY (OBJECT_ID (N'[crt].[PUBCATALOGCHANNELVIEW]', N'U'), N'IX_PUBCATALOGCHANNELVIEW_CATALOG', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_PUBCATALOGCHANNELVIEW_CATALOG'


CREATE NONCLUSTERED INDEX IX_PUBCATALOGCHANNELVIEW_CATALOG ON [crt].[PUBCATALOGCHANNELVIEW]
(
    CATALOG
)
INCLUDE
(
    CHANNEL
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_PUBCATALOGCHANNELVIEW_CATALOG'


GRANT SELECT ON [crt].[PUBCATALOGCHANNELVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PUBCATALOGCHANNELVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[PRODUCTVARIANTCATEGORYVIEW]
PRINT N'Creating view [crt].[PRODUCTVARIANTCATEGORYVIEW]';

GO
IF OBJECT_ID(N'[crt].[PRODUCTVARIANTCATEGORYVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PRODUCTVARIANTCATEGORYVIEW]
GO

CREATE VIEW [crt].[PRODUCTVARIANTCATEGORYVIEW] AS
(
    SELECT
        ERDPV.RECID AS PRODUCT,
        ERPC.RECID AS PRODUCTCATEGORY,
        ERPC.CATEGORY
    FROM [ax].ECORESDISTINCTPRODUCTVARIANT ERDPV
        JOIN [ax].ECORESPRODUCTCATEGORY ERPC ON ERPC.PRODUCT = ERDPV.PRODUCTMASTER
)


GO
PRINT N'Finished creating view [crt].[PRODUCTVARIANTCATEGORYVIEW]'
GO
-- End creating view [crt].[PRODUCTVARIANTCATEGORYVIEW]


GRANT SELECT ON [crt].[PRODUCTVARIANTCATEGORYVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PRODUCTVARIANTCATEGORYVIEW] TO [PublishersRole];
GO

-- Creating view crt.PRODUCTATTRIBUTEMETADATAVIEW
PRINT N'Creating view crt.PRODUCTATTRIBUTEMETADATAVIEW';

GO
IF OBJECT_ID(N'crt.PRODUCTATTRIBUTEMETADATAVIEW', N'V') IS NOT NULL
    DROP VIEW crt.PRODUCTATTRIBUTEMETADATAVIEW
GO

CREATE VIEW crt.PRODUCTATTRIBUTEMETADATAVIEW AS
(
    SELECT 
        rppacm.ATTRIBUTE,
        rppacm.HOSTCHANNEL AS CHANNEL,
        rppacm.KEYNAME,
        av.DATATYPE,
        av.RAWDATATYPE
        FROM ax.RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA rppacm
            JOIN crt.ATTRIBUTEVIEW av
                ON av.ATTRIBUTE = rppacm.ATTRIBUTE
)


GO
PRINT N'Finished creating view crt.PRODUCTATTRIBUTEMETADATAVIEW'
GO
-- End creating view crt.PRODUCTATTRIBUTEMETADATAVIEW


GRANT SELECT ON crt.PRODUCTATTRIBUTEMETADATAVIEW TO [UsersRole];
GO

GRANT SELECT ON crt.PRODUCTATTRIBUTEMETADATAVIEW TO [PublishersRole];
GO

-- Creating view [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW]
PRINT N'Creating view [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW]';

GO
IF OBJECT_ID(N'[crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW]
GO

CREATE VIEW [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW] AS
(
    SELECT
        rppacm.HOSTCHANNEL AS CHANNEL,
        rppacm.ATTRIBUTE,
        rppacm.ATTRIBUTE AS ACTUALATTRIBUTE,
        0 AS ISREFERENCE
        FROM ax.RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA rppacm

    UNION ALL

    SELECT
        rppacm.HOSTCHANNEL AS CHANNEL,
        rav.ATTRIBUTE,
        rav.REFERENCEDATTRIBUTE AS ACTUALATTRIBUTE,
        1 AS ISREFERENCE
        FROM ax.RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA rppacm
            JOIN crt.REFERENCEATTRIBUTEVIEW rav
                ON rav.ATTRIBUTE = rppacm.ATTRIBUTE
)


GO
PRINT N'Finished creating view [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW]'
GO
-- End creating view [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW]


GRANT SELECT ON [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[ATTRIBUTEDEFAULTVALUEVIEW]
PRINT N'Creating view [crt].[ATTRIBUTEDEFAULTVALUEVIEW]';

GO
IF OBJECT_ID(N'[crt].[ATTRIBUTEDEFAULTVALUEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[ATTRIBUTEDEFAULTVALUEVIEW]
GO

CREATE VIEW [crt].[ATTRIBUTEDEFAULTVALUEVIEW] AS
(
    SELECT
        ppacmv.CHANNEL,
        ppacmv.ATTRIBUTE,
        ppacmv.ISREFERENCE,
        eradv.VALUE
        FROM crt.PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW ppacmv
            JOIN ax.ECORESATTRIBUTE era
                ON era.RECID = ppacmv.ACTUALATTRIBUTE
            JOIN ax.ECORESATTRIBUTETYPE erat
                ON erat.RECID = era.ATTRIBUTETYPE
            JOIN ax.ECORESATTRIBUTEDEFAULTVALUE eradv 
                ON eradv.ATTRIBUTE = ppacmv.ACTUALATTRIBUTE
WHERE erat.DATATYPE != 20-- REFEFENCE ATTRIBUTE TYPE
)


GO
PRINT N'Finished creating view [crt].[ATTRIBUTEDEFAULTVALUEVIEW]'
GO
-- End creating view [crt].[ATTRIBUTEDEFAULTVALUEVIEW]


GRANT SELECT ON [crt].[ATTRIBUTEDEFAULTVALUEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[ATTRIBUTEDEFAULTVALUEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]
PRINT N'Creating view [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]';

GO
IF OBJECT_ID(N'[crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]
GO

CREATE VIEW [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW] AS
(
    SELECT 
        ppacmv.ATTRIBUTE,
        ppacmv.ISREFERENCE,
        eraga.DEFAULTVALUE AS VALUE,
ppacmv.CHANNEL
        FROM ax.RETAILSHAREDPARAMETERS rsp 
            JOIN ax.ECORESATTRIBUTEGROUPATTRIBUTE eraga
                ON eraga.ATTRIBUTEGROUP = rsp.PRODUCTDEFAULTATTRIBUTEGROUP
JOIN crt.PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW ppacmv
ON ppacmv.ACTUALATTRIBUTE = eraga.ATTRIBUTE
        WHERE rsp.[KEY] = 0 AND eraga.DEFAULTVALUE != 0
)


GO
PRINT N'Finished creating view [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]'
GO
-- End creating view [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]


GRANT SELECT ON [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]
PRINT N'Creating view [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]';

GO
IF OBJECT_ID(N'[crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]
GO

CREATE VIEW [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW] AS
(
    SELECT 
        ppacmv.ATTRIBUTE,
        ppacmv.ISREFERENCE,
        eraga.DEFAULTVALUE AS VALUE,
        ppacmv.CHANNEL,
        rpioie.DISTANCE
        FROM ax.RETAILPUBINTERNALORGATTRIBUTEGROUP rpioag
            JOIN ax.RETAILPUBINTORGINHERITANCEEXPLODED rpioie 
                ON rpioie.ANCESTORINTERNALORG = rpioag.INTERNALORGANIZATION
            JOIN ax.RETAILPUBRETAILCHANNELTABLE rprct
                ON rprct.INTERNALORGANIZATION = rpioie.INTERNALORGANIZATION
            JOIN ax.ECORESATTRIBUTEGROUPATTRIBUTE eraga
                ON eraga.ATTRIBUTEGROUP = rpioag.ATTRIBUTEGROUP
            JOIN crt.PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW ppacmv
                ON ppacmv.ACTUALATTRIBUTE = eraga.ATTRIBUTE
                    AND ppacmv.CHANNEL = rprct.ORIGINID
        WHERE rpioag.MODIFIER = 1 AND eraga.DEFAULTVALUE != 0   -- Product
            AND GETUTCDATE() BETWEEN rpioie.VALIDFROM AND rpioie.VALIDTO
)


GO
PRINT N'Finished creating view [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]'
GO
-- End creating view [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW]


GRANT SELECT ON [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW]
PRINT N'Creating view [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW]';

GO
IF OBJECT_ID(N'[crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW]
GO

CREATE VIEW [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW] AS
(
    SELECT
        CHANNEL,
        ATTRIBUTE,
        ISREFERENCE,
        VALUE,
        1 AS SOURCE    -- AttributeDefaultValue
        FROM crt.ATTRIBUTEDEFAULTVALUEVIEW

    UNION ALL

    SELECT
        CHANNEL,
        ATTRIBUTE,
        ISREFERENCE,
        VALUE,
        2 AS SOURCE    -- DefaultProductAttributeGroupDefaultValue
        FROM crt.DEFAULTPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW

    UNION ALL

    SELECT
        CHANNEL,
        ATTRIBUTE,
        ISREFERENCE,
        VALUE,
        3 AS SOURCE    -- ChannelProductAttributeGroupDefaultValue
        FROM crt.CHANNELPRODUCTATTRIBUTEGROUPDEFAULTVALUEVIEW
)


GO
PRINT N'Finished creating view [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW]'
GO
-- End creating view [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW]


GRANT SELECT ON [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GLOBALPRODUCTATTRIBUTEVALUEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CATEGORYPRODUCTATTRIBUTEVIEW]
PRINT N'Creating view [crt].[CATEGORYPRODUCTATTRIBUTEVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATEGORYPRODUCTATTRIBUTEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATEGORYPRODUCTATTRIBUTEVIEW]
GO

CREATE VIEW [crt].[CATEGORYPRODUCTATTRIBUTEVIEW] AS
(
    SELECT 
        ercal.CATEGORY,
        ercal.ATTRIBUTE,
        eraga.ATTRIBUTEGROUP,

-- Workaround. Inherited specification attribute values do not make it to the Channel database. Schema change fix was punted.
        ISNULL(ercag.ATTRIBUTEGROUPTYPE, 0 /* Default */) AS ATTRIBUTEGROUPTYPE,

        eraga.DEFAULTVALUE
        FROM ax.ECORESCATEGORYATTRIBUTELOOKUP ercal 
            JOIN ax.ECORESATTRIBUTEGROUPATTRIBUTE eraga
                ON eraga.RECID = ercal.ATTRIBUTEGROUPATTRIBUTE
            LEFT JOIN ax.ECORESCATEGORYATTRIBUTEGROUP ercag
                ON ercag.CATEGORY = ercal.CATEGORY
                    AND ercag.MODIFIER = 1    -- Product
                    AND ercag.ATTRIBUTEGROUP = eraga.ATTRIBUTEGROUP
)


GO
PRINT N'Finished creating view [crt].[CATEGORYPRODUCTATTRIBUTEVIEW]'
GO
-- End creating view [crt].[CATEGORYPRODUCTATTRIBUTEVIEW]


GRANT SELECT ON [crt].[CATEGORYPRODUCTATTRIBUTEVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CATEGORYPRODUCTATTRIBUTEVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW]
PRINT N'Creating view [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW]';

GO
IF OBJECT_ID(N'[crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW]
GO

CREATE VIEW [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW] AS
(
    SELECT 
        rpioie.VALIDFROM AS ORGVALIDFROM,
        rpioie.VALIDTO AS ORGVALIDTO,
        ppacmv.ATTRIBUTE,
        ppacmv.ISREFERENCE,
        rppav.PRODUCT,
        ppacmv.CHANNEL,
        rppav.CATALOG,
        rpioie.DISTANCE,
        rppav.DATETIMEVALUE,
        rppav.DATETIMEVALUETZID,
        rppav.FLOATVALUE,
        rppav.INTVALUE, 
        rppav.LANGUAGEID,
        rppav.TEXTVALUE,
        rppav.UNITOFMEASURE
        FROM ax.RETAILPUBPRODUCTATTRIBUTEVALUE rppav
            JOIN ax.RETAILPUBINTORGINHERITANCEEXPLODED rpioie
                ON rpioie.ANCESTORINTERNALORG = rppav.INTERNALORGANIZATION
            JOIN ax.RETAILPUBRETAILCHANNELTABLE rprct
                ON rprct.INTERNALORGANIZATION = rpioie.INTERNALORGANIZATION
            JOIN crt.PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW ppacmv
                ON ppacmv.ACTUALATTRIBUTE = rppav.ATTRIBUTE
                    AND ppacmv.CHANNEL = rprct.ORIGINID
)


GO
PRINT N'Finished creating view [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW]'
GO
-- End creating view [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW]


GRANT SELECT ON [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW]
PRINT N'Creating view [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW]
GO

CREATE VIEW [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW] AS
(
    SELECT
rpcp.CATALOG,
        rpcp.PRODUCT,
        rpcpre.PRODUCTRELATION
        FROM ax.RETAILPUBCATALOGPRODUCT rpcp
            JOIN ax.RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION rpcpre 
                ON rpcpre.CATALOGPRODUCT = rpcp.ORIGIN
)


GO
PRINT N'Finished creating view [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW]'
GO
-- End creating view [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW]


GRANT SELECT ON [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CATALOGPRODUCTRELATIONEXCLUSIONVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[CATALOGPRODUCTRELATIONVIEW]
PRINT N'Creating view [crt].[CATALOGPRODUCTRELATIONVIEW]';

GO
IF OBJECT_ID(N'[crt].[CATALOGPRODUCTRELATIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CATALOGPRODUCTRELATIONVIEW]
GO

CREATE VIEW [crt].[CATALOGPRODUCTRELATIONVIEW] AS
(
    SELECT
rpcp.CATALOG,
        rpcp.PRODUCT,
        rpcpr.RELATEDPRODUCT,
        rpcpr.PRODUCTRELATIONTYPE
        FROM ax.RETAILPUBCATALOGPRODUCT rpcp
            JOIN ax.RETAILPUBCATALOGPRODUCTRELATION rpcpr
                ON rpcpr.CATALOGPRODUCT = rpcp.ORIGIN
)


GO
PRINT N'Finished creating view [crt].[CATALOGPRODUCTRELATIONVIEW]'
GO
-- End creating view [crt].[CATALOGPRODUCTRELATIONVIEW]


GRANT SELECT ON [crt].[CATALOGPRODUCTRELATIONVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[CATALOGPRODUCTRELATIONVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[SERIALIZEDITEMSVIEW]
PRINT N'Creating view [crt].[SERIALIZEDITEMSVIEW]';

GO
IF OBJECT_ID(N'[crt].[SERIALIZEDITEMSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[SERIALIZEDITEMSVIEW]
GO

CREATE VIEW [crt].[SERIALIZEDITEMSVIEW] AS
(
SELECT tdgi.RECID, 
   tdgi.ITEMID,
   tdgi.ITEMDATAAREAID,
   it.PRODUCT AS 'PRODUCTID'
FROM ax.ECORESTRACKINGDIMENSIONGROUPFLDSETUP tdgs
INNER JOIN ax.ECORESTRACKINGDIMENSIONGROUPITEM tdgi ON tdgi.TRACKINGDIMENSIONGROUP = tdgs.TRACKINGDIMENSIONGROUP
INNER JOIN [ax].INVENTTABLE it ON it.ITEMID = tdgi.ITEMID AND it.DATAAREAID = tdgi.ITEMDATAAREAID
WHERE TDGS.DIMENSIONFIELDID = 5 AND tdgs.ISACTIVE = 1-- DIMENSIONFIELDID 5 indicates that the tracking dimension is serial number
)


GO
PRINT N'Finished creating view [crt].[SERIALIZEDITEMSVIEW]'
GO
-- End creating view [crt].[SERIALIZEDITEMSVIEW]


GRANT SELECT ON [crt].[SERIALIZEDITEMSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW]
PRINT N'Creating view [crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW]
GO
-- Combining reference tables to simplify selection of ButtonGrid zones 
CREATE VIEW [crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW] AS
(
SELECT 
bgz.[BUTTONGRIDID]
,bgz.[RECID]
,rtlzr.[LAYOUTID]
,rtlz.[ZONEID]
,rtlz.[ZONENAME]
,rtlz.[ZONETYPE]
FROM [ax].[RETAILTILLLAYOUTBUTTONGRIDZONE] AS bgz
LEFT JOIN [ax].[RETAILTILLLAYOUTZONEREFERENCE] AS rtlzr on rtlzr.RECID = bgz.RECID
LEFT JOIN [ax].[RETAILTILLLAYOUTZONE] AS rtlz ON rtlz.RECID = rtlzr.ZONE
)


GO
PRINT N'Finished creating view [crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW]'
GO
-- End creating view [crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW]


GRANT SELECT ON [crt].[RETAILTILLLAYOUTBUTTONGRIDZONEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTILLLAYOUTIMAGEZONEVIEW]
PRINT N'Creating view [crt].[RETAILTILLLAYOUTIMAGEZONEVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTILLLAYOUTIMAGEZONEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTILLLAYOUTIMAGEZONEVIEW]
GO
-- Combining reference tables to simplify selection of image zones
CREATE VIEW [crt].[RETAILTILLLAYOUTIMAGEZONEVIEW] AS
(
SELECT 
iz.[PICTUREID]
,iz.[RECID]
,rtlzr.[LAYOUTID]
,rtlz.[ZONEID]
,rtlz.[ZONENAME]
,rtlz.[ZONETYPE]
FROM [ax].[RETAILTILLLAYOUTIMAGEZONE] AS iz
LEFT JOIN [ax].[RETAILTILLLAYOUTZONEREFERENCE] AS rtlzr on rtlzr.RECID = iz.RECID
LEFT JOIN [ax].[RETAILTILLLAYOUTZONE] AS rtlz ON rtlz.RECID = rtlzr.ZONE
)


GO
PRINT N'Finished creating view [crt].[RETAILTILLLAYOUTIMAGEZONEVIEW]'
GO
-- End creating view [crt].[RETAILTILLLAYOUTIMAGEZONEVIEW]


GRANT SELECT ON [crt].[RETAILTILLLAYOUTIMAGEZONEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTILLLAYOUTREPORTZONEVIEW]
PRINT N'Creating view [crt].[RETAILTILLLAYOUTREPORTZONEVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTILLLAYOUTREPORTZONEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTILLLAYOUTREPORTZONEVIEW]
GO
-- Combining reference tables to simplify selection of report zones
CREATE VIEW [crt].[RETAILTILLLAYOUTREPORTZONEVIEW] AS
(
SELECT 
rz.[REPORT]
,rz.[RECID]
,rtlzr.[LAYOUTID]
,rtlz.[ZONEID]
,rtlz.[ZONENAME]
,rtlz.[ZONETYPE]
FROM [ax].[RETAILTILLLAYOUTREPORTZONE] AS rz
LEFT JOIN [ax].[RETAILTILLLAYOUTZONEREFERENCE] AS rtlzr on rtlzr.RECID = rz.RECID
LEFT JOIN [ax].[RETAILTILLLAYOUTZONE] AS rtlz ON rtlz.RECID = rtlzr.ZONE
)


GO
PRINT N'Finished creating view [crt].[RETAILTILLLAYOUTREPORTZONEVIEW]'
GO
-- End creating view [crt].[RETAILTILLLAYOUTREPORTZONEVIEW]


GRANT SELECT ON [crt].[RETAILTILLLAYOUTREPORTZONEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTILLLAYOUTVIEW]
PRINT N'Creating view [crt].[RETAILTILLLAYOUTVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTILLLAYOUTVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTILLLAYOUTVIEW]
GO
-- Combining tables to simplify selection of TillLayout
CREATE VIEW [crt].[RETAILTILLLAYOUTVIEW] AS
(
    SELECT
rtl.[NAME]
,rtl.[WIDTH]
,rtl.[HEIGHT]
,rtl.[LAYOUTID]
,rtl.[CUSTOMERLAYOUTID]
,rtl.[TOTALID]
,rtl.[RECEIPTID]
,rtl.[LAYOUTXML]
,rtl.[CUSTOMERLAYOUTXML]
,rtl.[TOTALSLAYOUTXML]
,rtl.[CASHCHANGERLAYOUTXML]
,rtl.[RECEIPTPAYMENTLAYOUTXML]
,rtl.[RECEIPTITEMSLAYOUTXML]
,rtl.[RECID]
,rdt.[TYPE] AS DEVICETYPE
,rdt.[RECID] AS DEVICETYPERECID
    FROM [ax].[RETAILTILLLAYOUT] AS rtl
LEFT JOIN [ax].[RETAILDEVICETYPES] AS rdt ON rdt.RECID = rtl.DEVICETYPE
)


GO
PRINT N'Finished creating view [crt].[RETAILTILLLAYOUTVIEW]'
GO
-- End creating view [crt].[RETAILTILLLAYOUTVIEW]


GRANT SELECT ON [crt].[RETAILTILLLAYOUTVIEW] TO [UsersRole];
GO


-- Creating view [crt].[RETAILTHEMEPALLETCOLORVIEW]
PRINT N'Creating view [crt].[RETAILTHEMEPALLETCOLORVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTHEMEPALLETCOLORVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTHEMEPALLETCOLORVIEW]
GO
-- Combining reference tables to simplify selection of accent color
CREATE VIEW [crt].[RETAILTHEMEPALLETCOLORVIEW] AS
(
SELECT 
rtp.RECID
,rtac.COLOR
,rtc.ACCENTID
,rtc.NAME AS ACCENTNAME
FROM [ax].[RETAILTHEMEPALLET] as rtp
LEFT JOIN [ax].[RETAILTHEMEACCENTCOLOR] AS rtac ON rtac.PALLET = rtp.RECID
LEFT JOIN [ax].[RETAILTHEMEACCENT] AS rtc ON rtc.RECID = rtac.ACCENT
)


GO
PRINT N'Finished creating view [crt].[RETAILTHEMEPALLETCOLORVIEW]'
GO
-- End creating view [crt].[RETAILTHEMEPALLETCOLORVIEW]


GRANT SELECT ON [crt].[RETAILTHEMEPALLETCOLORVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILAFFILIATIONSVIEW]
PRINT N'Creating view [crt].[RETAILAFFILIATIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILAFFILIATIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILAFFILIATIONSVIEW]
GO

/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
    [crt].[RETAILAFFILIATIONSVIEW] creates a view about retail affiliation.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

CREATE VIEW [crt].[RETAILAFFILIATIONSVIEW] AS
(
  SELECT
    [RECID],
    [AFFILIATIONTYPE],
    [NAME]
  FROM [ax].RETAILAFFILIATION
);


GO
PRINT N'Finished creating view [crt].[RETAILAFFILIATIONSVIEW]'
GO
-- End creating view [crt].[RETAILAFFILIATIONSVIEW]


GRANT SELECT ON [crt].[RETAILAFFILIATIONSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW]
GO

/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
    [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW] creates a view 
    about retail transaction affiliation.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

CREATE VIEW [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW] AS
(
    SELECT
      RTAT.AFFILIATION,
      RTAT.LOYALTYTIER,
      RTAT.TRANSACTIONID,
      RTAT.TERMINALID,
      RTAT.RECEIPTID,
      RTAT.STAFFID,
      RTAT.STOREID,
      RTAT.DATAAREAID,
      RTAT.CHANNEL
    FROM [ax].RETAILTRANSACTIONAFFILIATIONTRANS RTAT
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW]
GO

/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
    [crt].[RETAILTRANSACTIONAFFILIATIONTRANSVIEW] creates a view 
    about reward point lines of retail transactions.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

CREATE VIEW [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW] AS
(
    SELECT
  RTLRPT.TRANSACTIONID AS TRANSACTIONID,
      RTLRPT.LINENUM AS LINENUM,
      RTLRPT.AFFILIATION AS AFFILIATION,
      RTLRPT.LOYALTYTIER AS LOYALTYTIER,
      RTLRPT.CARDNUMBER AS CARDNUMBER,
      RTLRPT.CUSTACCOUNT AS CUSTACCOUNT,
      RTLRPT.ENTRYDATE AS ENTRYDATE,
      RTLRPT.ENTRYTIME AS ENTRYTIME,
      RTLRPT.ENTRYTYPE AS ENTRYTYPE,
      RTLRPT.EXPIRATIONDATE AS EXPIRATIONDATE,
      RTLRPT.REWARDPOINT AS REWARDPOINT,
      RTLRPT.REWARDPOINTAMOUNTQTY AS REWARDPOINTAMOUNTQTY,
      RLRP.REWARDPOINTID AS REWARDPOINTID,
      RLRP.REWARDPOINTTYPE AS REWARDPOINTTYPE,
      RLRP.REWARDPOINTCURRENCY AS REWARDPOINTCURRENCY,
      RLRP.REDEEMABLE AS REWARDPOINTREDEEMABLE
    FROM [ax].RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS RTLRPT
INNER JOIN [ax].RETAILLOYALTYREWARDPOINT RLRP
ON RLRP.RECID = RTLRPT.REWARDPOINT
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].GETEMPLOYEESBYSTOREVIEW
PRINT N'Creating view [crt].GETEMPLOYEESBYSTOREVIEW';

GO
IF OBJECT_ID(N'[crt].GETEMPLOYEESBYSTOREVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].GETEMPLOYEESBYSTOREVIEW
GO

CREATE VIEW [crt].GETEMPLOYEESBYSTOREVIEW AS
(
SELECT 
staff.STAFFID AS STAFFID,
party.NAME AS NAME,
storeAddress.STORERECID AS STOREID,
staff.IMAGE
FROM [ax].RETAILSTAFFTABLE staff
INNER JOIN [ax].HCMWORKER worker ON staff.STAFFID = worker.PERSONNELNUMBER
INNER JOIN [ax].DIRPARTYTABLE party ON worker.PERSON = party.RECID
INNER JOIN [ax].DIRADDRESSBOOKPARTY addressBookParty ON party.RECID = addressBookParty.PARTY
INNER JOIN [ax].RETAILSTOREADDRESSBOOK storeAddress ON addressBookParty.ADDRESSBOOK = storeAddress.ADDRESSBOOK
GROUP BY storeAddress.STORERECID, staff.STAFFID, party.NAME, staff.IMAGE
)


GO
PRINT N'Finished creating view [crt].GETEMPLOYEESBYSTOREVIEW'
GO
-- End creating view [crt].GETEMPLOYEESBYSTOREVIEW


GRANT SELECT ON [crt].GETEMPLOYEESBYSTOREVIEW TO [UsersRole];
GO

-- Creating view [crt].[RETAILSTORETABLEINDIAVIEW]
PRINT N'Creating view [crt].[RETAILSTORETABLEINDIAVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILSTORETABLEINDIAVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILSTORETABLEINDIAVIEW]
GO

CREATE VIEW [crt].[RETAILSTORETABLEINDIAVIEW] AS
(
SELECT
rstIndia.[RECID],
rstIndia.[RETAILSTORETABLE] AS [CHANNELID],
rstIndia.[SALESTAXFORMTYPES],
rstIndia.[TAXDETAILSTYPE],
rstIndia.[SHOWTAXONTAX]
FROM [ax].RETAILSTORETABLE_IN rstIndia
)


GO
PRINT N'Finished creating view [crt].[RETAILSTORETABLEINDIAVIEW]'
GO
-- End creating view [crt].[RETAILSTORETABLEINDIAVIEW]


GRANT SELECT ON [crt].[RETAILSTORETABLEINDIAVIEW] TO [UsersRole];
GO

-- Creating view [crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW
PRINT N'Creating view [crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW';

GO
IF OBJECT_ID(N'[crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW', N'V') IS NOT NULL
    DROP VIEW [crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW
GO

CREATE VIEW [crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW AS
(
SELECT
rtttIndia.[TAXITEMGROUP],
rtttIndia.[TAXPERCENTAGE],
rtttIndia.[TAXCOMPONENT],
rtttIndia.[TAXBASIS],
rtttIndia.[TAXISINCLUDEDINPRICE],
rtttIndia.[TAXFORMULA],
rtttIndia.[TAXISEXEMPT],
rtttIndia.[ISTAXONTAX],
rtttIndia.[TERMINALID],
rtttIndia.[TRANSACTIONID],
rtttIndia.[STOREID],
rtttIndia.[SALELINENUM],
rtttIndia.[TAXCODE],
rttt.[AMOUNT] AS [TAXAMOUNT],
rttt.[CHANNEL] AS [CHANNELID]
FROM [ax].RETAILTRANSACTIONTAXTRANS_IN rtttIndia
INNER JOIN [ax].RETAILTRANSACTIONTAXTRANS rttt 
ON rttt.CHANNEL = rtttIndia.CHANNEL 
AND rttt.TAXCODE = rtttIndia.TAXCODE
AND rttt.SALELINENUM = rtttIndia.SALELINENUM
AND rttt.TRANSACTIONID = rtttIndia.TRANSACTIONID
AND rttt.STOREID = rtttIndia.STOREID
AND rttt.TERMINALID = rtttIndia.TERMINALID
)


GO
PRINT N'Finished creating view [crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW'
GO
-- End creating view [crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW


GRANT SELECT ON [crt].RETAILTRANSACTIONTAXTRANSINDIAVIEW TO [UsersRole];
GO

-- Creating view [crt].[TAXCOMPONENTTABLEINDIAVIEW]
PRINT N'Creating view [crt].[TAXCOMPONENTTABLEINDIAVIEW]';

GO
IF OBJECT_ID(N'[crt].[TAXCOMPONENTTABLEINDIAVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TAXCOMPONENTTABLEINDIAVIEW]
GO

CREATE VIEW [crt].[TAXCOMPONENTTABLEINDIAVIEW] AS
(
SELECT
tctIndia.[RECID],
tctIndia.[COMPONENT],
tctIndia.[TAXTYPE],
tctIndia.[DATAAREAID],
tt.[TAXCODE],
rct.[RECID] as [CHANNELID]
FROM [ax].TAXCOMPONENTTABLE_IN tctIndia
INNER JOIN [ax].TAXTABLE tt ON tt.TAXCOMPONENTTABLE_IN = tctIndia.RECID AND tctIndia.DATAAREAID = tt.DATAAREAID
INNER JOIN [ax].RETAILCHANNELTABLE rct on rct.INVENTLOCATIONDATAAREAID = tctIndia.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[TAXCOMPONENTTABLEINDIAVIEW]'
GO
-- End creating view [crt].[TAXCOMPONENTTABLEINDIAVIEW]


GRANT SELECT ON [crt].[TAXCOMPONENTTABLEINDIAVIEW] TO [UsersRole];
GO

-- Creating view [crt].[TAXINFORMATIONINDIAVIEW]
PRINT N'Creating view [crt].[TAXINFORMATIONINDIAVIEW]';

GO
IF OBJECT_ID(N'[crt].[TAXINFORMATIONINDIAVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TAXINFORMATIONINDIAVIEW]
GO

CREATE VIEW [crt].[TAXINFORMATIONINDIAVIEW] AS
(
SELECT
tiIndia.[RECID],
tiIndia.[ECCNUMBER],
tiIndia.[ISPRIMARY],
tiIndia.[REGISTRATIONLOCATION],
tiIndia.[STCREGISTRATIONNUMBERTABLE],
tiIndia.[TIN]
FROM [ax].TAXINFORMATION_IN tiIndia
)


GO
PRINT N'Finished creating view [crt].[TAXINFORMATIONINDIAVIEW]'
GO
-- End creating view [crt].[TAXINFORMATIONINDIAVIEW]


GRANT SELECT ON [crt].[TAXINFORMATIONINDIAVIEW] TO [UsersRole];
GO

-- Creating view [crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW]
PRINT N'Creating view [crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW]';

GO
IF OBJECT_ID(N'[crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW]
GO

CREATE VIEW [crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW] AS
(
SELECT
tileIndia.[RECID],
tileIndia.[LEGALENTITY],
tileIndia.[PANNUMBER] AS [COMPANYPERMANENTACCOUNTNUMBER],
rct.[RECID] AS [CHANNELID]
FROM [ax].TAXINFORMATIONLEGALENTITY_IN tileIndia
INNER JOIN [ax].COMPANYINFO ci ON ci.RECID = tileIndia.LEGALENTITY
INNER JOIN [ax].RETAILCHANNELTABLE rct ON rct.INVENTLOCATIONDATAAREAID = tileIndia.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW]'
GO
-- End creating view [crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW]


GRANT SELECT ON [crt].[TAXINFORMATIONLEGALENTITIESINDIAVIEW] TO [UsersRole];
GO

-- Creating view [crt].[TAXREGISTRATIONNUMBERSINDIAVIEW]
PRINT N'Creating view [crt].[TAXREGISTRATIONNUMBERSINDIAVIEW]';

GO
IF OBJECT_ID(N'[crt].[TAXREGISTRATIONNUMBERSINDIAVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TAXREGISTRATIONNUMBERSINDIAVIEW]
GO

CREATE VIEW [crt].[TAXREGISTRATIONNUMBERSINDIAVIEW] AS
(
SELECT
trnIndia.[RECID],
trnIndia.[REGISTRATIONNUMBER]
FROM [ax].TAXREGISTRATIONNUMBERS_IN trnIndia
)


GO
PRINT N'Finished creating view [crt].[TAXREGISTRATIONNUMBERSINDIAVIEW]'
GO
-- End creating view [crt].[TAXREGISTRATIONNUMBERSINDIAVIEW]


GRANT SELECT ON [crt].[TAXREGISTRATIONNUMBERSINDIAVIEW] TO [UsersRole];
GO

-- Creating view [crt].[PRODUCTRULESVIEW]
PRINT N'Creating view [crt].[PRODUCTRULESVIEW]';

GO
IF OBJECT_ID(N'[crt].[PRODUCTRULESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PRODUCTRULESVIEW]
GO

CREATE VIEW [crt].[PRODUCTRULESVIEW] AS
(
    SELECT
        it.PRODUCT AS 'PRODUCTID',
        rit.BLOCKEDONPOS,
        rit.DATEBLOCKED,
        rit.DATETOACTIVATEITEM,
        rit.DATETOBEBLOCKED,
        rit.KEYINGINPRICE,
        rit.KEYINGINQTY,
        rit.MUSTKEYINCOMMENT,
        rit.QTYBECOMESNEGATIVE,
        rit.SCALEITEM,
        rit.ZEROPRICEVALID,
        CASE
            WHEN siv.PRODUCTID IS NULL THEN 0
            ELSE 1
        END AS ISSERIALIZED,
        itm.UNITID AS 'DEFAULTUNITOFMEASURE',
        rit.DATAAREAID
    FROM [ax].[RETAILINVENTTABLE] rit
    INNER JOIN [ax].INVENTTABLE it ON it.ITEMID = rit.ITEMID AND it.DATAAREAID = rit.DATAAREAID
    LEFT OUTER JOIN [ax].[INVENTTABLEMODULE] itm ON itm.ITEMID = rit.ITEMID AND itm.MODULETYPE = 2 AND itm.DATAAREAID = rit.DATAAREAID -- 2 = Sales
    LEFT OUTER JOIN [crt].SERIALIZEDITEMSVIEW siv ON siv.ITEMID = rit.ITEMID AND siv.ITEMDATAAREAID = rit.DATAAREAID
)


GO
PRINT N'Finished creating view [crt].[PRODUCTRULESVIEW]'
GO
-- End creating view [crt].[PRODUCTRULESVIEW]


GRANT SELECT ON [crt].[PRODUCTRULESVIEW] TO [UsersRole];
GO

GRANT SELECT ON [crt].[PRODUCTRULESVIEW] TO [PublishersRole];
GO

-- Creating view [crt].[RETAILIMAGESVIEW]
PRINT N'Creating view [crt].[RETAILIMAGESVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILIMAGESVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILIMAGESVIEW]
GO

/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
    [crt].[RETAILIMAGESVIEW] creates a view about retail images.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

CREATE VIEW [crt].[RETAILIMAGESVIEW] AS
(
  SELECT
    ri.[RECID],
    ri.[PICTURE],
    ri.[PICTUREID]
  FROM [ax].RETAILIMAGES ri
);


GO
PRINT N'Finished creating view [crt].[RETAILIMAGESVIEW]'
GO
-- End creating view [crt].[RETAILIMAGESVIEW]


GRANT SELECT ON [crt].[RETAILIMAGESVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONMARKUPTRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONMARKUPTRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONMARKUPTRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONMARKUPTRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONMARKUPTRANSVIEW] AS
(
    SELECT
        MT.CURRENCYCODE
        ,MT.MARKUPCODE
        ,MT.MARKUPLINENUM
        ,MT.SALELINENUM
        ,MT.STORE
        ,MT.TAXGROUP
        ,MT.TAXITEMGROUP as ITEMTAXGROUPID
        ,MT.TERMINALID
        ,MT.TRANSACTIONID
        ,MT.VALUE
        ,MT.METHOD
        ,MT.CALCULATEDAMOUNT
,MT.TAXAMOUNT
,MT.TAXAMOUNTINCLUSIVE
,MT.TAXAMOUNTEXCLUSIVE
        ,MT.DATAAREAID
    FROM [ax].RETAILTRANSACTIONMARKUPTRANS MT
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONMARKUPTRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONMARKUPTRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONMARKUPTRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[PICKINGLISTLINEVIEW]
PRINT N'Creating view [crt].[PICKINGLISTLINEVIEW]';

GO
IF OBJECT_ID(N'[crt].[PICKINGLISTLINEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PICKINGLISTLINEVIEW]
GO

CREATE VIEW [crt].[PICKINGLISTLINEVIEW] AS
(
    SELECT
        pll.[RECID],
        pll.[ORDERID],
        pll.[ITEMID],
        pll.[ITEMNAME],
        pll.[INVENTDIMID],
        pll.[PURCHASERECEIVEDNOW],
        pll.[INVENTBATCHID],
        pll.[INVENTSITEID],
        pll.[INVENTLOCATIONID],
        pll.[CONFIGID],
        pll.[INVENTSERIALID],
        pll.[INVENTSIZEID],
        pll.[INVENTCOLORID],
        pll.[INVENTSTYLEID],
        pll.[DELIVERYMETHOD]
    FROM [crt].[PICKINGLISTLINE] pll
)


GO
PRINT N'Finished creating view [crt].[PICKINGLISTLINEVIEW]'
GO
-- End creating view [crt].[PICKINGLISTLINEVIEW]


GRANT SELECT ON [crt].[PICKINGLISTLINEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[PURCHASEORDERLINEVIEW]
PRINT N'Creating view [crt].[PURCHASEORDERLINEVIEW]';

GO
IF OBJECT_ID(N'[crt].[PURCHASEORDERLINEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[PURCHASEORDERLINEVIEW]
GO

CREATE VIEW [crt].[PURCHASEORDERLINEVIEW] AS
(
    SELECT
        pol.[RECID],
        pol.[ORDERID],
        pol.[LINERECEIPTNUMBER],
        pol.[ITEMID],
        pol.[ITEMNAME],
        pol.[INVENTDIMID],
        pol.[QUANTITYORDERED],
        pol.[PURCHASEQUANTITY],
        pol.[PURCHASEUNIT],
        pol.[PURCHASERECEIVED],
        pol.[PURCHASERECEIVEDNOW],
        pol.[INVENTBATCHID],
        pol.[INVENTSITEID],
        pol.[INVENTLOCATIONID],
        pol.[CONFIGID],
        pol.[INVENTSERIALID],
        pol.[INVENTSIZEID],
        pol.[INVENTCOLORID],
        pol.[INVENTSTYLEID],
        pol.[RECEIPTDATE],
        pol.[DELIVERYMETHOD]
    FROM [crt].[PURCHASEORDERLINE] pol
)


GO
PRINT N'Finished creating view [crt].[PURCHASEORDERLINEVIEW]'
GO
-- End creating view [crt].[PURCHASEORDERLINEVIEW]


GRANT SELECT ON [crt].[PURCHASEORDERLINEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[TRANSFERORDERLINEVIEW]
PRINT N'Creating view [crt].[TRANSFERORDERLINEVIEW]';

GO
IF OBJECT_ID(N'[crt].[TRANSFERORDERLINEVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[TRANSFERORDERLINEVIEW]
GO

CREATE VIEW [crt].[TRANSFERORDERLINEVIEW] AS
(
    SELECT
        tol.[RECID],
        tol.[ORDERID],
        tol.[LINERECEIPTNUMBER],
        tol.[ITEMID],
        tol.[ITEMNAME],
        tol.[INVENTDIMID],
        tol.[QUANTITYTRANSFERRED],
        tol.[QUANTITYSHIPPED],
        tol.[QUANTITYRECEIVED],
        tol.[QUANTITYSHIPNOW],
        tol.[QUANTITYRECEIVENOW],
        tol.[QUANTITYREMAINSHIP],
        tol.[QUANTITYREMAINRECEIVE],
        tol.[PURCHASEUNIT],
        tol.[INVENTBATCHID],
        tol.[INVENTSITEID],
        tol.[INVENTLOCATIONID],
        tol.[CONFIGID],
        tol.[INVENTSERIALID],
        tol.[INVENTSIZEID],
        tol.[INVENTCOLORID],
        tol.[INVENTSTYLEID],
        tol.[DELIVERYMETHOD]
    FROM [crt].[TRANSFERORDERLINE] tol
)


GO
PRINT N'Finished creating view [crt].[TRANSFERORDERLINEVIEW]'
GO
-- End creating view [crt].[TRANSFERORDERLINEVIEW]


GRANT SELECT ON [crt].[TRANSFERORDERLINEVIEW] TO [UsersRole];
GO

-- Creating view [crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW]
PRINT N'Creating view [crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW]';

GO
IF OBJECT_ID(N'[crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW]
GO

CREATE VIEW [crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW] AS
(
    SELECT
        IT.STOREID AS 'STORE'
        ,IT.TERMINALID AS 'TERMINALID'
        ,IT.TRANSACTIONID AS 'TRANSACTIONID'
        ,IT.LINENUM AS 'LINENUM'
        ,IT.INVOICEID AS 'INVOICEID'
        ,IT.AMOUNTCUR AS 'INVOICEAMOUNT'
        ,IT.INVOICEID AS 'COMMENT'
        ,IT.TRANSACTIONSTATUS as 'TRANSACTIONSTATUS'
    FROM [ax].RETAILTRANSACTIONORDERINVOICETRANS IT
)


GO
PRINT N'Finished creating view [crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW]'
GO
-- End creating view [crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW]


GRANT SELECT ON [crt].[RETAILTRANSACTIONORDERINVOICETRANSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[CUSTOMERAFFILIATIONSVIEW]
PRINT N'Creating view [crt].[CUSTOMERAFFILIATIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[CUSTOMERAFFILIATIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[CUSTOMERAFFILIATIONSVIEW]
GO

CREATE VIEW [crt].[CUSTOMERAFFILIATIONSVIEW] AS
(
    SELECT
        rca.RECID,
        rca.CUSTACCOUNTNUM,
        rca.RETAILAFFILIATIONID,
        ra.NAME,
        rat.DESCRIPTION,
rca.DATAAREAID,
rat.LANGUAGEID
    FROM [ax].RETAILCUSTAFFILIATION rca
    INNER JOIN [ax].RETAILAFFILIATION ra ON ra.RECID = rca.RETAILAFFILIATIONID
LEFT JOIN [ax].RETAILAFFILIATIONTRANSLATION rat ON rat.AFFILIATION = ra.RECID
)


GO
PRINT N'Finished creating view [crt].[CUSTOMERAFFILIATIONSVIEW]'
GO
-- End creating view [crt].[CUSTOMERAFFILIATIONSVIEW]


GRANT SELECT ON [crt].[CUSTOMERAFFILIATIONSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[DROPANDDECLARETENDERSVIEW]
PRINT N'Creating view [crt].[DROPANDDECLARETENDERSVIEW]';

GO
IF OBJECT_ID(N'[crt].[DROPANDDECLARETENDERSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[DROPANDDECLARETENDERSVIEW]
GO

CREATE VIEW [crt].[DROPANDDECLARETENDERSVIEW] AS
(
SELECT 
rttdt.TRANSACTIONID,
rttdt.LINENUM,
rttdt.AMOUNTTENDERED AS AMOUNT,
rttdt.AMOUNTCUR AS FOREIGNCURRENCYAMOUNT,
rttdt.CURRENCY,
NULL AS BANKBAGNUMBER,
rttdt.EXCHRATEMST,
rttdt.AMOUNTMST,
rttdt.TENDERTYPE,
rttdt.EXCHRATE
FROM ax.[RETAILTRANSACTIONTENDERDECLARATIONTRANS] rttdt
UNION
SELECT 
rtbtt.TRANSACTIONID,
rtbtt.LINENUM,
rtbtt.AMOUNTTENDERED AS AMOUNT,
rtbtt.AMOUNTCUR AS FOREIGNCURRENCYAMOUNT,
rtbtt.CURRENCY,
rtbtt.BANKBAGNO AS BANKBAGNUMBER,
rtbtt.EXCHRATEMST,
rtbtt.AMOUNTMST,
rtbtt.TENDERTYPE,
rtbtt.EXCHRATE
FROM ax.[RETAILTRANSACTIONBANKEDTENDERTRANS] rtbtt
UNION
SELECT
rtstt.TRANSACTIONID,
rtstt.LINENUM,
rtstt.AMOUNTTENDERED AS AMOUNT,
rtstt.AMOUNTCUR AS FOREIGNCURRENCYAMOUNT,
rtstt.CURRENCY,
NULL AS BANKBAGNUMBER,
rtstt.EXCHRATEMST,
rtstt.AMOUNTMST,
rtstt.TENDERTYPE,
rtstt.EXCHRATE
FROM ax.[RETAILTRANSACTIONSAFETENDERTRANS] rtstt
)


GO
PRINT N'Finished creating view [crt].[DROPANDDECLARETENDERSVIEW]'
GO
-- End creating view [crt].[DROPANDDECLARETENDERSVIEW]


GRANT SELECT ON [crt].[DROPANDDECLARETENDERSVIEW] TO [UsersRole];
GO

-- Creating view [crt].[DROPANDDECLARETRANSACTIONSVIEW]
PRINT N'Creating view [crt].[DROPANDDECLARETRANSACTIONSVIEW]';

GO
IF OBJECT_ID(N'[crt].[DROPANDDECLARETRANSACTIONSVIEW]', N'V') IS NOT NULL
    DROP VIEW [crt].[DROPANDDECLARETRANSACTIONSVIEW]
GO

CREATE VIEW [crt].[DROPANDDECLARETRANSACTIONSVIEW] AS
(
SELECT 
rtt.TYPE,
rtt.TRANSACTIONID,
rtt.OPENDRAWER,
rtt.STORE,
rtt.TERMINAL,
rtt.STAFF,
rtt.BATCHID,
rtt.BATCHTERMINALID,
rtt.DESCRIPTION
FROM ax.[RETAILTRANSACTIONTABLE] rtt
WHERE (rtt.TYPE = 16 OR rtt.TYPE = 17 OR rtt.TYPE = 7) -- SELECT ONLY SAFE DROP, BANK DROP AND DECLARE TENDER TRANSACTIONS
)


GO
PRINT N'Finished creating view [crt].[DROPANDDECLARETRANSACTIONSVIEW]'
GO
-- End creating view [crt].[DROPANDDECLARETRANSACTIONSVIEW]


GRANT SELECT ON [crt].[DROPANDDECLARETRANSACTIONSVIEW] TO [UsersRole];
GO
DECLARE @db_name                        NVARCHAR(128);
DECLARE @is_change_tracking_enabled     BIT;
DECLARE @is_retailListing_tracked       BIT;
DECLARE @i_Error                        INT;
DECLARE @is_delete_trigger_found        BIT;
DECLARE @allow_snapshot_isolation       NVARCHAR;
DECLARE @read_committed_snapshot        BIT;

-- Create Delete trigger on RetailListing to tombstone deleted records

SET @is_delete_trigger_found = (SELECT 1 FROM sys.triggers WHERE name = 'RETAILLISTING_DELETETRIGGER');

SET @db_name = (SELECT DB_NAME());

-- Enable snapshot isolation on database
-- These ALTERs do not fail even if run multiple times

SELECT @allow_snapshot_isolation = snapshot_isolation_state_desc,
       @read_committed_snapshot = is_read_committed_snapshot_on
FROM sys.databases WHERE name = N''' + @db_name + N''' and (snapshot_isolation_state_desc = 'ON' OR is_read_committed_snapshot_on = '1')

IF (coalesce(@allow_snapshot_isolation, 'OFF') = 'OFF')
    BEGIN
        EXEC('ALTER DATABASE [' + @db_name + '] SET ALLOW_SNAPSHOT_ISOLATION ON');
        SELECT @i_Error = @@ERROR;

        IF @i_Error <> 0
            BEGIN
                RAISERROR ('Error enabling snapshot isolation on the database', 16, 1);
            END
        ELSE
            BEGIN
                -- Use Read Committed snapshot
                IF (coalesce(@read_committed_snapshot, 0) = 0)
                    BEGIN
                        EXEC('ALTER DATABASE [' + @db_name + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE');
                        EXEC('ALTER DATABASE [' + @db_name + '] SET READ_COMMITTED_SNAPSHOT ON');
                        EXEC('ALTER DATABASE [' + @db_name + '] SET MULTI_USER');

                        SELECT @i_Error = @@ERROR;

                        IF @i_Error <> 0
                            BEGIN
                                RAISERROR ('Error enabling read committed snapshot on the database', 16, 1);
                            END
                    END
            END
    END
 /******************************************************************************
  File:        utlPopDBErrorFunctions.sql
  Purpose:     Populate DB Error functions

  History:
  Who       When        What
  --------  ----------  ------------------------------------------------------
  sanson     7/25/2009  Created
  xiaoli     3/12/2012  Ported to CRT
******************************************************************************/

print '******************************************************************************';
if object_id(N'[crt].create_errorcodes_fn',N'P') is not null
begin
    drop procedure [crt].create_errorcodes_fn;
end;
go

--create temporary function creator procedure
create procedure [crt].create_errorcodes_fn 
     @vc_error_name varchar(50)
    ,@i_error_code int
as
begin
    declare @vc_function_name   varchar(73); --50 + 16 + length('[crt].fn_')
    declare @vc_function_type   varchar(3);
    declare @i_Error            int;
    declare @vc_error_code      varchar(16);
    
    set @vc_function_type = 'fn';
    set @vc_function_name = '[crt].fn_' + ltrim (rtrim (@vc_error_name));
    set @vc_error_code = cast(@i_error_code as varchar(16));
    
    if object_id (@vc_function_name, @vc_function_type) is not null
    begin
        print 'altering function ' + @vc_function_name + '';
        exec('alter function '+ @vc_function_name + ' () returns int as begin return '+ @vc_error_code + ' end;');
        select @i_Error = @@ERROR;
        if @i_Error <> 0
        begin
            raiserror
            (   
                'Error in script',
                16, -- Severity
                1 -- State
            ); --[sanson: removing, sqlAzure does not allow] with log;
        end;
    end;
    else
    begin
        print 'creating function ' + @vc_function_name;
        exec ('create function '   + @vc_function_name + ' () returns int as begin return '+ @vc_error_code + ' end;');
        exec ('GRANT EXECUTE ON '  + @vc_function_name + ' TO [UsersRole]');
        select @i_Error = @@ERROR;
        if @i_Error <> 0
        begin
            raiserror
            (   
                'Error in script',
                16, -- Severity
                1 -- State
            ); --[sanson: removing, sqlAzure does not allow] with log;
        end;
    end;
end;
go 

-------------------------------------------
--- BEGIN ERROR CODE FUNCTION CREATION ----
-------------------------------------------

declare @vc_ErrorName  varchar(50);
declare @i_ErrorCode  int;
declare @i_BaseErrorCode int;

-- Pick 100000 to not overlap with ex POS error codes
set @i_BaseErrorCode = 100000; --make this whatever the lower range is that we can return.

--success error code
set @vc_ErrorName = 'kSuccess';
set @i_ErrorCode = 0; 
exec [crt].create_errorcodes_fn 
     @vc_error_name = @vc_ErrorName
    ,@i_error_code = @i_ErrorCode;

--generic error code, bug if ever returned.
set @vc_ErrorName = 'kErrorDbCriticalError';
set @i_ErrorCode = @i_BaseErrorCode + 1;
exec [crt].create_errorcodes_fn 
     @vc_error_name = @vc_ErrorName
    ,@i_error_code = @i_ErrorCode;

--item out of stock error   
set @vc_ErrorName = 'kErrorDbItemOutOfStock';
set @i_ErrorCode = @i_BaseErrorCode + 2;
exec [crt].create_errorcodes_fn 
     @vc_error_name = @vc_ErrorName
    ,@i_error_code = @i_ErrorCode;

--authorization error   
set @vc_ErrorName = 'kErrorDbAuthorizationError';
set @i_ErrorCode = @i_BaseErrorCode + 3;
exec [crt].create_errorcodes_fn 
     @vc_error_name = @vc_ErrorName
    ,@i_error_code = @i_ErrorCode;

--version mismatch error   
set @vc_ErrorName = 'kErrorVersionMismatchError';
set @i_ErrorCode = @i_BaseErrorCode + 4;
exec [crt].create_errorcodes_fn 
     @vc_error_name = @vc_ErrorName
    ,@i_error_code = @i_ErrorCode;

GO

drop procedure [crt].create_errorcodes_fn
go
print '*********** finished running ' + db_name() + ' errorcodes creation ********************'

-- Creating table function [crt].[GETNEARBYSTORESFUNCTION]
PRINT N'Creating table function [crt].[GETNEARBYSTORESFUNCTION]';

GO
IF OBJECT_ID(N'[crt].[GETNEARBYSTORESFUNCTION]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETNEARBYSTORESFUNCTION] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETNEARBYSTORESFUNCTION].'
GO


ALTER FUNCTION [crt].[GETNEARBYSTORESFUNCTION]
(
    @bi_ChannelId       BIGINT,
    @f_Latitude         FLOAT,
    @f_Longitude        FLOAT,
    @f_SearchDistance   FLOAT,
    @f_UnitConversion   FLOAT
)
RETURNS @GETNEARBYSTORESRESULT TABLE
(
    [DISTANCE] [FLOAT] NOT NULL,
    [STORENUMBER] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](100) NOT NULL,
    [CHANNELID] [bigint] NOT NULL,
    [INVENTLOCATION] [nvarchar](10) NOT NULL,
    [GEOLOCATION] [geography] NOT NULL,
    [ADDRESS] [nvarchar](250) NOT NULL,
    [COUNTRYREGIONID] [nvarchar](10) NOT NULL,
    [ZIPCODE] [nvarchar](10) NOT NULL,
    [STATE] [nvarchar](10) NOT NULL,
    [COUNTY] [nvarchar](10) NOT NULL,
    [CITY] [nvarchar](60) NOT NULL,
    [STREET] [nvarchar](250) NOT NULL,
    [LATITUDE] [numeric](32, 16) NOT NULL,
    [LONGITUDE] [numeric](32, 16) NOT NULL,
    [STREETNUMBER] [nvarchar](20) NOT NULL,
    [BUILDINGCOMPLIMENT] [nvarchar](60) NOT NULL,
    [POSTBOX] [nvarchar](20) NOT NULL,
    [CITYRECID] [bigint] NOT NULL,
    [DISTRICT] [bigint] NOT NULL,
    [LOCATION] [bigint] NOT NULL,
    [ZIPCODERECID] [bigint] NOT NULL,
    [DISTRICTNAME] [nvarchar](60) NOT NULL,
    [MODIFIEDDATETIME] [datetime] NOT NULL,
    [RECID] [bigint] NOT NULL,
    [POSTALADDRESSRECID] [bigint] NOT NULL,
    [ELECTRONICADDRESSLOCATIONRECID] [bigint] NULL,
    [ELECTRONICADDRESSDESCRIPTION] [nvarchar](60) DEFAULT(''),
    [ELECTRONICADDRESSLOCATOR] [nvarchar](255) DEFAULT(''),
    [ELECTRONICADDRESSTYPE] [int] DEFAULT(0),
    [OPENFROM] [int] DEFAULT(0),
    [OPENTO] [int] DEFAULT(0)
)
AS
BEGIN
    DECLARE @geo_CenterGeolocation geography;

    -- Retrieve the data area for the current channel identifier.
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId

    DECLARE @STORES TABLE(CHANNELID bigint NOT NULL PRIMARY KEY);

    INSERT INTO @STORES(CHANNELID)
    SELECT DISTINCT STORE
    FROM [ax].RETAILSTORELOCATORGROUPMEMBER rslgm
    INNER JOIN [ax].RETAILSTORELOCATORGROUP rslg ON rslg.RECID = rslgm.LOCATORGROUP
    INNER JOIN [ax].RETAILSTORELOCATORGROUPOWNER rslgo ON rslgo.LOCATORGROUP = rslg.RECID
WHERE rslgo.CHANNEL = @bi_ChannelId

    -- 4326 maps to the WGS 84 spatial reference system. Use link to see more info.
    -- https://msdn.microsoft.com/library/bb964707.aspx
    SET @geo_CenterGeolocation = geography::STGeomFromText('POINT(' + CONVERT(VARCHAR(100), @f_Longitude) + ' ' +  CONVERT(VARCHAR(100), @f_Latitude) + ')', 4326)

    INSERT @GETNEARBYSTORESRESULT
    SELECT
        (sv.[GEOLOCATION].STDistance(@geo_CenterGeolocation)) / @f_UnitConversion AS DISTANCE
        ,sv.[STORENUMBER]
        ,sv.[STORENAME]
        ,sv.[CHANNELID]
        ,sv.[INVENTLOCATION]
        ,sv.[GEOLOCATION]
        ,sv.[STOREADDRESS]
        ,sv.[COUNTRYREGIONID]
        ,sv.[ZIPCODE]
        ,sv.[STATE]
        ,sv.[COUNTY]
        ,sv.[CITY]
        ,sv.[STREET]
        ,sv.[LATITUDE]
        ,sv.[LONGITUDE]
        ,sv.[STREETNUMBER]
        ,sv.[BUILDINGCOMPLIMENT]
        ,sv.[POSTBOX]
        ,sv.[CITYRECID]
        ,sv.[DISTRICT]
        ,sv.[LOCATION]
        ,sv.[ZIPCODERECID]
        ,sv.[DISTRICTNAME]
        ,sv.[MODIFIEDDATETIME]
        ,sv.[RECID]
        ,sv.[POSTALADDRESSRECID]
        ,sv.[ELECTRONICADDRESSLOCATIONRECID]
        ,sv.[ELECTRONICADDRESSDESCRIPTION]
        ,sv.[ELECTRONICADDRESSLOCATOR]
        ,sv.[ELECTRONICADDRESSTYPE]
        ,sv.[OPENFROM]
        ,sv.[OPENTO]
    FROM crt.STOREVIEW sv
    INNER JOIN @STORES strs ON strs.CHANNELID = sv.CHANNELID
    WHERE
        GEOLOCATION.STDistance(@geo_CenterGeolocation) <= (@f_SearchDistance * @f_UnitConversion)
        AND sv.DATAAREAID = @nvc_DataAreaId
    ORDER BY DISTANCE

    RETURN
END;


GO
PRINT N'Finished creating table function [crt].[GETNEARBYSTORESFUNCTION]'
-- End creating table function [crt].[GETNEARBYSTORESFUNCTION]


GRANT SELECT ON [crt].[GETNEARBYSTORESFUNCTION] TO [UsersRole];
GO

-- Creating scalar function [crt].[GETALLBLANKINVENTDIMID]
PRINT N'Creating scalar function [crt].[GETALLBLANKINVENTDIMID]';

GO
IF OBJECT_ID(N'[crt].[GETALLBLANKINVENTDIMID]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETALLBLANKINVENTDIMID] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETALLBLANKINVENTDIMID].'
GO


-- Get the inventory dimension ID with all blank fields.
ALTER FUNCTION [crt].GETALLBLANKINVENTDIMID ()
RETURNS nvarchar(20)
BEGIN
    DECLARE @INVENTDIMID nvarchar(20);

    SELECT TOP 1 @INVENTDIMID = id.INVENTDIMID
        FROM [ax].INVENTDIM id
        WHERE id.INVENTDIMID IN ('AllBlank', 'AllBlank2') 
            AND id.CONFIGID = ''
            AND id.INVENTBATCHID = ''
            AND id.INVENTCOLORID = ''
            AND id.INVENTLOCATIONID = ''
            AND id.INVENTSERIALID = ''
            AND id.INVENTSITEID = ''
            AND id.INVENTSIZEID = ''
            AND id.INVENTSTYLEID = ''
            AND id.WMSLOCATIONID = ''
            AND id.WMSPALLETID = ''
        ORDER BY id.INVENTDIMID;

    IF @INVENTDIMID IS NULL
    BEGIN
        SELECT TOP 1 @INVENTDIMID = id.INVENTDIMID
        FROM [ax].INVENTDIM id
        WHERE id.CONFIGID = ''
            AND id.INVENTBATCHID = ''
            AND id.INVENTCOLORID = ''
            AND id.INVENTLOCATIONID = ''
            AND id.INVENTSERIALID = ''
            AND id.INVENTSITEID = ''
            AND id.INVENTSIZEID = ''
            AND id.INVENTSTYLEID = ''
            AND id.WMSLOCATIONID = ''
            AND id.WMSPALLETID = ''
        ORDER BY id.INVENTDIMID
    END
            
    RETURN ISNULL(@INVENTDIMID, '');
END


GO
PRINT N'Finished creating scalar function [crt].[GETALLBLANKINVENTDIMID]'
-- End creating scalar function [crt].[GETALLBLANKINVENTDIMID]


GRANT EXECUTE ON [crt].[GETALLBLANKINVENTDIMID] TO [UsersRole];
GO

-- Creating inline table function [crt].[GETUNITOFMEASURECONVERSIONS]
PRINT N'Creating inline table function [crt].[GETUNITOFMEASURECONVERSIONS]';

GO
IF OBJECT_ID(N'[crt].[GETUNITOFMEASURECONVERSIONS]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETUNITOFMEASURECONVERSIONS] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETUNITOFMEASURECONVERSIONS].'
GO


-- Get unit of measure conversions for the collection of specified items.
ALTER FUNCTION [crt].GETUNITOFMEASURECONVERSIONS
(
    @nvc_DataAreaId             NVARCHAR(4),
    @tvp_ItemUnitConversions    [crt].ITEMUNITCONVERSIONTABLETYPE READONLY
)
RETURNS TABLE
RETURN
    SELECT
        u.[ITEMID],
        u.[FROMUNITID],
        u.[TOUNITID],
        u.[FROMUOMSYMBOL],
        u.[TOUOMSYMBOL],
        u.[ISBACKWARD],
        uomc.[RECID],
        uomc.[DENOMINATOR],
        uomc.[FACTOR],
        uomc.[FROMUNITOFMEASURE],
        uomc.[INNEROFFSET],
        uomc.[NUMERATOR],
        uomc.[OUTEROFFSET],
        uomc.[PRODUCT],
        uomc.[ROUNDING],
        uomc.[TOUNITOFMEASURE],
        uomc.[ROWVERSION]
    FROM
    (
        SELECT
            iuc.ITEMID,
            iuc.FROMUNITID,
            iuc.TOUNITID,
            uom_from.SYMBOL AS FROMUOMSYMBOL,
            uom_to.SYMBOL AS TOUOMSYMBOL,
            CASE
                WHEN uomc1.RECID IS NOT NULL THEN 0
                WHEN uomc2.RECID IS NOT NULL THEN 1
                WHEN uomc3.RECID IS NOT NULL THEN 0
                WHEN uomc4.RECID IS NOT NULL THEN 1
            END ISBACKWARD,
            CASE
                WHEN uomc1.RECID IS NOT NULL THEN uomc1.RECID
                WHEN uomc2.RECID IS NOT NULL THEN uomc2.RECID
                WHEN uomc3.RECID IS NOT NULL THEN uomc3.RECID
                WHEN uomc4.RECID IS NOT NULL THEN uomc4.RECID
            END RECID
        FROM @tvp_ItemUnitConversions iuc
        INNER JOIN [ax].UNITOFMEASURE uom_from ON uom_from.SYMBOL = iuc.FROMUNITID
        INNER JOIN [ax].UNITOFMEASURE uom_to ON uom_to.SYMBOL = iuc.TOUNITID
        LEFT JOIN [ax].INVENTTABLE it ON it.ITEMID = iuc.ITEMID AND it.DATAAREAID = @nvc_DataAreaId
        LEFT JOIN [ax].UNITOFMEASURECONVERSION uomc1
            ON uomc1.FROMUNITOFMEASURE = uom_from.RECID
                AND uomc1.TOUNITOFMEASURE = uom_to.RECID
                AND uomc1.PRODUCT = it.PRODUCT
        LEFT JOIN [ax].UNITOFMEASURECONVERSION uomc2
            ON uomc2.FROMUNITOFMEASURE = uom_to.RECID
                AND uomc2.TOUNITOFMEASURE = uom_from.RECID
                AND uomc2.PRODUCT = it.PRODUCT
        LEFT JOIN [ax].UNITOFMEASURECONVERSION uomc3
            ON uomc3.FROMUNITOFMEASURE = uom_from.RECID
                AND uomc3.TOUNITOFMEASURE = uom_to.RECID
                AND uomc3.PRODUCT = 0
        LEFT JOIN [ax].UNITOFMEASURECONVERSION uomc4
            ON uomc4.FROMUNITOFMEASURE = uom_to.RECID
                AND uomc4.TOUNITOFMEASURE = uom_from.RECID
                AND uomc4.PRODUCT = 0
    ) U
    INNER JOIN [ax].UNITOFMEASURECONVERSION uomc ON uomc.RECID = u.RECID


GO
PRINT N'Finished creating inline table function [crt].[GETUNITOFMEASURECONVERSIONS]'
-- End creating inline table function [crt].[GETUNITOFMEASURECONVERSIONS]


GRANT SELECT ON [crt].[GETUNITOFMEASURECONVERSIONS] TO [UsersRole];
GO

-- Creating inline table function [crt].[GETITEMINVENTORYSETTINGS]
PRINT N'Creating inline table function [crt].[GETITEMINVENTORYSETTINGS]';

GO
IF OBJECT_ID(N'[crt].[GETITEMINVENTORYSETTINGS]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETITEMINVENTORYSETTINGS] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETITEMINVENTORYSETTINGS].'
GO


-- Get inventory settings for items based on customer, item and channel setup.
ALTER FUNCTION [crt].GETITEMINVENTORYSETTINGS
(
    @bi_ChannelId               BIGINT,
    @tvp_ItemVariantInventDims  [crt].ITEMVARIANTINVENTDIMTABLETYPE READONLY ,
    @nvc_CustomerAccountNumber  NVARCHAR(20)
)
RETURNS TABLE
RETURN
    SELECT
        IVID.ITEMID
        ,IVID.VARIANTINVENTDIMID
        ,CT.INVENTLOCATION AS CUSTOMERWAREHOUSE
        ,CT.INVENTSITEID AS CUSTOMERSITE
        ,ID_WAREHOUSE.INVENTLOCATIONID AS ITEMWAREHOUSE
        ,ID_SITE.INVENTSITEID AS ITEMSITE
        ,RCT.INVENTLOCATION AS CHANNELWAREHOUSE
        ,IL_CHANNEL.INVENTSITEID AS CHANNELSITE
        ,IISS_WAREHOUSE.MANDATORYINVENTLOCATION AS ISITEMWAREHOUSEMANDATORY
        ,IISS_SITE.MANDATORYINVENTSITE AS ISITEMSITEMANDATORY
    FROM @tvp_ItemVariantInventDims IVID
    JOIN [ax].RETAILCHANNELTABLE CHANNEL ON CHANNEL.RECID = @bi_ChannelId
    LEFT JOIN [ax].INVENTITEMSALESSETUP IISS_SITE ON IISS_SITE.ITEMID = IVID.ITEMID AND IISS_SITE.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID AND IISS_SITE.INVENTDIMID = [crt].GETALLBLANKINVENTDIMID() 
    LEFT JOIN [ax].INVENTDIM ID_SITE ON ID_SITE.INVENTDIMID = IISS_SITE.INVENTDIMIDDEFAULT AND ID_SITE.DATAAREAID = IISS_SITE.DATAAREAID
    LEFT JOIN [ax].INVENTITEMSALESSETUP IISS_WAREHOUSE ON IISS_WAREHOUSE.ITEMID = IVID.ITEMID AND IISS_WAREHOUSE.INVENTDIMID = IISS_SITE.INVENTDIMIDDEFAULT AND IISS_WAREHOUSE.DATAAREAID = IISS_SITE.DATAAREAID
    LEFT JOIN [ax].INVENTDIM ID_WAREHOUSE ON ID_WAREHOUSE.INVENTDIMID = IISS_WAREHOUSE.INVENTDIMIDDEFAULT AND ID_WAREHOUSE.DATAAREAID = IISS_WAREHOUSE.DATAAREAID
    LEFT JOIN [ax].CUSTTABLE CT ON CT.ACCOUNTNUM = @nvc_CustomerAccountNumber AND CT.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID
    LEFT JOIN [ax].RETAILPUBRETAILCHANNELTABLE RCT ON RCT.ORIGINID = @bi_ChannelId
    LEFT JOIN [ax].INVENTLOCATION IL_CHANNEL ON IL_CHANNEL.INVENTLOCATIONID = RCT.INVENTLOCATION AND IL_CHANNEL.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID


GO
PRINT N'Finished creating inline table function [crt].[GETITEMINVENTORYSETTINGS]'
-- End creating inline table function [crt].[GETITEMINVENTORYSETTINGS]


GRANT SELECT ON [crt].[GETITEMINVENTORYSETTINGS] TO [UsersRole];
GO

-- Creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMS]
PRINT N'Creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMS]';

GO
IF OBJECT_ID(N'[crt].[GETITEMAVAILABILITIESBYITEMS]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETITEMAVAILABILITIESBYITEMS] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETITEMAVAILABILITIESBYITEMS].'
GO


-- Get item availabilities by items.
ALTER FUNCTION [crt].GETITEMAVAILABILITIESBYITEMS
(
    @bi_ChannelId               BIGINT,
    @tvp_ItemVariantInventDims  [crt].ITEMVARIANTINVENTDIMTABLETYPE READONLY,
    @nvc_CustomerAccountNumber  NVARCHAR(20)
)
RETURNS TABLE
RETURN
    SELECT
        IAV.[RECID]
        ,IAV.[ITEMID]
        ,IAV.[VARIANTINVENTDIMID]
        ,IAV.[WAREHOUSEINVENTDIMID]
        ,IAV.[INVENTSITEID]
        ,IAV.[INVENTLOCATIONID]
        ,IAV.[AVAILPHYSICAL]
        ,IAV.[UNITID]
        ,CASE
            WHEN IAV.INVENTLOCATIONID = IIS.CUSTOMERWAREHOUSE AND IAV.INVENTLOCATIONID != '' THEN 32
            ELSE 0
        END | CASE
            WHEN IAV.INVENTSITEID = IIS.CUSTOMERSITE AND IAV.INVENTSITEID != '' THEN 16
            ELSE 0
        END | CASE
            WHEN IAV.INVENTLOCATIONID = IIS.ITEMWAREHOUSE AND IAV.INVENTLOCATIONID != '' THEN 8
            ELSE 0
        END | CASE
            WHEN IAV.INVENTSITEID = IIS.ITEMSITE AND IAV.INVENTSITEID != '' THEN 4
            ELSE 0
        END | CASE
            WHEN IAV.INVENTLOCATIONID = IIS.CHANNELWAREHOUSE AND IAV.INVENTLOCATIONID != '' THEN 2
            ELSE 0
        END | CASE
            WHEN IAV.INVENTSITEID = IIS.CHANNELSITE AND IAV.INVENTSITEID != '' THEN 1
            ELSE 0
        END PREFERENCES
    FROM @tvp_ItemVariantInventDims IVI
    JOIN [crt].ITEMAVAILABILITYVIEW IAV ON IAV.ITEMID = IVI.ITEMID AND IAV.VARIANTINVENTDIMID = IVI.VARIANTINVENTDIMID
    LEFT JOIN [crt].GETITEMINVENTORYSETTINGS(@bi_ChannelId, @tvp_ItemVariantInventDims, @nvc_CustomerAccountNumber) IIS ON IIS.ITEMID = IVI.ITEMID AND IIS.VARIANTINVENTDIMID = IVI.VARIANTINVENTDIMID
    WHERE (IIS.ISITEMWAREHOUSEMANDATORY = 1 AND IAV.INVENTLOCATIONID = IIS.ITEMWAREHOUSE)                                                                       -- Mandatory warehouse,
        OR ((IIS.ISITEMWAREHOUSEMANDATORY IS NULL OR IIS.ISITEMWAREHOUSEMANDATORY != 1) AND IIS.ISITEMSITEMANDATORY = 1 AND IAV.INVENTSITEID = IIS.ITEMSITE)    -- or mandatory site,
        OR ((IIS.ISITEMWAREHOUSEMANDATORY IS NULL OR IIS.ISITEMWAREHOUSEMANDATORY != 1) AND (IIS.ISITEMSITEMANDATORY IS NULL OR IIS.ISITEMSITEMANDATORY != 1))  -- or not mandatory


GO
PRINT N'Finished creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMS]'
-- End creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMS]


GRANT SELECT ON [crt].[GETITEMAVAILABILITIESBYITEMS] TO [UsersRole];
GO

-- Creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES]
PRINT N'Creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES]';

GO
IF OBJECT_ID(N'[crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES].'
GO


-- Get item availabilities by requested item quantities.
-- For items with sufficient quantities available in one warehouse, the topmost warehouse is returned, order by preferences descending, then available quantities descending, and recid ascending.
-- Otherwise, at most top n = @i_MaxWarehousesPerItem warehouses are returned, order by available quantities descending, then preferences descending, and recid ascending.
-- Because there is no efficient way of calculating running totals, the function returns cannot return just enough records to fulfill the order.
ALTER FUNCTION [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES]
(
    @bi_ChannelId               BIGINT,
    @tvp_ItemQuantities         [crt].ITEMQUANTITYTABLETYPE READONLY,
    @nvc_CustomerAccountNumber  NVARCHAR(20),
    @i_MaxWarehousesPerItem     INT
)
RETURNS TABLE
RETURN
    WITH ITEM_INVENTORY_SETTINGS AS
    (
        SELECT
            IQ.ITEMID
            ,IQ.VARIANTINVENTDIMID
            ,CT.INVENTLOCATION AS CUSTOMERWAREHOUSE
            ,CT.INVENTSITEID AS CUSTOMERSITE
            ,ID_WAREHOUSE.INVENTLOCATIONID AS ITEMWAREHOUSE
            ,ID_SITE.INVENTSITEID AS ITEMSITE
            ,RCT.INVENTLOCATION AS CHANNELWAREHOUSE
            ,IL_CHANNEL.INVENTSITEID AS CHANNELSITE
            ,IISS_WAREHOUSE.MANDATORYINVENTLOCATION AS ISITEMWAREHOUSEMANDATORY
            ,IISS_SITE.MANDATORYINVENTSITE AS ISITEMSITEMANDATORY
        FROM @tvp_ItemQuantities IQ
        JOIN [ax].RETAILCHANNELTABLE CHANNEL ON CHANNEL.RECID = @bi_ChannelId
        LEFT JOIN [ax].INVENTITEMSALESSETUP IISS_SITE ON IISS_SITE.ITEMID = IQ.ITEMID AND IISS_SITE.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID AND IISS_SITE.INVENTDIMID = [crt].GETALLBLANKINVENTDIMID()
        LEFT JOIN [ax].INVENTDIM ID_SITE ON ID_SITE.INVENTDIMID = IISS_SITE.INVENTDIMIDDEFAULT AND ID_SITE.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID
        LEFT JOIN [ax].INVENTITEMSALESSETUP IISS_WAREHOUSE ON IISS_WAREHOUSE.ITEMID = IQ.ITEMID AND IISS_WAREHOUSE.INVENTDIMID = IISS_SITE.INVENTDIMIDDEFAULT AND IISS_WAREHOUSE.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID
        LEFT JOIN [ax].INVENTDIM ID_WAREHOUSE ON ID_WAREHOUSE.INVENTDIMID = IISS_WAREHOUSE.INVENTDIMIDDEFAULT AND ID_WAREHOUSE.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID
        LEFT JOIN [ax].CUSTTABLE CT ON CT.ACCOUNTNUM = @nvc_CustomerAccountNumber AND CT.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID
        LEFT JOIN [ax].RETAILPUBRETAILCHANNELTABLE RCT ON RCT.ORIGINID = @bi_ChannelId
        LEFT JOIN [ax].INVENTLOCATION IL_CHANNEL ON IL_CHANNEL.INVENTLOCATIONID = RCT.INVENTLOCATION AND IL_CHANNEL.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID
    ),
    ITEM_AVAILABILITIES AS
    (
        SELECT
            IAV.RECID
            ,IAV.ITEMID
            ,IAV.VARIANTINVENTDIMID
            ,IAV.AVAILPHYSICAL
            ,CASE
                WHEN IAV.INVENTLOCATIONID = IIS.CUSTOMERWAREHOUSE AND IAV.INVENTLOCATIONID != '' THEN 32
                ELSE 0
            END | CASE
                WHEN IAV.INVENTSITEID = IIS.CUSTOMERSITE AND IAV.INVENTSITEID != '' THEN 16
                ELSE 0
            END | CASE
                WHEN IAV.INVENTLOCATIONID = IIS.ITEMWAREHOUSE AND IAV.INVENTLOCATIONID != '' THEN 8
                ELSE 0
            END | CASE
                WHEN IAV.INVENTSITEID = IIS.ITEMSITE AND IAV.INVENTSITEID != '' THEN 4
                ELSE 0
            END | CASE
                WHEN IAV.INVENTLOCATIONID = IIS.CHANNELWAREHOUSE AND IAV.INVENTLOCATIONID != '' THEN 2
                ELSE 0
            END | CASE
                WHEN IAV.INVENTSITEID = IIS.CHANNELSITE AND IAV.INVENTSITEID != '' THEN 1
                ELSE 0
            END PREFERENCES
            FROM @tvp_ItemQuantities IQ
            INNER JOIN [crt].ITEMAVAILABILITYVIEW IAV ON IAV.ITEMID = IQ.ITEMID AND IAV.VARIANTINVENTDIMID = IQ.VARIANTINVENTDIMID
            INNER JOIN [ax].RETAILCHANNELTABLE CHANNEL ON CHANNEL.RECID = @bi_ChannelId AND CHANNEL.INVENTLOCATIONDATAAREAID =  IAV.DATAAREAID
            LEFT JOIN ITEM_INVENTORY_SETTINGS IIS ON IIS.ITEMID = IQ.ITEMID AND IIS.VARIANTINVENTDIMID = IQ.VARIANTINVENTDIMID
            WHERE (IIS.ISITEMWAREHOUSEMANDATORY = 1 AND IAV.INVENTLOCATIONID = IIS.ITEMWAREHOUSE)                                                                       -- Mandatory warehouse,
                OR ((IIS.ISITEMWAREHOUSEMANDATORY IS NULL OR IIS.ISITEMWAREHOUSEMANDATORY != 1) AND IIS.ISITEMSITEMANDATORY = 1 AND IAV.INVENTSITEID = IIS.ITEMSITE)    -- or mandatory site,
                OR ((IIS.ISITEMWAREHOUSEMANDATORY IS NULL OR IIS.ISITEMWAREHOUSEMANDATORY != 1) AND (IIS.ISITEMSITEMANDATORY IS NULL OR IIS.ISITEMSITEMANDATORY != 1))  -- or not mandatory
    ),
    SUFFICIENT_QUANTITY_ITEMS AS
    (
        SELECT
            IQ.ITEMID
            ,IQ.VARIANTINVENTDIMID
        FROM @tvp_ItemQuantities IQ
        INNER JOIN ITEM_AVAILABILITIES IA ON IA.ITEMID = IQ.ITEMID AND IA.VARIANTINVENTDIMID = IQ.VARIANTINVENTDIMID
        WHERE IQ.QUANTITY <= IA.AVAILPHYSICAL
        GROUP BY IQ.ITEMID, IQ.VARIANTINVENTDIMID
    ),
    INSUFFICIENT_QUANTITY_ITEMS AS
    (
        SELECT
            IQ.ITEMID
            ,IQ.VARIANTINVENTDIMID
        FROM @tvp_ItemQuantities IQ
        LEFT JOIN SUFFICIENT_QUANTITY_ITEMS SQI ON SQI.ITEMID = IQ.ITEMID AND SQI.VARIANTINVENTDIMID = IQ.VARIANTINVENTDIMID
        WHERE SQI.ITEMID IS NULL    -- Exclude records in SUFFICIENT_QUANTITY_ITEMS set
    ),
    SUFFICIENT_QUANTITY_ITEM_AVAILABILITIES AS
    (
        SELECT
            IA.RECID
            ,IA.ITEMID
            ,IA.VARIANTINVENTDIMID
            ,IA.PREFERENCES
            ,RANK() OVER
            (
                PARTITION BY IA.ITEMID, IA.VARIANTINVENTDIMID

                -- Order by preferences first because there are enough available quantities
                -- Add recid to break ties so that ranks will always be consecutive numbers
                ORDER BY IA.PREFERENCES DESC, IA.AVAILPHYSICAL DESC, IA.RECID
            ) AS RANK
        FROM SUFFICIENT_QUANTITY_ITEMS SQI
        INNER JOIN ITEM_AVAILABILITIES IA ON IA.ITEMID = SQI.ITEMID AND IA.VARIANTINVENTDIMID = SQI.VARIANTINVENTDIMID
    ),
    INSUFFICIENT_QUANTITY_ITEM_AVAILABILITIES AS
    (
        SELECT
            IA.RECID
            ,IA.ITEMID
            ,IA.VARIANTINVENTDIMID
            ,IA.AVAILPHYSICAL
            ,IA.PREFERENCES
            ,RANK() OVER
            (
                PARTITION BY IA.ITEMID, IA.VARIANTINVENTDIMID

                -- Order by quantities first to maximize the chance of fulfilling the order
                -- Add recid to break ties so that ranks will always be consecutive numbers
                ORDER BY IA.AVAILPHYSICAL DESC, IA.PREFERENCES DESC, IA.RECID
            ) AS RANK
        FROM INSUFFICIENT_QUANTITY_ITEMS IQI
        INNER JOIN ITEM_AVAILABILITIES IA ON IA.ITEMID = IQI.ITEMID AND IA.VARIANTINVENTDIMID = IQI.VARIANTINVENTDIMID
    ),
    ASSIGNED_ITEM_AVAILABILITIES AS
    (
        SELECT
            RECID
            ,ITEMID
            ,VARIANTINVENTDIMID
            ,PREFERENCES
        FROM SUFFICIENT_QUANTITY_ITEM_AVAILABILITIES
        WHERE RANK = 1

        UNION ALL

        SELECT
            RECID
            ,ITEMID
            ,VARIANTINVENTDIMID
            ,PREFERENCES
        FROM INSUFFICIENT_QUANTITY_ITEM_AVAILABILITIES
        WHERE RANK <= @i_MaxWarehousesPerItem AND (RANK = 1 OR AVAILPHYSICAL > 0) -- No need to return zero quantity records except for the first one.
    )
    SELECT
        IAV.RECID
        ,IAV.ITEMID
        ,IAV.VARIANTINVENTDIMID
        ,IAV.WAREHOUSEINVENTDIMID
        ,IAV.INVENTSITEID
        ,IAV.INVENTLOCATIONID
        ,IAV.AVAILPHYSICAL
        ,IAV.UNITID
        ,AIA.PREFERENCES
    FROM ASSIGNED_ITEM_AVAILABILITIES AIA
    JOIN [crt].ITEMAVAILABILITYVIEW IAV ON IAV.RECID = AIA.RECID


GO
PRINT N'Finished creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES]'
-- End creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES]


GRANT SELECT ON [crt].[GETITEMAVAILABILITIESBYITEMQUANTITIES] TO [UsersRole];
GO

-- Creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES]
PRINT N'Creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES]';

GO
IF OBJECT_ID(N'[crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES].'
GO


-- Get item availabilities by item warehouses.
ALTER FUNCTION [crt].GETITEMAVAILABILITIESBYITEMWAREHOUSES
(
    @bi_ChannelId               BIGINT,
    @tvp_ItemWarehouses [crt].ITEMWAREHOUSETABLETYPE READONLY
)
RETURNS TABLE
RETURN
    SELECT
        IAV.[RECID]
        ,IAV.[ITEMID]
        ,IAV.[VARIANTINVENTDIMID]
        ,IAV.[WAREHOUSEINVENTDIMID]
        ,IAV.[INVENTSITEID]
        ,IAV.[INVENTLOCATIONID]
        ,IAV.[AVAILPHYSICAL]
        ,IAV.[UNITID]
    FROM @tvp_ItemWarehouses IW
    JOIN [ax].RETAILCHANNELTABLE CHANNEL ON CHANNEL.RECID = @bi_ChannelId
    INNER JOIN [crt].ITEMAVAILABILITYVIEW IAV ON IAV.ITEMID = IW.ITEMID AND IAV.VARIANTINVENTDIMID = IW.VARIANTINVENTDIMID AND IAV.INVENTLOCATIONID = IW.INVENTLOCATIONID AND IAV.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID
    LEFT JOIN [ax].INVENTITEMSALESSETUP IISS_SITE ON IISS_SITE.ITEMID = IW.ITEMID AND IISS_SITE.DATAAREAID = CHANNEL.INVENTLOCATIONDATAAREAID AND IISS_SITE.INVENTDIMID = [crt].GETALLBLANKINVENTDIMID()
    LEFT JOIN [ax].INVENTDIM ID_SITE ON ID_SITE.INVENTDIMID = IISS_SITE.INVENTDIMIDDEFAULT AND ID_SITE.DATAAREAID = IISS_SITE.DATAAREAID
    LEFT JOIN [ax].INVENTITEMSALESSETUP IISS_WAREHOUSE ON IISS_WAREHOUSE.ITEMID = IW.ITEMID AND IISS_WAREHOUSE.INVENTDIMID = IISS_SITE.INVENTDIMIDDEFAULT AND IISS_WAREHOUSE.DATAAREAID = IISS_SITE.DATAAREAID
    LEFT JOIN [ax].INVENTDIM ID_WAREHOUSE ON ID_WAREHOUSE.INVENTDIMID = IISS_WAREHOUSE.INVENTDIMIDDEFAULT AND ID_WAREHOUSE.DATAAREAID = IISS_WAREHOUSE.DATAAREAID
    WHERE (IISS_WAREHOUSE.MANDATORYINVENTLOCATION = 1 AND IAV.INVENTLOCATIONID = ID_WAREHOUSE.INVENTLOCATIONID)                                                                                 -- Mandatory warehouse,
        OR ((IISS_WAREHOUSE.MANDATORYINVENTLOCATION IS NULL OR IISS_WAREHOUSE.MANDATORYINVENTLOCATION != 1) AND IISS_SITE.MANDATORYINVENTSITE = 1 AND IAV.INVENTSITEID = ID_SITE.INVENTSITEID)  -- or mandatory site,
        OR ((IISS_WAREHOUSE.MANDATORYINVENTLOCATION IS NULL OR IISS_WAREHOUSE.MANDATORYINVENTLOCATION != 1) AND (IISS_SITE.MANDATORYINVENTSITE IS NULL OR IISS_SITE.MANDATORYINVENTSITE != 1))  -- or not mandatory


GO
PRINT N'Finished creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES]'
-- End creating inline table function [crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES]


GRANT SELECT ON [crt].[GETITEMAVAILABILITIESBYITEMWAREHOUSES] TO [UsersRole];
GO

-- Creating inline table function [crt].[GETITEMAVAILABLEQUANTITIESBYITEMS]
PRINT N'Creating inline table function [crt].[GETITEMAVAILABLEQUANTITIESBYITEMS]';

GO
IF OBJECT_ID(N'[crt].[GETITEMAVAILABLEQUANTITIESBYITEMS]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETITEMAVAILABLEQUANTITIESBYITEMS] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETITEMAVAILABLEQUANTITIESBYITEMS].'
GO


-- Get item available quantities.
ALTER FUNCTION [crt].GETITEMAVAILABLEQUANTITIESBYITEMS
(
    @bi_ChannelId              BIGINT,
    @tvp_ItemVariantInventDims  [crt].ITEMVARIANTINVENTDIMTABLETYPE READONLY,
    @nvc_CustomerAccountNumber  NVARCHAR(20)
)
RETURNS TABLE
RETURN
    SELECT
        IVI.ITEMID
        ,IVI.VARIANTINVENTDIMID
        ,SUM(IAV.AVAILPHYSICAL) AS AVAILPHYSICAL
        ,MAX(IAV.UNITID) AS UNITID
    FROM @tvp_ItemVariantInventDims IVI
    JOIN [crt].ITEMAVAILABILITYVIEW IAV ON IAV.ITEMID = IVI.ITEMID AND (IVI.VARIANTINVENTDIMID = '' OR IAV.VARIANTINVENTDIMID = IVI.VARIANTINVENTDIMID)
    LEFT JOIN [crt].GETITEMINVENTORYSETTINGS(@bi_ChannelId, @tvp_ItemVariantInventDims, @nvc_CustomerAccountNumber) IIS ON IIS.ITEMID = IVI.ITEMID AND IIS.VARIANTINVENTDIMID = IVI.VARIANTINVENTDIMID
    WHERE (IIS.ISITEMWAREHOUSEMANDATORY = 1 AND IAV.INVENTLOCATIONID = IIS.ITEMWAREHOUSE)                                                                       -- Mandatory warehouse,
        OR ((IIS.ISITEMWAREHOUSEMANDATORY IS NULL OR IIS.ISITEMWAREHOUSEMANDATORY != 1) AND IIS.ISITEMSITEMANDATORY = 1 AND IAV.INVENTSITEID = IIS.ITEMSITE)    -- or mandatory site,
        OR ((IIS.ISITEMWAREHOUSEMANDATORY IS NULL OR IIS.ISITEMWAREHOUSEMANDATORY != 1) AND (IIS.ISITEMSITEMANDATORY IS NULL OR IIS.ISITEMSITEMANDATORY != 1))  -- or not mandatory
    GROUP BY IVI.ITEMID, IVI.VARIANTINVENTDIMID


GO
PRINT N'Finished creating inline table function [crt].[GETITEMAVAILABLEQUANTITIESBYITEMS]'
-- End creating inline table function [crt].[GETITEMAVAILABLEQUANTITIESBYITEMS]


GRANT SELECT ON [crt].[GETITEMAVAILABLEQUANTITIESBYITEMS] TO [UsersRole];
GO

-- Creating scalar function [crt].GETAXTABLEID
PRINT N'Creating scalar function [crt].GETAXTABLEID';

GO
IF OBJECT_ID(N'[crt].GETAXTABLEID', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].GETAXTABLEID () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].GETAXTABLEID.'
GO


ALTER FUNCTION [crt].GETAXTABLEID
(
    @nvc_TableName NVARCHAR(255)
)
RETURNS BIGINT
BEGIN
    IF (@nvc_TableName = 'EcoResDistinctProduct')
        RETURN 3265;

    -- The table is not yet supported.
    RETURN 0;
END


GO
PRINT N'Finished creating scalar function [crt].GETAXTABLEID'
-- End creating scalar function [crt].GETAXTABLEID


GRANT EXECUTE ON [crt].GETAXTABLEID TO [UsersRole];
GO

GRANT EXECUTE ON [crt].GETAXTABLEID TO [PublishersRole];
GO

-- Creating scalar function [crt].GETMAXAXDATE
PRINT N'Creating scalar function [crt].GETMAXAXDATE';

GO
IF OBJECT_ID(N'[crt].GETMAXAXDATE', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].GETMAXAXDATE () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].GETMAXAXDATE.'
GO


ALTER FUNCTION [crt].GETMAXAXDATE 
(
)
RETURNS DATETIME
BEGIN
    DECLARE @MaxAxDate DATETIME;
SET @MaxAxDate = CAST('2154-12-31 23:59:59.000' AS DATETIME);
            
    RETURN @MaxAxDate
END


GO
PRINT N'Finished creating scalar function [crt].GETMAXAXDATE'
-- End creating scalar function [crt].GETMAXAXDATE


GRANT EXECUTE ON [crt].GETMAXAXDATE TO [UsersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION]
PRINT N'Creating inline table function [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTMASTERDIMVALUETRANSLATION]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION].'
GO


-- Gets product master's dimension value translations
ALTER FUNCTION [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION]
(
    @bi_ChannelId       BIGINT
)
RETURNS TABLE
RETURN
    SELECT
erpmdvt.PRODUCTMASTERDIMENSIONVALUE,
erpmdvt.LANGUAGEID,
erpmdvt.NAME
        FROM ax.ECORESPRODUCTMASTERDIMVALUETRANSLATION erpmdvt
JOIN crt.CHANNELLANGUAGESVIEW clv ON clv.CHANNEL = @bi_ChannelId AND clv.LANGUAGEID = erpmdvt.LANGUAGEID


GO
PRINT N'Finished creating inline table function [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION]'
-- End creating inline table function [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION]


GRANT SELECT ON [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTMASTERDIMVALUETRANSLATION] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETTEXTVALUETRANSLATION]
PRINT N'Creating inline table function [crt].[GETTEXTVALUETRANSLATION]';

GO
IF OBJECT_ID(N'[crt].[GETTEXTVALUETRANSLATION]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETTEXTVALUETRANSLATION] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETTEXTVALUETRANSLATION].'
GO


-- Gets channel's text value translations
ALTER FUNCTION [crt].[GETTEXTVALUETRANSLATION]
(
    @bi_ChannelId       BIGINT
)
RETURNS TABLE
RETURN
    SELECT
ertvt.TEXTVALUETABLE AS VALUE,
ertvt.[LANGUAGE],
ertvt.TEXTVALUE AS TRANSLATION
        FROM ax.ECORESTEXTVALUETRANSLATION ertvt
            JOIN crt.CHANNELLANGUAGESVIEW clv ON clv.CHANNEL = @bi_ChannelId AND clv.LANGUAGEID = ertvt.[LANGUAGE]


GO
PRINT N'Finished creating inline table function [crt].[GETTEXTVALUETRANSLATION]'
-- End creating inline table function [crt].[GETTEXTVALUETRANSLATION]


GRANT SELECT ON [crt].[GETTEXTVALUETRANSLATION] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETTEXTVALUETRANSLATION] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETVALUEEXPANDED]
PRINT N'Creating inline table function [crt].[GETVALUEEXPANDED]';

GO
IF OBJECT_ID(N'[crt].[GETVALUEEXPANDED]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETVALUEEXPANDED] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETVALUEEXPANDED].'
GO


-- Gets expanded values
ALTER FUNCTION [crt].[GETVALUEEXPANDED]
(
    @bi_ChannelId       BIGINT
)
RETURNS TABLE
RETURN
    SELECT
        erv.RECID,
        erbv.BOOLEANVALUE,
        ercv.CURRENCYVALUE,
        ercv.CURRENCYCODE,
        erdtv.DATETIMEVALUE,
        erdtv.DATETIMEVALUETZID,
        erfv.FLOATVALUE,
        uom_float.SYMBOL AS FLOATUNITSYMBOL,
        eriv.INTVALUE,
        uom_int.SYMBOL AS INTUNITSYMBOL,
        ertv.TEXTVALUE,
        tvt.LANGUAGE,
        tvt.TRANSLATION
    FROM [ax].ECORESVALUE erv
    LEFT JOIN [ax].ECORESBOOLEANVALUE erbv ON erbv.RECID = erv.RECID
    LEFT JOIN [ax].ECORESCURRENCYVALUE ercv ON ercv.RECID = erv.RECID
    LEFT JOIN [ax].ECORESDATETIMEVALUE erdtv ON erdtv.RECID = erv.RECID
    LEFT JOIN [ax].ECORESFLOATVALUE erfv ON erfv.RECID = erv.RECID
    LEFT JOIN [ax].UNITOFMEASURE uom_float ON uom_float.RECID = erfv.FLOATUNITOFMEASURE
    LEFT JOIN [ax].ECORESINTVALUE eriv ON eriv.RECID = erv.RECID
    LEFT JOIN [ax].UNITOFMEASURE uom_int ON uom_int.RECID = eriv.INTUNITOFMEASURE
    LEFT JOIN [ax].ECORESTEXTVALUE ertv ON ertv.RECID = erv.RECID
    LEFT JOIN [crt].GETTEXTVALUETRANSLATION(@bi_ChannelId) tvt ON tvt.VALUE = ertv.RECID


GO
PRINT N'Finished creating inline table function [crt].[GETVALUEEXPANDED]'
-- End creating inline table function [crt].[GETVALUEEXPANDED]


GRANT SELECT ON [crt].[GETVALUEEXPANDED] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETVALUEEXPANDED] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPUBCATALOG]
PRINT N'Creating inline table function [crt].[GETPUBCATALOG]';

GO
IF OBJECT_ID(N'[crt].[GETPUBCATALOG]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPUBCATALOG] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPUBCATALOG].'
GO


ALTER FUNCTION [crt].[GETPUBCATALOG]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_IsForwardLooking BIT
)
RETURNS TABLE
RETURN
    SELECT
        rpc.ORIGIN AS [CATALOG]
    FROM [ax].RETAILPUBCATALOG rpc
    JOIN [crt].PUBCATALOGCHANNELVIEW pccv ON pccv.[CATALOG] = rpc.ORIGIN AND pccv.CHANNEL = @bi_ChannelId
    WHERE (@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN rpc.PUBLISHEDVALIDFROM AND rpc.PUBLISHEDVALIDTO) 
        OR (@b_IsForwardLooking = 1 AND @dt_ChannelDate <= rpc.PUBLISHEDVALIDTO)


GO
PRINT N'Finished creating inline table function [crt].[GETPUBCATALOG]'
-- End creating inline table function [crt].[GETPUBCATALOG]


GRANT SELECT ON [crt].[GETPUBCATALOG] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPUBCATALOG] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPUBCATALOGCURRENT]
PRINT N'Creating inline table function [crt].[GETPUBCATALOGCURRENT]';

GO
IF OBJECT_ID(N'[crt].[GETPUBCATALOGCURRENT]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPUBCATALOGCURRENT] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPUBCATALOGCURRENT].'
GO


ALTER FUNCTION [crt].[GETPUBCATALOGCURRENT]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE
)
RETURNS TABLE
RETURN
    SELECT
        rpc.ORIGIN AS 'CATALOG',
        pccv.CHANNEL,
        rpc.ENABLESNAPSHOT,
        rpc.PUBLISHEDVALIDFROM AS 'VALIDFROM',
        rpc.PUBLISHEDVALIDTO AS 'VALIDTO',
        rpc.CREATEDDATETIME,
        rpc.MODIFIEDDATETIME,
        rpc.PUBLISHEDDATETIME
    FROM [ax].RETAILPUBCATALOG rpc
    INNER JOIN [crt].PUBCATALOGCHANNELVIEW pccv ON pccv.[CATALOG] = rpc.[ORIGIN]
    WHERE rpc.STATE = 5 -- Published
        AND pccv.CHANNEL = @bi_ChannelId
        AND @dt_ChannelDate BETWEEN rpc.PUBLISHEDVALIDFROM AND rpc.PUBLISHEDVALIDTO


GO
PRINT N'Finished creating inline table function [crt].[GETPUBCATALOGCURRENT]'
-- End creating inline table function [crt].[GETPUBCATALOGCURRENT]


GRANT SELECT ON [crt].[GETPUBCATALOGCURRENT] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPUBCATALOGCURRENT] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPUBCATALOGATTRIBUTEINHERITED]
PRINT N'Creating inline table function [crt].[GETPUBCATALOGATTRIBUTEINHERITED]';

GO
IF OBJECT_ID(N'[crt].[GETPUBCATALOGATTRIBUTEINHERITED]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPUBCATALOGATTRIBUTEINHERITED] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPUBCATALOGATTRIBUTEINHERITED].'
GO


ALTER FUNCTION [crt].[GETPUBCATALOGATTRIBUTEINHERITED]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_IsForwardLooking BIT
)
RETURNS TABLE
RETURN
    SELECT
        rpc.ORIGIN AS [CATALOG]
    FROM [ax].RETAILPUBCATALOG rpc
    INNER JOIN [crt].PUBCATALOGCHANNELATTRIBUTEINHERITEDVIEW pccaiv ON pccaiv.[CATALOG] = rpc.ORIGIN AND pccaiv.CHANNEL = @bi_ChannelId
    WHERE (@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN rpc.PUBLISHEDVALIDFROM AND rpc.PUBLISHEDVALIDTO) OR
        (@b_IsForwardLooking = 1 AND @dt_ChannelDate <= rpc.PUBLISHEDVALIDTO)


GO
PRINT N'Finished creating inline table function [crt].[GETPUBCATALOGATTRIBUTEINHERITED]'
-- End creating inline table function [crt].[GETPUBCATALOGATTRIBUTEINHERITED]


GRANT SELECT ON [crt].[GETPUBCATALOGATTRIBUTEINHERITED] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPUBCATALOGATTRIBUTEINHERITED] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATION]
PRINT N'Creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATION]';

GO
IF OBJECT_ID(N'[crt].[GETCATALOGCHANNELPRODUCTRELATION]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATALOGCHANNELPRODUCTRELATION] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATION].'
GO


-- Gets catalog channel product's hieararchy
ALTER FUNCTION [crt].[GETCATALOGCHANNELPRODUCTRELATION]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE
)
RETURNS TABLE
RETURN
    SELECT
        pcc.CHANNEL,
        cprv.CATALOG,
        cprv.PRODUCT,
        cprv.RELATEDPRODUCT,
        cprv.PRODUCTRELATIONTYPE
    FROM [crt].CATALOGPRODUCTRELATIONVIEW cprv
    INNER JOIN [crt].GETPUBCATALOGCURRENT(@bi_ChannelId, @dt_ChannelDate) pcc ON pcc.CATALOG = cprv.CATALOG


GO
PRINT N'Finished creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATION]'
-- End creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATION]


GRANT SELECT ON [crt].[GETCATALOGCHANNELPRODUCTRELATION] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETCATALOGCHANNELPRODUCTRELATION] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION]
PRINT N'Creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION]';

GO
IF OBJECT_ID(N'[crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION].'
GO


-- Gets catalog channel product's hieararchy
ALTER FUNCTION [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION]
(
    @bi_ChannelId   BIGINT,
    @dt_ChannelDate DATE
)
RETURNS TABLE
RETURN
    SELECT
        pcc.CHANNEL,
        cprev.CATALOG,
        cprev.PRODUCT,
        cprev.PRODUCTRELATION
    FROM [crt].CATALOGPRODUCTRELATIONEXCLUSIONVIEW cprev
    INNER JOIN [crt].GETPUBCATALOGCURRENT(@bi_ChannelId, @dt_ChannelDate) pcc ON pcc.CATALOG = cprev.CATALOG


GO
PRINT N'Finished creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION]'
-- End creating inline table function [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION]


GRANT SELECT ON [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUE]
PRINT N'Creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETPUBPRODUCTATTRIBUTEVALUE]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPUBPRODUCTATTRIBUTEVALUE] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUE].'
GO


ALTER FUNCTION [crt].[GETPUBPRODUCTATTRIBUTEVALUE]
(
    @bi_ChannelId       BIGINT,
    @bi_CatalogId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_IsForwardLooking BIT,
@tvp_ProductIds [crt].RECORDIDTABLETYPE READONLY
)
RETURNS TABLE
RETURN
    SELECT 
        ppavev.CHANNEL,
        ppavev.ATTRIBUTE,
        ppavev.ISREFERENCE,
        ppavev.PRODUCT,
        ppavev.CATALOG,
        ppavev.DISTANCE,
        7 AS SOURCE,    -- ChannelProductAttributeValue
        ppavev.DATETIMEVALUE,
        ppavev.DATETIMEVALUETZID,
        ppavev.FLOATVALUE,
        ppavev.INTVALUE, 
        ppavev.LANGUAGEID,
        ppavev.TEXTVALUE,
        ppavev.UNITOFMEASURE
    FROM [crt].PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW ppavev
INNER JOIN @tvp_ProductIds as IDS on ids.RECID = ppavev.PRODUCT
    WHERE ppavev.CATALOG = 0 AND GETUTCDATE() BETWEEN ppavev.ORGVALIDFROM AND ppavev.ORGVALIDTO
        AND
        (@bi_CatalogId = 0 OR EXISTS(
            SELECT 1
            FROM [ax].[RETAILPUBCATALOG]
            WHERE ORIGIN = @bi_CatalogId AND ENABLESNAPSHOT = 0
        ))

    UNION ALL

    SELECT
        ppacmv.CHANNEL,
        ppacmv.ATTRIBUTE,
        ppacmv.ISREFERENCE,
        rppav.PRODUCT,
        rppav.CATALOG,
        0 AS DISTANCE,
        8 AS SOURCE,    -- CatalogProductAttributeValue
        rppav.DATETIMEVALUE,
        rppav.DATETIMEVALUETZID,
        rppav.FLOATVALUE,
        rppav.INTVALUE,
        rppav.LANGUAGEID,
        rppav.TEXTVALUE,
        rppav.UNITOFMEASURE
    FROM [ax].RETAILPUBPRODUCTATTRIBUTEVALUE rppav
INNER JOIN @tvp_ProductIds as IDS on ids.RECID = rppav.PRODUCT
        INNER JOIN [crt].GETPUBCATALOGATTRIBUTEINHERITED(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking) pcai ON pcai.CATALOG = rppav.CATALOG
        INNER JOIN [crt].[PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW] ppacmv ON ppacmv.ACTUALATTRIBUTE = rppav.ATTRIBUTE AND ppacmv.CHANNEL = @bi_ChannelId
    WHERE rppav.INTERNALORGANIZATION = 0
        AND (@bi_CatalogId = 0                  -- All catalogs
            OR rppav.CATALOG = @bi_CatalogId)   -- Given catalog

    UNION ALL

    SELECT 
        ppavev.CHANNEL,
        ppavev.ATTRIBUTE,
        ppavev.ISREFERENCE,
        ppavev.PRODUCT,
        ppavev.CATALOG,
        ppavev.DISTANCE,
        9 AS SOURCE,    -- CatalogChannelProductAttributeValue
        ppavev.DATETIMEVALUE,
        ppavev.DATETIMEVALUETZID,
        ppavev.FLOATVALUE,
        ppavev.INTVALUE, 
        ppavev.LANGUAGEID,
        ppavev.TEXTVALUE,
        ppavev.UNITOFMEASURE
    FROM [crt].PUBPRODUCTATTRIBUTEVALUEEXPLODEDVIEW ppavev
JOIN @tvp_ProductIds as IDS on ids.RECID = ppavev.PRODUCT
    INNER JOIN [crt].GETPUBCATALOGATTRIBUTEINHERITED(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking) pcai ON pcai.CATALOG = ppavev.CATALOG AND @bi_ChannelId = ppavev.CHANNEL
    INNER JOIN ax.RETAILPUBCATALOG rpc ON rpc.ORIGIN = ppavev.CATALOG
    WHERE rpc.VALIDFROMDATETIME BETWEEN ppavev.ORGVALIDFROM AND ppavev.ORGVALIDTO
        AND (@bi_CatalogId = 0                  -- All catalogs
            OR ppavev.CATALOG = @bi_CatalogId)  -- Given catalog


GO
PRINT N'Finished creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUE]'
-- End creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUE]


GRANT SELECT ON [crt].[GETPUBPRODUCTATTRIBUTEVALUE] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPUBPRODUCTATTRIBUTEVALUE] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED]
PRINT N'Creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED]';

GO
IF OBJECT_ID(N'[crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED].'
GO


ALTER FUNCTION [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED]
(
    @bi_ChannelId       BIGINT,
    @bi_CatalogId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_IsForwardLooking BIT,
@tvp_ProductIds [crt].RECORDIDTABLETYPE READONLY
)
RETURNS TABLE
RETURN
    WITH PUBPRODUCTATTRIBUTEVALUE AS (
        SELECT
            ppav.ATTRIBUTE,
            ppav.ISREFERENCE,
            ppav.PRODUCT,
            ppav.CHANNEL,
            ppav.CATALOG,
            ppav.LANGUAGEID,
            ppav.DISTANCE,
            ppav.SOURCE,
            ppav.DATETIMEVALUE,
            ppav.DATETIMEVALUETZID,
            ppav.FLOATVALUE,
            ppav.INTVALUE,
            ppav.TEXTVALUE,
            ppav.UNITOFMEASURE
        FROM [crt].[GETPUBPRODUCTATTRIBUTEVALUE] (@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @b_IsForwardLooking, @tvp_ProductIds) ppav
        WHERE ppav.LANGUAGEID = ''

        UNION ALL 

        SELECT
            ppav.ATTRIBUTE,
            ppav.ISREFERENCE,
            ppav.PRODUCT,
            ppav.CHANNEL,
            ppav.CATALOG,
            ppav.LANGUAGEID,
            ppav.DISTANCE,
            ppav.SOURCE,
            ppav.DATETIMEVALUE,
            ppav.DATETIMEVALUETZID,
            ppav.FLOATVALUE,
            ppav.INTVALUE,
            ppav.TEXTVALUE,
            ppav.UNITOFMEASURE
        FROM [crt].[GETPUBPRODUCTATTRIBUTEVALUE] (@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @b_IsForwardLooking, @tvp_ProductIds) ppav
        JOIN [crt].CHANNELLANGUAGESVIEW clv ON clv.CHANNEL = @bi_ChannelId AND clv.LANGUAGEID = ppav.LANGUAGEID
        WHERE ppav.LANGUAGEID != ''
    )
    SELECT
        ppav.ATTRIBUTE,
        ppav.ISREFERENCE,
        ppav.PRODUCT,
        ppav.CHANNEL,
        ppav.CATALOG,
        ppav.DISTANCE,
        ppav.SOURCE,
        ppav.INTVALUE AS BOOLEANVALUE,
        ppav.FLOATVALUE AS CURRENCYVALUE,
        ppav.TEXTVALUE AS CURRENCYCODE,
        ppav.DATETIMEVALUE,
        ppav.DATETIMEVALUETZID,
        ppav.FLOATVALUE,
        uom.SYMBOL AS FLOATUNITSYMBOL,
        ppav.INTVALUE,
        uom.SYMBOL AS INTUNITSYMBOL,
        ppav.TEXTVALUE,
        ppav.LANGUAGEID AS LANGUAGE,
        ppav.TEXTVALUE AS TRANSLATION
    FROM PUBPRODUCTATTRIBUTEVALUE ppav
    LEFT JOIN [ax].UNITOFMEASURE uom ON uom.RECID = ppav.UNITOFMEASURE



GO
PRINT N'Finished creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED]'
-- End creating inline table function [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED]


GRANT SELECT ON [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES]
PRINT N'Creating inline table function [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES]';

GO
IF OBJECT_ID(N'[crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES].'
GO


-- Get next batch of listing publish statuses
ALTER FUNCTION [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES]
(
    @i_ActionStatus            INT,
    @nvc_LastChannelBatchId     NVARCHAR(100)
)
RETURNS TABLE
RETURN
    WITH NEXT_BATCH AS
    (
        SELECT
            MIN(CHANNELBATCHID) AS CHANNELBATCHID
            FROM [crt].[LISTINGPUBLISHSTATUSVIEW]
            WHERE ACTIONSTATUS = @i_ActionStatus AND CHANNELBATCHID > @nvc_LastChannelBatchId
    )
    SELECT
        LPSV.ACTIONSTATUS,
        LPSV.APPLIEDACTION,
        LPSV.CHANNEL,
        LPSV.CHANNELBATCHID,
        LPSV.CHANNELLISTINGID,
        LPSV.CHANNELSTATE,
        LPSV.LISTINGMODIFIEDDATETIME,
        LPSV.LISTINGMODIFIEDDATETIMETZID,
        LPSV.PROCESSED,
        LPSV.PRODUCT,
        LPSV.STATUSDATETIME,
        LPSV.STATUSDATETIMETZID,
        LPSV.STATUSMESSAGE
    FROM [crt].[LISTINGPUBLISHSTATUSVIEW] LPSV
    INNER JOIN NEXT_BATCH NB ON NB.CHANNELBATCHID = LPSV.CHANNELBATCHID
    WHERE LPSV.ACTIONSTATUS = @i_ActionStatus


GO
PRINT N'Finished creating inline table function [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES]'
-- End creating inline table function [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES]


GRANT SELECT ON [crt].[GETNEXTBATCHLISTINGPUBLISHSTATUSES] TO [UsersRole];
GO

-- Creating table function [crt].[GETCHILDCATEGORYIDSRECURSIVELY]
PRINT N'Creating table function [crt].[GETCHILDCATEGORYIDSRECURSIVELY]';

GO
IF OBJECT_ID(N'[crt].[GETCHILDCATEGORYIDSRECURSIVELY]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCHILDCATEGORYIDSRECURSIVELY] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETCHILDCATEGORYIDSRECURSIVELY].'
GO


-- Get the descendant categories using SQL CTE
ALTER Function [crt].[GETCHILDCATEGORYIDSRECURSIVELY]
(
    @ParentCategoryID BIGINT
)
RETURNS @CategoryIdResult TABLE
(
    [RECID] BIGINT NOT NULL
)
AS
BEGIN
    WITH c AS (
        SELECT DISTINCT
            cchv.RECID as Cid,
            cchv.PARENTCATEGORY as Pid
        FROM [crt].CHANNELCATEGORYHIERARCHYVIEW cchv
        WHERE cchv.PARENTCATEGORY  = @ParentCategoryID

        UNION ALL

        SELECT
            cchv.RECID as Cid,
            c.Pid
        FROM [crt].CHANNELCATEGORYHIERARCHYVIEW cchv
        INNER JOIN c ON cchv.PARENTCATEGORY = c.Cid
    )

    INSERT @CategoryIdResult
    SELECT DISTINCT Cid
    FROM c
    WHERE Pid = @ParentCategoryID
    RETURN;

END



GO
PRINT N'Finished creating table function [crt].[GETCHILDCATEGORYIDSRECURSIVELY]'
-- End creating table function [crt].[GETCHILDCATEGORYIDSRECURSIVELY]



-- Creating scalar function [crt].[PRICE_NODATE]
PRINT N'Creating scalar function [crt].[PRICE_NODATE]';

GO
IF OBJECT_ID(N'[crt].[PRICE_NODATE]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[PRICE_NODATE] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[PRICE_NODATE].'
GO


ALTER FUNCTION [crt].[PRICE_NODATE]()
RETURNS DATETIME AS
BEGIN
RETURN CAST('1900-01-01' AS DATETIME)
END;


GO
PRINT N'Finished creating scalar function [crt].[PRICE_NODATE]'
-- End creating scalar function [crt].[PRICE_NODATE]



-- Creating scalar function [crt].[PRICEDATEEFFECTIVITYFROMTYPE]
PRINT N'Creating scalar function [crt].[PRICEDATEEFFECTIVITYFROMTYPE]';

GO
IF OBJECT_ID(N'[crt].[PRICEDATEEFFECTIVITYFROMTYPE]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[PRICEDATEEFFECTIVITYFROMTYPE] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[PRICEDATEEFFECTIVITYFROMTYPE].'
GO


ALTER FUNCTION [crt].[PRICEDATEEFFECTIVITYFROMTYPE]()
RETURNS INT AS
BEGIN
    RETURN 1
END;


GO
PRINT N'Finished creating scalar function [crt].[PRICEDATEEFFECTIVITYFROMTYPE]'
-- End creating scalar function [crt].[PRICEDATEEFFECTIVITYFROMTYPE]




-- Creating scalar function [crt].[PRICEDATEEFFECTIVITYTOTYPE]
PRINT N'Creating scalar function [crt].[PRICEDATEEFFECTIVITYTOTYPE]';

GO
IF OBJECT_ID(N'[crt].[PRICEDATEEFFECTIVITYTOTYPE]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[PRICEDATEEFFECTIVITYTOTYPE] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[PRICEDATEEFFECTIVITYTOTYPE].'
GO


ALTER FUNCTION [crt].[PRICEDATEEFFECTIVITYTOTYPE]()
RETURNS INT AS
BEGIN
    RETURN 2
END;


GO
PRINT N'Finished creating scalar function [crt].[PRICEDATEEFFECTIVITYTOTYPE]'
-- End creating scalar function [crt].[PRICEDATEEFFECTIVITYTOTYPE]

-- Creating inline table function [crt].[GETCATALOGPRODUCTCATEGORY]
PRINT N'Creating inline table function [crt].[GETCATALOGPRODUCTCATEGORY]';

GO
IF OBJECT_ID(N'[crt].[GETCATALOGPRODUCTCATEGORY]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATALOGPRODUCTCATEGORY] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETCATALOGPRODUCTCATEGORY].'
GO


-- Gets catalog product's categories
ALTER FUNCTION [crt].[GETCATALOGPRODUCTCATEGORY]
(
@bi_ChannelIdBIGINT,
@b_ProductIdsPassed BIT, -- 1 when @tvp_ProductIds parameter is passed, 0 otherwise.
@tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS TABLE
RETURN

SELECT
rpcp.CATALOG,
rpcp.PRODUCT,
rpcpc.CATEGORY,
rpcpc.CATEGORYHIERARCHY,
rpcpc.INCLUDEEXCLUDETYPE
FROM [ax].RETAILPUBCATALOGPRODUCT rpcp
JOIN @tvp_ProductIds AS ids on @b_ProductIdsPassed = 0 OR rpcp.PRODUCT = ids.RECID
JOIN [ax].RETAILPUBCATALOGPRODUCTCATEGORY rpcpc ON rpcp.ORIGIN = rpcpc.CATALOGPRODUCT




GO
PRINT N'Finished creating inline table function [crt].[GETCATALOGPRODUCTCATEGORY]'
-- End creating inline table function [crt].[GETCATALOGPRODUCTCATEGORY]


GRANT SELECT ON [crt].[GETCATALOGPRODUCTCATEGORY] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETCATALOGPRODUCTCATEGORY] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETNONCATALOGPRODUCTCATEGORY]
PRINT N'Creating inline table function [crt].[GETNONCATALOGPRODUCTCATEGORY]';

GO
IF OBJECT_ID(N'[crt].[GETNONCATALOGPRODUCTCATEGORY]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETNONCATALOGPRODUCTCATEGORY] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETNONCATALOGPRODUCTCATEGORY].'
GO


-- Gets noncatalog product's categories
ALTER FUNCTION [crt].[GETNONCATALOGPRODUCTCATEGORY]
(
    @bi_ChannelId       BIGINT,
    @b_ProductIdsPassed BIT, -- 1 when @tvp_ProductIds parameter is passed, 0 otherwise.
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS TABLE
RETURN

    SELECT
        erpc.PRODUCT,
        erpc.CATEGORY,
erpc.CATEGORYHIERARCHY
    FROM [ax].ECORESPRODUCTCATEGORY AS erpc
    JOIN @tvp_ProductIds AS ids ON @b_ProductIdsPassed = 0 OR ids.RECID = erpc.PRODUCT
JOIN [ax].RETAILPUBECORESCATEGORY AS rperc ON rperc.CHANNEL = @bi_ChannelId AND rperc.ORIGINID = erpc.CATEGORY 
 
    UNION ALL

    SELECT
        erdpv.RECID AS PRODUCT,
        erpc.CATEGORY,
erpc.CATEGORYHIERARCHY
    FROM [ax].ECORESDISTINCTPRODUCTVARIANT AS erdpv
    JOIN @tvp_ProductIds AS ids ON @b_ProductIdsPassed = 0 OR erdpv.RECID = ids.RECID
    JOIN [ax].ECORESPRODUCTCATEGORY AS erpc ON erpc.PRODUCT = erdpv.PRODUCTMASTER
JOIN [ax].RETAILPUBECORESCATEGORY AS rperc ON rperc.CHANNEL = @bi_ChannelId AND rperc.ORIGINID = ERPC.CATEGORY


GO
PRINT N'Finished creating inline table function [crt].[GETNONCATALOGPRODUCTCATEGORY]'
-- End creating inline table function [crt].[GETNONCATALOGPRODUCTCATEGORY]


GRANT SELECT ON [crt].[GETNONCATALOGPRODUCTCATEGORY] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETNONCATALOGPRODUCTCATEGORY] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETCATALOGCHANNELPRODUCTCATEGORY]
PRINT N'Creating inline table function [crt].[GETCATALOGCHANNELPRODUCTCATEGORY]';

GO
IF OBJECT_ID(N'[crt].[GETCATALOGCHANNELPRODUCTCATEGORY]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATALOGCHANNELPRODUCTCATEGORY] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETCATALOGCHANNELPRODUCTCATEGORY].'
GO


-- Gets catalog channel product's hieararchy
ALTER FUNCTION [crt].[GETCATALOGCHANNELPRODUCTCATEGORY]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_IsForwardLooking BIT,
    @b_ProductIdsPassed BIT, -- 1 when @tvp_ProductIds parameter is passed, 0 otherwise.
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS TABLE
RETURN
    SELECT
        cpc.CATALOG,
        cpc.PRODUCT,
        cpc.CATEGORY,
        cpc.INCLUDEEXCLUDETYPE
    FROM [crt].GETCATALOGPRODUCTCATEGORY(@bi_ChannelId, @b_ProductIdsPassed, @tvp_ProductIds) cpc
        JOIN [crt].GETPUBCATALOGATTRIBUTEINHERITED(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking) rpc ON rpc.[CATALOG] = cpc.[CATALOG]
        JOIN [crt].PUBCATALOGCHANNELVIEW pccv ON pccv.[CATALOG] = rpc.[CATALOG]
        JOIN [ax].RETAILPUBRETAILCHANNELTABLE rprct ON rprct.ORIGINID = pccv.[CHANNEL]
    WHERE rprct.ORIGINID = @bi_ChannelId AND rprct.CATEGORYHIERARCHY = cpc.CATEGORYHIERARCHY


GO
PRINT N'Finished creating inline table function [crt].[GETCATALOGCHANNELPRODUCTCATEGORY]'
-- End creating inline table function [crt].[GETCATALOGCHANNELPRODUCTCATEGORY]


GRANT SELECT ON [crt].[GETCATALOGCHANNELPRODUCTCATEGORY] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETCATALOGCHANNELPRODUCTCATEGORY] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTCATEGORIES]
PRINT N'Creating inline table function [crt].[GETPRODUCTCATEGORIES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTCATEGORIES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTCATEGORIES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTCATEGORIES].'
GO


-- Get product navigation categories. @bi_CatalogId = 0 means all applicable catalogs.
ALTER FUNCTION [crt].[GETPRODUCTCATEGORIES]
(
    @bi_ChannelId     BIGINT,
    @bi_CatalogId     BIGINT,
    @dt_ChannelDate   DATE,
    @b_IsForwardLooking BIT,
    @b_ProductIdsPassed BIT,
    @tvp_ProductIds [crt].RECORDIDTABLETYPE READONLY,
    @b_CategoryIdsPassed BIT,
    @tvp_CategoryIds [crt].RECORDIDTABLETYPE READONLY
)
RETURNS TABLE
RETURN

    -- @bi_CatalogId = 0: Shared categories
    SELECT
        ncpc.PRODUCT,
        ncpc.CATEGORY,
        0 AS [CATALOG]
    FROM [crt].GETNONCATALOGPRODUCTCATEGORY(@bi_ChannelId, @b_ProductIdsPassed, @tvp_ProductIds) ncpc
    JOIN @tvp_CategoryIds cids ON @b_CategoryIdsPassed = 0 OR cids.RECID = ncpc.CATEGORY
    JOIN [ax].RETAILPUBRETAILCHANNELTABLE rprct ON rprct.ORIGINID = @bi_ChannelId
    WHERE @bi_CatalogId = 0 AND rprct.CATEGORYHIERARCHY = ncpc.CATEGORYHIERARCHY

    UNION ALL

    -- @bi_CatalogId = 0: Catalog specific categories
    SELECT
        ccpc.PRODUCT,
        ccpc.CATEGORY,
        ccpc.[CATALOG]
    FROM [crt].GETCATALOGCHANNELPRODUCTCATEGORY(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking, @b_ProductIdsPassed, @tvp_ProductIds) ccpc
    JOIN @tvp_CategoryIds cids ON @b_CategoryIdsPassed = 0 OR cids.RECID = ccpc.CATEGORY
    WHERE @bi_CatalogId = 0 AND ccpc.INCLUDEEXCLUDETYPE = 1    -- Include

    UNION ALL

    -- @bi_CatalogId != 0: Inherited categories
    SELECT
        ncpc.PRODUCT,
        ncpc.CATEGORY,
        rpcp.[CATALOG]
    FROM [crt].GETNONCATALOGPRODUCTCATEGORY(@bi_ChannelId, @b_ProductIdsPassed, @tvp_ProductIds) ncpc
    JOIN @tvp_CategoryIds cids ON @b_CategoryIdsPassed = 0 OR cids.RECID = ncpc.CATEGORY
    JOIN [ax].RETAILPUBCATALOGPRODUCT rpcp ON rpcp.PRODUCT = ncpc.PRODUCT AND rpcp.[CATALOG] = @bi_CatalogId
    JOIN [ax].RETAILPUBRETAILCHANNELTABLE rprct ON rprct.ORIGINID = @bi_ChannelId
    WHERE rprct.CATEGORYHIERARCHY = ncpc.CATEGORYHIERARCHY AND rpcp.USEHIERARCHY = 1
        AND EXISTS(
            SELECT 1
            FROM [ax].[RETAILPUBCATALOG]
            WHERE ORIGIN = @bi_CatalogId AND ENABLESNAPSHOT = 0
        )
        AND NOT EXISTS (
            SELECT *
            FROM [crt].GETCATALOGCHANNELPRODUCTCATEGORY(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking, @b_ProductIdsPassed, @tvp_ProductIds) ccpc
            WHERE ccpc.[CATALOG] = @bi_CatalogId
                AND ccpc.PRODUCT = rpcp.PRODUCT
                AND ccpc.CATEGORY = ncpc.CATEGORY
                AND ccpc.INCLUDEEXCLUDETYPE = 0    -- Exclude
        )

    UNION ALL

    -- @bi_CatalogId != 0: Catalog specific categories
    SELECT
        ccpc.PRODUCT,
        ccpc.CATEGORY,
        ccpc.[CATALOG]
    FROM [crt].GETCATALOGCHANNELPRODUCTCATEGORY(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking, @b_ProductIdsPassed, @tvp_ProductIds) ccpc
    JOIN @tvp_CategoryIds cids ON @b_CategoryIdsPassed = 0 OR cids.RECID = ccpc.CATEGORY
    WHERE ccpc.[CATALOG] = @bi_CatalogId AND ccpc.INCLUDEEXCLUDETYPE = 1    -- Include


GO
PRINT N'Finished creating inline table function [crt].[GETPRODUCTCATEGORIES]'
-- End creating inline table function [crt].[GETPRODUCTCATEGORIES]


GRANT SELECT ON [crt].[GETPRODUCTCATEGORIES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTCATEGORIES] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTCATEGORY]
PRINT N'Creating inline table function [crt].[GETPRODUCTCATEGORY]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTCATEGORY]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTCATEGORY] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTCATEGORY].'
GO


-- Get product categories for attributes. @bi_CatalogId = 0 means all applicable catalogs.
ALTER FUNCTION [crt].[GETPRODUCTCATEGORY]
(
    @bi_ChannelId       BIGINT,
    @bi_CatalogId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_ProductIdsPassed BIT, -- 1 when @tvp_ProductIds parameter is passed, 0 otherwise.
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY,
    @tvp_DummyId        [crt].[RECORDIDTABLETYPE] READONLY  -- A single row of ID 0
)
RETURNS TABLE
RETURN
    -- Channel navigation hierarchy
    SELECT
        @bi_ChannelId AS CHANNEL,
        pc.PRODUCT,
        pc.CATEGORY,
        pc.CATALOG
    FROM [crt].GETPRODUCTCATEGORIES(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, 0 /* @b_IsForwardLooking */, @b_ProductIdsPassed, @tvp_ProductIds, 0 /* @b_CategoryIdsPassed */, @tvp_DummyId) pc

    UNION ALL

    -- Retail product category hierarchy
    SELECT
        @bi_ChannelId AS CHANNEL,
        erpc.PRODUCT,
        erpc.CATEGORY,
        0 AS [CATALOG]
    FROM [ax].ECORESPRODUCTCATEGORY erpc
    JOIN @tvp_ProductIds ids on @b_ProductIdsPassed = 0 OR ids.RECID = erpc.PRODUCT
    JOIN [ax].RETAILPUBECORESCATEGORY rperc ON rperc.CHANNEL = @bi_ChannelId AND rperc.ORIGINID = erpc.CATEGORY
    JOIN [ax].ECORESCATEGORYHIERARCHYROLE erchr ON erchr.CATEGORYHIERARCHY = erpc.CATEGORYHIERARCHY AND erchr.NAMEDCATEGORYHIERARCHYROLE = 4 /* Retail */;


GO
PRINT N'Finished creating inline table function [crt].[GETPRODUCTCATEGORY]'
-- End creating inline table function [crt].[GETPRODUCTCATEGORY]


GRANT SELECT ON [crt].[GETPRODUCTCATEGORY] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTCATEGORY] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTATTRIBUTESCHEMAS]
PRINT N'Creating inline table function [crt].[GETPRODUCTATTRIBUTESCHEMAS]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTATTRIBUTESCHEMAS]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTATTRIBUTESCHEMAS] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTATTRIBUTESCHEMAS].'
GO


-- Get product attribute schemas. @bi_CatalogId = 0 means all applicable catalogs.
-- Note that the result set may contain duplicate rows because one attribute can come from multiple categories.
ALTER FUNCTION [crt].[GETPRODUCTATTRIBUTESCHEMAS]
(
    @bi_ChannelId BIGINT,
    @bi_CatalogId BIGINT,
    @dt_ChannelDate DATE,
    @tvp_ProductIds [crt].RECORDIDTABLETYPE READONLY,
@tvp_DummyId [crt].[RECORDIDTABLETYPE] READONLY     -- A single row of ID 0
)
RETURNS TABLE
RETURN
    -- NonCategory
    SELECT
        rppacm.ATTRIBUTE,
        0 AS PRODUCT,
        0 AS CATALOG,
        0 AS ATTRIBUTEGROUP,
        0 AS ATTRIBUTEGROUPTYPE
        FROM [ax].RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA rppacm
        WHERE rppacm.ATTRIBUTERELATIONTYPE != 1  -- NonCategory
            AND rppacm.HOSTCHANNEL = @bi_ChannelId

    UNION ALL

    -- Category
    SELECT
        rppacm.ATTRIBUTE,
        pc.PRODUCT,
        pc.CATALOG,
        cpav.ATTRIBUTEGROUP, 
        cpav.ATTRIBUTEGROUPTYPE
        FROM @tvp_ProductIds tpi
            JOIN [crt].GETPRODUCTCATEGORY(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, 1 /* @b_ProductIdsPassed */,  @tvp_ProductIds, @tvp_DummyId) pc
                ON pc.PRODUCT = tpi.RECID
            JOIN [crt].CATEGORYPRODUCTATTRIBUTEVIEW cpav 
                ON cpav.CATEGORY = pc.CATEGORY
            JOIN [ax].RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA rppacm
                ON rppacm.ATTRIBUTE = cpav.ATTRIBUTE
                    AND rppacm.HOSTCHANNEL = pc.CHANNEL
        WHERE rppacm.ATTRIBUTERELATIONTYPE = 1  -- Category
            AND rppacm.HOSTCHANNEL = @bi_ChannelId


GO
PRINT N'Finished creating inline table function [crt].[GETPRODUCTATTRIBUTESCHEMAS]'
-- End creating inline table function [crt].[GETPRODUCTATTRIBUTESCHEMAS]


GRANT SELECT ON [crt].[GETPRODUCTATTRIBUTESCHEMAS] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTATTRIBUTESCHEMAS] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE]
PRINT N'Creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE].'
GO


-- Gets category productattributegroup default values
ALTER FUNCTION [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE]
(
@bi_ChannelIdBIGINT,
@dt_ChannelDateDATE,
@b_ProductIdsPassedBIT,
@tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY,
@tvp_DummyId[crt].[RECORDIDTABLETYPE] READONLY-- A single row of ID 0
)
RETURNS TABLE
RETURN

SELECT 
pc.CHANNEL,
ppacmv.ATTRIBUTE,
ppacmv.ISREFERENCE,
cpav.ATTRIBUTEGROUP,
cpav.ATTRIBUTEGROUPTYPE,
cpav.DEFAULTVALUE AS VALUE,
pc.PRODUCT,
pc.CATEGORY,
pc.CATALOG
        FROM [crt].GETPRODUCTCATEGORY(@bi_ChannelId, 0 /* @bi_CatalogId */, @dt_ChannelDate, @b_ProductIdsPassed, @tvp_ProductIds, @tvp_DummyId) pc
        JOIN [crt].CATEGORYPRODUCTATTRIBUTEVIEW cpav ON cpav.CATEGORY = pc.CATEGORY AND cpav.DEFAULTVALUE != 0
JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW ppacmv ON ppacmv.ACTUALATTRIBUTE = cpav.ATTRIBUTE AND ppacmv.CHANNEL = pc.CHANNEL
    


GO
PRINT N'Finished creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE]'
-- End creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE]


GRANT SELECT ON [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE]
PRINT N'Creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE].'
GO


-- Gets category productattribute's values
ALTER FUNCTION [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE]
(
@bi_ChannelIdBIGINT,
@dt_ChannelDateDATE,
@b_ProductIdsPassedBIT,
@tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY,
@tvp_DummyId[crt].[RECORDIDTABLETYPE] READONLY-- A single row of ID 0
)
RETURNS TABLE
RETURN

SELECT
pc.CHANNEL,
ppacmv.ATTRIBUTE,
ppacmv.ISREFERENCE,
cpav.ATTRIBUTEGROUP,
cpav.ATTRIBUTEGROUPTYPE,
erav.VALUE,
pc.PRODUCT,
pc.CATALOG
        FROM [crt].GETPRODUCTCATEGORY(@bi_ChannelId, 0 /* @bi_CatalogId */, @dt_ChannelDate, @b_ProductIdsPassed, @tvp_ProductIds, @tvp_DummyId) pc
        JOIN [crt].CATEGORYPRODUCTATTRIBUTEVIEW cpav ON cpav.CATEGORY = pc.CATEGORY
            JOIN [ax].ECORESPRODUCTINSTANCEVALUE erpiv ON  erpiv.PRODUCT = pc.PRODUCT
JOIN [ax].ECORESATTRIBUTEVALUE erav ON erav.INSTANCEVALUE = erpiv.RECID AND erav.ATTRIBUTE = cpav.ATTRIBUTE
JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW ppacmv ON ppacmv.ACTUALATTRIBUTE = cpav.ATTRIBUTE AND ppacmv.CHANNEL = pc.CHANNEL  AND ppacmv.CHANNEL = @bi_ChannelId




GO
PRINT N'Finished creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE]'
-- End creating inline table function [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE]


GRANT SELECT ON [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUE]
PRINT N'Creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETLIVEPRODUCTATTRIBUTEVALUE]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETLIVEPRODUCTATTRIBUTEVALUE] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUE].'
GO


-- Gets live product attributes' values
ALTER FUNCTION [crt].[GETLIVEPRODUCTATTRIBUTEVALUE]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_ProductIdsPassed BIT,
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY,
@tvp_DummyId[crt].[RECORDIDTABLETYPE] READONLY-- A single row of ID 0
)
RETURNS TABLE
RETURN

    SELECT
        CHANNEL,
        ATTRIBUTE,
        ISREFERENCE,
        ATTRIBUTEGROUP,
        ATTRIBUTEGROUPTYPE,
        VALUE,
        PRODUCT,
        CATEGORY,
        CATALOG,
        4 AS SOURCE    -- CategoryProductAttributeGroupDefaultValue
    FROM [crt].GETCATEGORYPRODUCTATTRIBUTEGROUPDEFAULTVALUE(@bi_ChannelId, @dt_ChannelDate, @b_ProductIdsPassed, @tvp_ProductIds, @tvp_DummyId)

    UNION ALL

    SELECT
        CHANNEL,
        ATTRIBUTE,
        ISREFERENCE,
        ATTRIBUTEGROUP,
        ATTRIBUTEGROUPTYPE,
        VALUE,
        PRODUCT,
        0 AS CATEGORY,
        CATALOG,
        6 AS SOURCE    -- CategoryProductAttributeValue
    FROM [crt].[GETCATEGORYPRODUCTATTRIBUTEVALUE](@bi_ChannelId, @dt_ChannelDate, @b_ProductIdsPassed, @tvp_ProductIds, @tvp_DummyId)



GO
PRINT N'Finished creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUE]'
-- End creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUE]


GRANT SELECT ON [crt].[GETLIVEPRODUCTATTRIBUTEVALUE] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETLIVEPRODUCTATTRIBUTEVALUE] TO [PublishersRole];
GO

-- Creating table function [crt].[GETPRODUCTVARIANTDIMENSIONVALUES]
PRINT N'Creating table function [crt].[GETPRODUCTVARIANTDIMENSIONVALUES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTVARIANTDIMENSIONVALUES]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTVARIANTDIMENSIONVALUES] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETPRODUCTVARIANTDIMENSIONVALUES].'
GO


-- Gets dimensions by given set of Ids
ALTER FUNCTION [crt].[GETPRODUCTVARIANTDIMENSIONVALUES]
(
@b_ProductIdsPassed     BIT,
@tvp_ProductIds         [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS @resultTable TABLE
(
RECID BIGINT,
DISTINCTPRODUCTVARIANT BIGINT
)
AS BEGIN

IF @b_ProductIdsPassed = 0
BEGIN
INSERT @resultTable
SELECT 
RECID, 
DISTINCTPRODUCTVARIANT
FROM ax.ECORESPRODUCTVARIANTDIMENSIONVALUE
END
ELSE
BEGIN
INSERT @resultTable
SELECT 
EPVDV.RECID, 
DISTINCTPRODUCTVARIANT
FROM @tvp_ProductIds ids
JOIN ax.ECORESPRODUCTVARIANTDIMENSIONVALUE EPVDV ON EPVDV.DISTINCTPRODUCTVARIANT = ids.RECID
OPTION (FORCE ORDER)
END

RETURN 

END


GO
PRINT N'Finished creating table function [crt].[GETPRODUCTVARIANTDIMENSIONVALUES]'
-- End creating table function [crt].[GETPRODUCTVARIANTDIMENSIONVALUES]


GRANT SELECT ON [crt].[GETPRODUCTVARIANTDIMENSIONVALUES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTVARIANTDIMENSIONVALUES] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE]
PRINT N'Creating inline table function [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE]';

GO
IF OBJECT_ID(N'[crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE].'
GO


-- Gets standard product attributes' values.
ALTER FUNCTION [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE]
(
@bi_ChannelId           BIGINT,
@b_ProductIdsPassed     BIT,
@tvp_ProductIds         [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS TABLE
RETURN

    SELECT
        EP.RECID AS PRODUCT,
        RSA.ATTRIBUTE,
        EP.DISPLAYPRODUCTNUMBER AS TEXTVALUE,
        '' AS LANGUAGEID,
        '' AS TRANSLATION
    FROM [ax].ECORESPRODUCT EP
    JOIN @tvp_ProductIds AS ids ON @b_ProductIdsPassed = 0 OR EP.RECID = ids.RECID
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 1  -- ProductNumber
    
    UNION ALL

    SELECT
        EPT.PRODUCT,
        RSA.ATTRIBUTE,
        '' AS TEXTVALUE,
        EPT.LANGUAGEID,
        EPT.NAME AS TRANSLATION
    FROM [ax].ECORESPRODUCTTRANSLATION EPT
    JOIN [crt].CHANNELLANGUAGESVIEW CLV ON CLV.CHANNEL = @bi_ChannelId AND CLV.LANGUAGEID = EPT.LANGUAGEID
    JOIN @tvp_ProductIds AS ids ON @b_ProductIdsPassed = 0 OR EPT.PRODUCT = ids.RECID
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 2  -- ProductName
    
    UNION ALL

    SELECT
        EP.RECID AS PRODUCT,
        RSA.ATTRIBUTE,
        EP.SEARCHNAME AS TEXTVALUE,
        '' AS LANGUAGEID,
        '' AS TRANSLATION
    FROM [ax].ECORESPRODUCT EP
    JOIN @tvp_ProductIds AS ids ON @b_ProductIdsPassed = 0 OR EP.RECID = ids.RECID
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 3  -- SearchName
    
    UNION ALL

    SELECT
        EPT.PRODUCT,
        RSA.ATTRIBUTE,
        '' AS TEXTVALUE,
        EPT.LANGUAGEID,
        EPT.DESCRIPTION AS TRANSLATION
    FROM [ax].ECORESPRODUCTTRANSLATION EPT
    JOIN [crt].CHANNELLANGUAGESVIEW CLV ON CLV.CHANNEL = @bi_ChannelId AND CLV.LANGUAGEID = EPT.LANGUAGEID
    JOIN @tvp_ProductIds AS ids ON @b_ProductIdsPassed = 0 OR EPT.PRODUCT = ids.RECID
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 4  -- Description

UNION ALL

    SELECT
        EPVDV.DISTINCTPRODUCTVARIANT AS PRODUCT,
        rsa.ATTRIBUTE,
        EC.NAME AS TEXTVALUE,
        ISNULL(PMDVT.LANGUAGEID, '') AS LANGUAGEID,
        ISNULL(PMDVT.NAME, '') AS TRANSLATION
FROM crt.GETPRODUCTVARIANTDIMENSIONVALUES(@b_ProductIdsPassed, @tvp_ProductIds) EPVDV
JOIN ax.ECORESPRODUCTVARIANTCOLOR EPVC ON EPVDV.RECID = EPVC.RECID
    JOIN ax.ECORESCOLOR EC ON EC.RECID = EPVC.COLOR
    JOIN ax.ECORESDISTINCTPRODUCTVARIANT EDPV ON EDPV.RECID = EPVDV.DISTINCTPRODUCTVARIANT
    JOIN ax.ECORESPRODUCTMASTERCOLOR EPMC ON (EPMC.COLORPRODUCTMASTER = EDPV.PRODUCTMASTER AND EPMC.COLOR = EC.RECID)
    LEFT OUTER JOIN crt.GETPRODUCTMASTERDIMVALUETRANSLATION(@bi_ChannelId) AS PMDVT ON PMDVT.PRODUCTMASTERDIMENSIONVALUE = EPMC.RECID
JOIN ax.RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 5  -- Color

UNION ALL

SELECT
        EPVDV.DISTINCTPRODUCTVARIANT AS PRODUCT,
        rsa.ATTRIBUTE,
        EC.NAME AS TEXTVALUE,
        ISNULL(PMDVT.LANGUAGEID, '') AS LANGUAGEID,
        ISNULL(PMDVT.NAME, '') AS TRANSLATION
FROM crt.GETPRODUCTVARIANTDIMENSIONVALUES(@b_ProductIdsPassed, @tvp_ProductIds) EPVDV
JOIN ax.ECORESPRODUCTVARIANTSTYLE EPVS ON EPVDV.RECID = EPVS.RECID
    JOIN ax.ECORESSTYLE EC ON EC.RECID = EPVS.STYLE
    JOIN ax.ECORESDISTINCTPRODUCTVARIANT EDPV ON EDPV.RECID = EPVDV.DISTINCTPRODUCTVARIANT
    JOIN ax.ECORESPRODUCTMASTERSTYLE EPMS ON (EPMS.STYLEPRODUCTMASTER = EDPV.PRODUCTMASTER AND EPMS.STYLE = EC.RECID)
    LEFT OUTER JOIN crt.GETPRODUCTMASTERDIMVALUETRANSLATION(@bi_ChannelId) AS PMDVT ON PMDVT.PRODUCTMASTERDIMENSIONVALUE = EPMS.RECID
JOIN ax.RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 6  -- Style

UNION ALL

SELECT
        EPVDV.DISTINCTPRODUCTVARIANT AS PRODUCT,
        RSA.ATTRIBUTE,
        EC.NAME AS TEXTVALUE,
        ISNULL(PMDVT.LANGUAGEID, '') AS LANGUAGEID,
        ISNULL(PMDVT.NAME, '') AS TRANSLATION
FROM crt.GETPRODUCTVARIANTDIMENSIONVALUES(@b_ProductIdsPassed, @tvp_ProductIds) EPVDV
JOIN ax.ECORESPRODUCTVARIANTSIZE EPVS ON EPVDV.RECID = EPVS.RECID
    JOIN ax.ECORESSIZE EC ON EC.RECID = EPVS.SIZE
    JOIN ax.ECORESDISTINCTPRODUCTVARIANT EDPV ON EDPV.RECID = EPVDV.DISTINCTPRODUCTVARIANT
    JOIN ax.ECORESPRODUCTMASTERSIZE EPMS ON (EPMS.SIZEPRODUCTMASTER = EDPV.PRODUCTMASTER AND EPMS.SIZE = EC.RECID)
    LEFT OUTER JOIN crt.GETPRODUCTMASTERDIMVALUETRANSLATION(@bi_ChannelId) AS PMDVT ON PMDVT.PRODUCTMASTERDIMENSIONVALUE = EPMS.RECID
JOIN ax.RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 7  -- Size

UNION ALL

SELECT
        EPVDV.DISTINCTPRODUCTVARIANT AS PRODUCT,
        rsa.ATTRIBUTE,
        EC.NAME AS TEXTVALUE,
        ISNULL(PMDVT.LANGUAGEID, '') AS LANGUAGEID,
        ISNULL(PMDVT.NAME, '') AS TRANSLATION
FROM crt.GETPRODUCTVARIANTDIMENSIONVALUES(@b_ProductIdsPassed, @tvp_ProductIds) EPVDV
JOIN ax.ECORESPRODUCTVARIANTCONFIGURATION EPVC ON EPVDV.RECID = EPVC.RECID
    JOIN ax.ECORESCONFIGURATION EC ON EC.RECID = EPVC.CONFIGURATION
    JOIN ax.ECORESDISTINCTPRODUCTVARIANT EDPV ON EDPV.RECID = EPVDV.DISTINCTPRODUCTVARIANT
    JOIN ax.ECORESPRODUCTMASTERCONFIGURATION EPMC ON (EPMC.CONFIGPRODUCTMASTER = EDPV.PRODUCTMASTER AND EPMC.CONFIGURATION = EC.RECID)
    LEFT OUTER JOIN crt.GETPRODUCTMASTERDIMVALUETRANSLATION(@bi_ChannelId) AS PMDVT ON PMDVT.PRODUCTMASTERDIMENSIONVALUE = EPMC.RECID
JOIN ax.RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 8  -- Configuration


    

GO
PRINT N'Finished creating inline table function [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE]'
-- End creating inline table function [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE]


GRANT SELECT ON [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED]
PRINT N'Creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED]';

GO
IF OBJECT_ID(N'[crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED].'
GO


-- Gets live product expanded attributes' values
ALTER FUNCTION [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_ProductIdsPassed BIT,
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE] READONLY,
@tvp_DummyId[crt].[RECORDIDTABLETYPE] READONLY-- A single row of ID 0
)
RETURNS TABLE
RETURN

    SELECT
        lpav.CHANNEL,
        lpav.ATTRIBUTE,
        lpav.ISREFERENCE,
        lpav.ATTRIBUTEGROUP,
        lpav.ATTRIBUTEGROUPTYPE,
        lpav.VALUE,
        lpav.PRODUCT,
        lpav.CATEGORY,
        lpav.CATALOG,
        lpav.SOURCE,
        ve.BOOLEANVALUE,
        ve.CURRENCYVALUE,
        ve.CURRENCYCODE,
        ve.DATETIMEVALUE,
        ve.DATETIMEVALUETZID,
        ve.FLOATVALUE,
        ve.FLOATUNITSYMBOL,
        ve.INTVALUE,
        ve.INTUNITSYMBOL,
        ve.TEXTVALUE,
        ve.LANGUAGE,
        ve.TRANSLATION
    FROM [crt].GETLIVEPRODUCTATTRIBUTEVALUE(@bi_ChannelId, @dt_ChannelDate, @b_ProductIdsPassed, @tvp_ProductIds, @tvp_DummyId) lpav
JOIN crt.GETVALUEEXPANDED(@bi_ChannelId) ve
ON ve.RECID = lpav.VALUE

    UNION ALL

    SELECT
        ppacmv.CHANNEL,
        ppacmv.ATTRIBUTE,
        ppacmv.ISREFERENCE,
        0 AS ATTRIBUTEGROUP,
        0 AS ATTRIBUTEGROUPTYPE,
        0 AS VALUE,
        spav.PRODUCT,
        0 AS CATEGORY,
        0 AS CATALOG,
        5 AS SOURCE,    -- StandardProductAttributeValue
        0 AS BOOLEANVALUE,
        0 AS CURRENCYVALUE,
        '' AS CURRENCYCODE,
        0 AS DATETIMEVALUE,
        0 AS DATETIMEVALUETZID,
        0 AS FLOATVALUE,
        '' AS FLOATUNITSYMBOL,
        0 AS INTVALUE,
        '' AS INTUNITSYMBOL,
        spav.TEXTVALUE,
        spav.LANGUAGEID AS LANGUAGE,
        spav.TRANSLATION
    FROM [crt].[GETSTANDARDPRODUCTATTRIBUTEVALUE](@bi_ChannelId, @b_ProductIdsPassed, @tvp_ProductIds) spav
    JOIN crt.PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW ppacmv ON ppacmv.ACTUALATTRIBUTE = spav.ATTRIBUTE WHERE ppacmv.CHANNEL = @bi_ChannelId



GO
PRINT N'Finished creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED]'
-- End creating inline table function [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED]


GRANT SELECT ON [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTATTRIBUTEVALUES]
PRINT N'Creating inline table function [crt].[GETPRODUCTATTRIBUTEVALUES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTATTRIBUTEVALUES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTATTRIBUTEVALUES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTATTRIBUTEVALUES].'
GO


-- Get product attribute values. @bi_CatalogId = 0 means all applicable catalogs.
ALTER FUNCTION [crt].[GETPRODUCTATTRIBUTEVALUES]
(
    @bi_ChannelId       BIGINT,
    @bi_CatalogId       BIGINT,
    @dt_ChannelDate     DATE,
    @b_IsForwardLooking BIT,
    @tvp_ProductIds     [crt].RECORDIDTABLETYPE READONLY,
@tvp_DummyId[crt].[RECORDIDTABLETYPE] READONLY-- A single row of ID 0
)
RETURNS TABLE
RETURN
    -- Non product specific live attribute values.
    SELECT
        gpavv.ATTRIBUTE,
        gpavv.VALUE,
        gpavv.ISREFERENCE,
        0 AS PRODUCT,
        0 AS CATEGORY,
        0 AS CATALOG,
        0 AS DISTANCE,
        gpavv.SOURCE,
        ve.BOOLEANVALUE,
        ve.CURRENCYVALUE,
        ve.CURRENCYCODE,
        ve.DATETIMEVALUE,
        ve.DATETIMEVALUETZID,
        ve.FLOATVALUE,
        ve.FLOATUNITSYMBOL,
        ve.INTVALUE,
        ve.INTUNITSYMBOL,
        ve.TEXTVALUE,
        ve.LANGUAGE,
        ve.TRANSLATION
    FROM [crt].GLOBALPRODUCTATTRIBUTEVALUEVIEW gpavv
JOIN crt.GETVALUEEXPANDED(@bi_ChannelId) ve
ON ve.RECID = gpavv.VALUE
    WHERE gpavv.CHANNEL = @bi_ChannelId 
        AND
        (@bi_CatalogId = 0 OR EXISTS(
            SELECT 1
            FROM [ax].[RETAILPUBCATALOG]
            WHERE ORIGIN = @bi_CatalogId AND ENABLESNAPSHOT = 0
        ))

    UNION ALL

    -- Product specific live attribute values.
    SELECT
        lpave.ATTRIBUTE,
        lpave.VALUE,
        lpave.ISREFERENCE,
        lpave.PRODUCT,
        lpave.CATEGORY,
        lpave.CATALOG,
        0 AS DISTANCE,
        lpave.SOURCE,
        lpave.BOOLEANVALUE,
        lpave.CURRENCYVALUE,
        lpave.CURRENCYCODE,
        lpave.DATETIMEVALUE,
        lpave.DATETIMEVALUETZID,
        lpave.FLOATVALUE,
        lpave.FLOATUNITSYMBOL,
        lpave.INTVALUE,
        lpave.INTUNITSYMBOL,
        lpave.TEXTVALUE,
        lpave.LANGUAGE,
        lpave.TRANSLATION
    FROM [crt].[GETLIVEPRODUCTATTRIBUTEVALUEEXPANDED](@bi_ChannelId, @dt_ChannelDate, 1 /* @b_ProductIdsPassed */, @tvp_ProductIds, @tvp_DummyId) lpave
WHERE @bi_CatalogId = 0 OR EXISTS(
        SELECT 1
        FROM [ax].[RETAILPUBCATALOG]
        WHERE ORIGIN = @bi_CatalogId AND ENABLESNAPSHOT = 0
)

    UNION ALL

    -- Non product specific published attribute values.
    SELECT
        ppave.ATTRIBUTE,
        0 AS VALUE,
        ppave.ISREFERENCE,
        ppave.PRODUCT,
        0 AS CATEGORY,
        ppave.CATALOG,
        ppave.DISTANCE,
        ppave.SOURCE,
        ppave.BOOLEANVALUE,
        ppave.CURRENCYVALUE,
        ppave.CURRENCYCODE,
        ppave.DATETIMEVALUE,
        ppave.DATETIMEVALUETZID,
        ppave.FLOATVALUE,
        ppave.FLOATUNITSYMBOL,
        ppave.INTVALUE,
        ppave.INTUNITSYMBOL,
        ppave.TEXTVALUE,
        ppave.LANGUAGE,
        ppave.TRANSLATION
    -- The variable @tvp_DummyId is used below but in fact its purpose is not to provide literally *dummy* id but a row with ID 0 which should be 
-- there for a business reason we are interested in only those products which have value 0 as their productID
FROM [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED] (@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @b_IsForwardLooking, @tvp_DummyId) ppave 

    UNION ALL

    -- Product specific published attribute values.
    SELECT
        ppave.ATTRIBUTE,
        0 AS VALUE,
        ppave.ISREFERENCE,
        ppave.PRODUCT,
        0 AS CATEGORY,
        ppave.CATALOG,
        ppave.DISTANCE,
        ppave.SOURCE,
        ppave.BOOLEANVALUE,
        ppave.CURRENCYVALUE,
        ppave.CURRENCYCODE,
        ppave.DATETIMEVALUE,
        ppave.DATETIMEVALUETZID,
        ppave.FLOATVALUE,
        ppave.FLOATUNITSYMBOL,
        ppave.INTVALUE,
        ppave.INTUNITSYMBOL,
        ppave.TEXTVALUE,
        ppave.LANGUAGE,
        ppave.TRANSLATION
    FROM [crt].[GETPUBPRODUCTATTRIBUTEVALUEEXPANDED] (@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @b_IsForwardLooking, @tvp_ProductIds) ppave


GO
PRINT N'Finished creating inline table function [crt].[GETPRODUCTATTRIBUTEVALUES]'
-- End creating inline table function [crt].[GETPRODUCTATTRIBUTEVALUES]


GRANT SELECT ON [crt].[GETPRODUCTATTRIBUTEVALUES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTATTRIBUTEVALUES] TO [PublishersRole];
GO

-- Creating table function [crt].[GETPRODUCTRELATIONS]
PRINT N'Creating table function [crt].[GETPRODUCTRELATIONS]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTRELATIONS]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTRELATIONS] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETPRODUCTRELATIONS].'
GO


-- Get product relations. @bi_CatalogId = 0 means all applicable catalogs.
ALTER FUNCTION [crt].[GETPRODUCTRELATIONS]
(
    @bi_ChannelId       BIGINT,
    @bi_CatalogId       BIGINT,
    @dt_ChannelDate     DATE,
    @tvp_ProductIds     [crt].RECORDIDTABLETYPE READONLY
)
RETURNS @productRelations TABLE
(
    [CATALOG] BIGINT,
    [PRODUCT] BIGINT,
    [RELATEDPRODUCT] BIGINT,
    [PRODUCTRELATIONTYPE] NVARCHAR(60),
    [EXCLUSION] BIT
)
AS
BEGIN

    -- Declare and fill a cursor with ids of all products related to the specified products,
    -- directly or indirectly.
    DECLARE @tvp_AllIds [crt].RECORDIDTABLETYPE
    INSERT @tvp_AllIds(RECID)
        SELECT DISTINCT allIds.RECID
        FROM (
            SELECT erprt.PRODUCT1 AS RECID
            FROM ax.ECORESPRODUCTRELATIONTABLE erprt
            INNER JOIN @tvp_ProductIds ids ON ids.RECID = erprt.PRODUCT1

            UNION

            SELECT erprt.PRODUCT1 AS RECID
            FROM ax.ECORESPRODUCTRELATIONTABLE erprt
            INNER JOIN @tvp_ProductIds ids ON ids.RECID = erprt.PRODUCT2
        ) AS allIds

    INSERT @productRelations(
        [CATALOG],
        [PRODUCT],
        [RELATEDPRODUCT],
        [PRODUCTRELATIONTYPE],
        [EXCLUSION])

    -- Non catalog product relations
    SELECT
        0 AS [CATALOG],
        erprt.PRODUCT1 AS PRODUCT,
        erprt.PRODUCT2 AS RELATEDPRODUCT,
        erprtype.NAME AS PRODUCTRELATIONTYPE,
        0 AS EXCLUSION
        FROM @tvp_AllIds tpi
        INNER JOIN ax.ECORESPRODUCTRELATIONTABLE erprt ON erprt.PRODUCT1 = tpi.RECID
    INNER JOIN ax.ECORESPRODUCTRELATIONTYPE erprtype ON erprt.PRODUCTRELATIONTYPE = erprtype.RECID
    WHERE @bi_CatalogId = 0 OR (EXISTS(
        SELECT 1
        FROM [ax].[RETAILPUBCATALOG]
        WHERE ORIGIN = @bi_CatalogId AND ENABLESNAPSHOT = 0
    ) AND NOT EXISTS (
        SELECT 1
        FROM [crt].GETCATALOGCHANNELPRODUCTRELATIONEXCLUSION(@bi_ChannelId, @dt_ChannelDate) ccpre
        WHERE ccpre.[CATALOG] = @bi_CatalogId AND ccpre.PRODUCTRELATION = erprt.RECID
    ))

    UNION ALL

    -- Catalog product relations
    SELECT
        ccpr.CATALOG,
        ccpr.PRODUCT,
        ccpr.RELATEDPRODUCT,
        erprtype.NAME AS PRODUCTRELATIONTYPE,
        0 AS EXCLUSION
    FROM @tvp_AllIds tpi
    INNER JOIN [crt].GETCATALOGCHANNELPRODUCTRELATION(@bi_ChannelId, @dt_ChannelDate) ccpr ON ccpr.PRODUCT = tpi.RECID
    INNER JOIN ax.ECORESPRODUCTRELATIONTYPE erprtype ON erprtype.RECID = ccpr.PRODUCTRELATIONTYPE
    WHERE ccpr.CHANNEL = @bi_ChannelId
        AND (@bi_CatalogId = 0                  -- All catalogs
            OR ccpr.CATALOG = @bi_CatalogId)    -- Given catalog

    RETURN;

END

GO
PRINT N'Finished creating table function [crt].[GETPRODUCTRELATIONS]'
-- End creating table function [crt].[GETPRODUCTRELATIONS]


GRANT SELECT ON [crt].[GETPRODUCTRELATIONS] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTRELATIONS] TO [PublishersRole];
GO

-- Creating scalar function [crt].[GETTENDERDECLARATIONCALCULATIONTYPE]
PRINT N'Creating scalar function [crt].[GETTENDERDECLARATIONCALCULATIONTYPE]';

GO
IF OBJECT_ID(N'[crt].[GETTENDERDECLARATIONCALCULATIONTYPE]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETTENDERDECLARATIONCALCULATIONTYPE] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETTENDERDECLARATIONCALCULATIONTYPE].'
GO


ALTER FUNCTION [crt].[GETTENDERDECLARATIONCALCULATIONTYPE]
(
@bi_ChannelIdbigint
)

RETURNS INT

BEGIN
DECLARE @TENDERDECLARATIONCALCTYPE as INT 

SET @TENDERDECLARATIONCALCTYPE = (SELECT TENDERDECLARATIONCALCULATION
FROM[ax].[RETAILSTORETABLE]
WHERERECID = @bi_ChannelId)

RETURN @TENDERDECLARATIONCALCTYPE
END


GO
PRINT N'Finished creating scalar function [crt].[GETTENDERDECLARATIONCALCULATIONTYPE]'
-- End creating scalar function [crt].[GETTENDERDECLARATIONCALCULATIONTYPE]



GRANT EXECUTE ON [crt].[GETTENDERDECLARATIONCALCULATIONTYPE] TO [UsersRole];
GO



-- Creating table function [crt].[SEARCHPRODUCTSBYCATEGORY]
PRINT N'Creating table function [crt].[SEARCHPRODUCTSBYCATEGORY]';

GO
IF OBJECT_ID(N'[crt].[SEARCHPRODUCTSBYCATEGORY]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[SEARCHPRODUCTSBYCATEGORY] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[SEARCHPRODUCTSBYCATEGORY].'
GO


ALTER FUNCTION [crt].[SEARCHPRODUCTSBYCATEGORY]
(
    @bi_ChannelId       BIGINT,
    @bi_CatalogId       BIGINT,
    @dt_ChannelDate     DATE,
    @i_CategoryLevels   INT,
    @tvp_CategoryIds    [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS @IDS TABLE
(
    RECID BIGINT
)
AS
BEGIN
    DECLARE @tvp_ProductIds [crt].[RECORDIDTABLETYPE]
    INSERT INTO @tvp_ProductIds VALUES (0) -- Insert dummy record to satisfy API contract

    INSERT @IDS(RECID)
        SELECT DISTINCT pc.PRODUCT AS RECID
        FROM [crt].GETPRODUCTCATEGORIES(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, 0 /* @b_IsForwardLooking */, 0 /* @b_ProductIdsPassed */, @tvp_ProductIds, 1 /* @b_CategoryIdsPassed */, @tvp_CategoryIds) pc

    RETURN;
END


GO
PRINT N'Finished creating table function [crt].[SEARCHPRODUCTSBYCATEGORY]'
-- End creating table function [crt].[SEARCHPRODUCTSBYCATEGORY]


GRANT SELECT ON [crt].[SEARCHPRODUCTSBYCATEGORY] TO [UsersRole];
GO

GRANT SELECT ON [crt].[SEARCHPRODUCTSBYCATEGORY] TO [PublishersRole];
GO

-- Creating inline table function [crt].[SEARCHPRODUCTSBYITEMID]
PRINT N'Creating inline table function [crt].[SEARCHPRODUCTSBYITEMID]';

GO
IF OBJECT_ID(N'[crt].[SEARCHPRODUCTSBYITEMID]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[SEARCHPRODUCTSBYITEMID] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[SEARCHPRODUCTSBYITEMID].'
GO


ALTER FUNCTION [crt].[SEARCHPRODUCTSBYITEMID]
(
    @nvc_DataAreaId     NVARCHAR(4),
    @tvp_ItemIds        [crt].ITEMIDSEARCHTABLETYPE READONLY
)
RETURNS TABLE
RETURN
    -- Retrieve product identifiers for item identifiers.
    SELECT it.PRODUCT AS RECID
    FROM @tvp_ItemIds ids
    INNER JOIN [ax].INVENTTABLE it ON it.ITEMID = ids.ITEMID AND it.DATAAREAID = @nvc_DataAreaId
    WHERE ids.INVENTDIMID = ''

    UNION ALL

    -- Retrieve variant identifiers for inventory dimensions.
    SELECT idc.DISTINCTPRODUCTVARIANT AS RECID
    FROM @tvp_ItemIds ids
    INNER JOIN [ax].INVENTDIMCOMBINATION idc ON idc.ITEMID = ids.ITEMID AND idc.INVENTDIMID = ids.INVENTDIMID AND idc.DATAAREAID = @nvc_DataAreaId
    WHERE ids.INVENTDIMID != ''


GO
PRINT N'Finished creating inline table function [crt].[SEARCHPRODUCTSBYITEMID]'
-- End creating inline table function [crt].[SEARCHPRODUCTSBYITEMID]


GRANT SELECT ON [crt].[SEARCHPRODUCTSBYITEMID] TO [UsersRole];
GO

GRANT SELECT ON [crt].[SEARCHPRODUCTSBYITEMID] TO [PublishersRole];
GO

-- Creating inline table function [crt].[SEARCHPRODUCTSBYKEYWORD]
PRINT N'Creating inline table function [crt].[SEARCHPRODUCTSBYKEYWORD]';

GO
IF OBJECT_ID(N'[crt].[SEARCHPRODUCTSBYKEYWORD]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[SEARCHPRODUCTSBYKEYWORD] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[SEARCHPRODUCTSBYKEYWORD].'
GO


ALTER FUNCTION [crt].[SEARCHPRODUCTSBYKEYWORD]
(
    @bi_ChannelId           BIGINT,
    @dt_ChannelDate         DATE,
    @nvc_SearchCondition    NVARCHAR(4000),
    @nvc_LanguageId         NVARCHAR(7),
    @tvp_ProductIds         [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS TABLE
RETURN
    -- The SELECT below is to enable "universal" search from the cart page. The client
    -- may not know what the string represents, and so cannot make a decision
    -- as to which search criteria to use. Since this string will often be an
    -- item id, we have to expand the keyword search space (which is attributes
    -- only) to include the item ids as well.
    SELECT p.RECID
    FROM [ax].ECORESPRODUCT p
    INNER JOIN [ax].RETAILCHANNELTABLE RCT ON RCT.RECID = @bi_ChannelId
    INNER JOIN [ax].INVENTTABLE IT ON IT.PRODUCT = p.RECID AND CONTAINS(it.ITEMID, @nvc_SearchCondition) AND IT.DATAAREAID = RCT.INVENTLOCATIONDATAAREAID

    UNION

    SELECT lpavv.PRODUCT AS RECID
    FROM [crt].GETLIVEPRODUCTATTRIBUTEVALUE(@bi_ChannelId, @dt_ChannelDate, 0 /* @b_ProductIdsPassed */, @tvp_ProductIds, @tvp_ProductIds) lpavv
    INNER JOIN [ax].ECORESTEXTVALUE ertv ON ertv.RECID = lpavv.VALUE AND CONTAINS(ertv.TEXTVALUE, @nvc_SearchCondition)

    UNION

    SELECT EP.RECID
    FROM [ax].ECORESPRODUCT EP
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 1  -- ProductNumber
    JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW m ON m.ACTUALATTRIBUTE = rsa.ATTRIBUTE AND m.CHANNEL = @bi_ChannelId
    WHERE CONTAINS(ep.DISPLAYPRODUCTNUMBER, @nvc_SearchCondition)

    UNION

    SELECT EP.RECID
    FROM [ax].ECORESPRODUCT EP
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID IN (2, 4)  -- ProductName, ProductDescription
    JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW m ON m.ACTUALATTRIBUTE = rsa.ATTRIBUTE AND m.CHANNEL = @bi_ChannelId
    JOIN [ax].ECORESPRODUCTTRANSLATION erpt ON erpt.PRODUCT = ep.RECID
    WHERE erpt.LANGUAGEID = @nvc_LanguageId AND (CONTAINS(erpt.NAME, @nvc_SearchCondition) OR (CONTAINS(erpt.DESCRIPTION, @nvc_SearchCondition)))

    UNION

    SELECT EP.RECID
    FROM [ax].ECORESPRODUCT EP
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 3  -- SearchName
    JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW m ON m.ACTUALATTRIBUTE = rsa.ATTRIBUTE AND m.CHANNEL = @bi_ChannelId
    WHERE CONTAINS(EP.SEARCHNAME, @nvc_SearchCondition)

    UNION

    SELECT EPVDV.DISTINCTPRODUCTVARIANT AS RECID
    FROM [ax].ECORESPRODUCTVARIANTCOLOR EPVC
    JOIN [ax].ECORESPRODUCTVARIANTDIMENSIONVALUE EPVDV ON EPVDV.RECID = EPVC.RECID
    JOIN [ax].ECORESCOLOR EC ON EC.RECID = EPVC.COLOR AND CONTAINS(EC.NAME, @nvc_SearchCondition)
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 5  -- Color
    JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW m ON m.ACTUALATTRIBUTE = rsa.ATTRIBUTE AND m.CHANNEL = @bi_ChannelId

    UNION

    SELECT EPVDV.DISTINCTPRODUCTVARIANT AS RECID
    FROM [ax].ECORESPRODUCTVARIANTSTYLE EPVS
    JOIN [ax].ECORESPRODUCTVARIANTDIMENSIONVALUE EPVDV ON EPVDV.RECID = EPVS.RECID
    JOIN [ax].ECORESSTYLE EC ON EC.RECID = EPVS.STYLE AND CONTAINS(EC.NAME, @nvc_SearchCondition)
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 6  -- Style
    JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW m ON m.ACTUALATTRIBUTE = rsa.ATTRIBUTE AND m.CHANNEL = @bi_ChannelId

    UNION

    SELECT EPVDV.DISTINCTPRODUCTVARIANT AS RECID
    FROM [ax].ECORESPRODUCTVARIANTSIZE EPVS
    JOIN [ax].ECORESPRODUCTVARIANTDIMENSIONVALUE EPVDV ON EPVDV.RECID = EPVS.RECID
    JOIN [ax].ECORESSIZE EC ON EC.RECID = EPVS.SIZE AND CONTAINS(EC.NAME, @nvc_SearchCondition)
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 7  -- Size
    JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW m ON m.ACTUALATTRIBUTE = rsa.ATTRIBUTE AND m.CHANNEL = @bi_ChannelId

    UNION

    SELECT EPVDV.DISTINCTPRODUCTVARIANT AS RECID
    FROM [ax].ECORESPRODUCTVARIANTCONFIGURATION EPVC
    JOIN [ax].ECORESPRODUCTVARIANTDIMENSIONVALUE EPVDV ON EPVDV.RECID = EPVC.RECID
    JOIN [ax].ECORESCONFIGURATION EC ON EC.RECID = EPVC.CONFIGURATION AND CONTAINS(EC.NAME, @nvc_SearchCondition)
    JOIN [ax].RETAILSTANDARDATTRIBUTE RSA ON RSA.STANDARDATTRIBUTEID = 8  -- Configuration
    JOIN [crt].PUBPRODUCTATTRIBUTECHANNELMETADATAVIEW m ON m.ACTUALATTRIBUTE = rsa.ATTRIBUTE AND m.CHANNEL = @bi_ChannelId


GO
PRINT N'Finished creating inline table function [crt].[SEARCHPRODUCTSBYKEYWORD]'
-- End creating inline table function [crt].[SEARCHPRODUCTSBYKEYWORD]


GRANT SELECT ON [crt].[SEARCHPRODUCTSBYKEYWORD] TO [UsersRole];
GO

GRANT SELECT ON [crt].[SEARCHPRODUCTSBYKEYWORD] TO [PublishersRole];
GO

-- Creating table function [crt].[GETINCLUDEDDATERANGES]
PRINT N'Creating table function [crt].[GETINCLUDEDDATERANGES]';

GO
IF OBJECT_ID(N'[crt].[GETINCLUDEDDATERANGES]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETINCLUDEDDATERANGES] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETINCLUDEDDATERANGES].'
GO


-- Excludes one date range from another.
-- Returns either zero (exclude fully covers), one (partially covered or disjoint) or two date ranges (split).
-- The excluded dates are exclusive so returned ranges are moved up/down one day on the boundaries.
ALTER FUNCTION [crt].[GETINCLUDEDDATERANGES]
(
    @dt_IncludedFrom DATE,
    @dt_IncludedTo DATE,
    @dt_ExcludedFrom DATE,
    @dt_ExcludedTo DATE
)
RETURNS @DATERANGES TABLE
(
    VALIDFROM DATE NOT NULL,
    VALIDTO DATE NOT NULL
)
AS BEGIN
    -- No excludes specified? Return the original date range.
    IF (@dt_ExcludedFrom IS NULL AND @dt_ExcludedTo IS NULL)
        INSERT @DATERANGES
        SELECT @dt_IncludedFrom, @dt_IncludedTo

    -- Excluded date range covers entire included range. Return nothing.
    IF (@dt_ExcludedFrom <= @dt_IncludedFrom AND @dt_ExcludedTo >= @dt_IncludedTo)
        RETURN

    -- Excluded start is within included range.
    IF (@dt_ExcludedFrom > @dt_IncludedFrom AND @dt_ExcludedFrom <= @dt_IncludedTo)
        INSERT @DATERANGES
        SELECT @dt_IncludedFrom, DATEADD(d, -1, @dt_ExcludedFrom)

    -- Excluded end is within include range.
    IF (@dt_ExcludedTo >= @dt_IncludedFrom AND @dt_ExcludedTo < @dt_IncludedTo)
        INSERT @DATERANGES
        SELECT DATEADD(d, 1, @dt_ExcludedTo), @dt_IncludedTo

    -- Excluded date range is disjoint from included range. Return original range.
    IF (@dt_ExcludedTo < @dt_IncludedFrom OR @dt_ExcludedFrom > @dt_IncludedTo)
        INSERT @DATERANGES
        SELECT @dt_IncludedFrom, @dt_IncludedTo

    RETURN
END;


GO
PRINT N'Finished creating table function [crt].[GETINCLUDEDDATERANGES]'
-- End creating table function [crt].[GETINCLUDEDDATERANGES]


GRANT SELECT ON [crt].[GETINCLUDEDDATERANGES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETINCLUDEDDATERANGES] TO [PublishersRole];
GO

-- Creating table function [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES]
PRINT N'Creating table function [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES].'
GO


ALTER FUNCTION [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES]
(
    @watermark AS [crt].[PRODUCTCHANGETRACKINGANCHORSET] READONLY 
)
RETURNS @changedAttributeValues TABLE
(
    RECID BIGINT,
    SEQUENCE BIGINT
)
AS
BEGIN

-- retain product ids
INSERT @changedAttributeValues(RECID, SEQUENCE)

-- get ids of changed product records
SELECT
erp.RECID,
erp.ROWVERSION AS SEQUENCE 
FROM ax.ECORESPRODUCT erp
    JOIN @watermark w ON erp.ROWVERSION > w.ECORESPRODUCT 

UNION 

-- get ids of products whose instance values have changed directly
SELECT 
erpiv.PRODUCT AS RECID,
erpiv.ROWVERSION AS SEQUENCE
FROM ax.ECORESPRODUCTINSTANCEVALUE erpiv
    JOIN @watermark w ON erpiv.ROWVERSION > w.ECORESPRODUCTINSTANCEVALUE 

UNION

-- get ids of products whose instance values have changed indirectly
SELECT
erpiv.PRODUCT,
erpiv.ROWVERSION AS SEQUENCE 
FROM ax.ECORESPRODUCTINSTANCEVALUE erpiv
INNER JOIN (

-- get ids of instance values which have changed directly
SELECT
eriv.RECID
FROM ax.ECORESINSTANCEVALUE eriv
        JOIN @watermark w ON eriv.ROWVERSION > w.ECORESINSTANCEVALUE 

UNION

-- get ids of instance values which have changed indirectly
SELECT 
eriv.RECID
FROM ax.ECORESINSTANCEVALUE eriv
INNER JOIN (

-- get ids of attribute values which have changed directly
SELECT 
erav.INSTANCEVALUE
FROM ax.ECORESATTRIBUTEVALUE erav
            JOIN @watermark w ON erav.ROWVERSION > w.ECORESATTRIBUTEVALUE 

UNION

-- get ids of attribe values which have changed indirectly
SELECT 
erav.INSTANCEVALUE
FROM ax.ECORESATTRIBUTEVALUE erav
INNER JOIN (

-- get ids of values which have changed directly
SELECT 
erv.RECID
FROM ax.ECORESVALUE erv
                    JOIN @watermark w ON erv.ROWVERSION > w.ECORESVALUE 

UNION

-- get ids of changed values of specific types
SELECT 
erv.RECID
FROM ax.ECORESVALUE erv
inner join ax.ECORESBOOLEANVALUE erbv on erbv.RECID = erv.RECID
WHERE erbv.ROWVERSION > (SELECT ECORESBOOLEANVALUE FROM @watermark)

UNION 

-- get ids of changed values of specific types
SELECT  
erv.RECID
FROM ax.ECORESVALUE erv
inner join ax.ECORESDATETIMEVALUE erbv on erbv.RECID = erv.RECID
WHERE erbv.ROWVERSION > (SELECT ECORESDATETIMEVALUE FROM @watermark)

UNION 

-- get ids of changed values of specific types
SELECT  
erv.RECID
FROM ax.ECORESVALUE erv
inner join ax.ECORESFLOATVALUE erbv on erbv.RECID = erv.RECID
WHERE erbv.ROWVERSION > (SELECT ECORESFLOATVALUE FROM @watermark)

UNION 

-- get ids of changed values of specific types
SELECT  
erv.RECID
FROM ax.ECORESVALUE erv
inner join ax.ECORESINTVALUE erbv on erbv.RECID = erv.RECID
WHERE erbv.ROWVERSION > (SELECT ECORESINTVALUE FROM @watermark)

UNION 

-- get ids of changed values of specific types
SELECT  
erv.RECID
FROM ax.ECORESVALUE erv
inner join ax.ECORESTEXTVALUE erbv on erbv.RECID = erv.RECID
WHERE erbv.ROWVERSION > (SELECT ECORESTEXTVALUE FROM @watermark)

UNION 

-- get ids of changed values of specific types
SELECT  
erv.RECID
FROM ax.ECORESVALUE erv
inner join ax.ECORESCURRENCYVALUE erbv on erbv.RECID = erv.RECID
WHERE erbv.ROWVERSION > (SELECT ECORESCURRENCYVALUE FROM @watermark)

UNION 

-- get ids of changed values of specific types
SELECT  
erv.RECID
FROM ax.ECORESVALUE erv
inner join ax.ECORESREFERENCEVALUE erbv on erbv.RECID = erv.RECID
WHERE erbv.ROWVERSION > (SELECT ECORESREFERENCEVALUE FROM @watermark)

) AS changedValues ON erav.VALUE = changedValues.RECID
) AS changedAttributeValues ON eriv.RECID = changedAttributeValues.INSTANCEVALUE
) AS changedInstanceValues ON erpiv.RECID = changedInstanceValues.RECID

RETURN;
END


GO
PRINT N'Finished creating table function [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES]'
-- End creating table function [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES]


GRANT SELECT ON [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES]
PRINT N'Creating inline table function [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTIDSWITHCATEGORYCHANGES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES].'
GO


ALTER FUNCTION [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES]
(
    @watermark AS [crt].[PRODUCTCHANGETRACKINGANCHORSET] READONLY 
)
RETURNS TABLE
RETURN
SELECT 
erp.RECID,
erp.ROWVERSION AS SEQUENCE
FROM ax.ECORESPRODUCT erp
INNER JOIN ax.ECORESPRODUCTCATEGORY erpc ON erpc.PRODUCT = erp.RECID
WHERE erpc.ROWVERSION > (SELECT ECORESPRODUCTCATEGORY FROM @watermark)



GO
PRINT N'Finished creating inline table function [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES]'
-- End creating inline table function [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES]


GRANT SELECT ON [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTIDSWITHCATEGORYCHANGES] TO [PublishersRole];
GO

-- Creating table function [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES]
PRINT N'Creating table function [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES].'
GO


ALTER FUNCTION [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES]
(
    @watermark AS [crt].[PRODUCTCHANGETRACKINGANCHORSET] READONLY 
)
RETURNS @changedAttributeValues TABLE
(
    RECID BIGINT,
    SEQUENCE BIGINT
)
AS
BEGIN
RETURN;
END


GO
PRINT N'Finished creating table function [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES]'
-- End creating table function [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES]


GRANT SELECT ON [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTIDSWITHCOMPOSITIONCHANGES] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES]
PRINT N'Creating inline table function [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES].'
GO


ALTER FUNCTION [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES]
(
    @watermark AS [crt].[PRODUCTCHANGETRACKINGANCHORSET] READONLY 
)
RETURNS TABLE
RETURN
-- get ids of changed product records
SELECT
rppav.PRODUCT AS RECID,
rppav.ROWVERSION AS SEQUENCE 
FROM ax.RETAILPUBPRODUCTATTRIBUTEVALUE rppav
    JOIN @watermark w ON rppav.ROWVERSION > w.RETAILPUBPRODUCTATTRIBUTEVALUE 


GO
PRINT N'Finished creating inline table function [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES]'
-- End creating inline table function [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES]


GRANT SELECT ON [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES] TO [PublishersRole];
GO

-- Creating table function [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES]
PRINT N'Creating table function [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES].'
GO


ALTER FUNCTION [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES]
(
    @watermark AS [crt].[PRODUCTCHANGETRACKINGANCHORSET] READONLY 
)
RETURNS @changedAttributeValues TABLE
(
    RECID BIGINT,
    SEQUENCE BIGINT
)
AS
BEGIN

-- retain product ids
INSERT @changedAttributeValues(RECID, SEQUENCE)

    -- get ids of products whose instance values have changed directly
SELECT
rpcp.PRODUCT AS RECID,
rpcp.ROWVERSION AS SEQUENCE
FROM ax.RETAILPUBCATALOGPRODUCT rpcp
    JOIN @watermark w ON w.RETAILPUBCATALOGPRODUCT IS NOT NULL AND rpcp.ROWVERSION > ISNULL(w.RETAILPUBCATALOGPRODUCT, 0)

UNION 

-- get ids of products whose category associations have changed
SELECT
rpcp.PRODUCT,
rpcp.ROWVERSION AS SEQUENCE 
FROM ax.RETAILPUBCATALOGPRODUCT rpcp
INNER JOIN ax.RETAILPUBCATALOGPRODUCTCATEGORY rpcpc ON rpcpc.CATALOGPRODUCT = rpcp.ORIGIN 
WHERE rpcpc.ROWVERSION > (SELECT RETAILPUBCATALOGPRODUCTCATEGORY FROM @watermark)

UNION

-- get ids of products whose catalog relations have changed 
SELECT
rpcp.PRODUCT AS RECID,
rpcp.ROWVERSION AS SEQUENCE
FROM ax.RETAILPUBCATALOGPRODUCT rpcp
INNER JOIN ax.RETAILPUBCATALOGPRODUCTRELATION rpcpr ON rpcpr.CATALOGPRODUCT = rpcp.ORIGIN
WHERE rpcpr.ROWVERSION > (SELECT RETAILPUBCATALOGPRODUCTRELATION FROM @watermark)

UNION

-- get ids of products whose catalog relation exclusions have changed 
SELECT
rpcp.PRODUCT AS RECID,
rpcp.ROWVERSION AS SEQUENCE
FROM ax.RETAILPUBCATALOGPRODUCT rpcp
INNER JOIN ax.RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION rpcpre ON rpcpre.CATALOGPRODUCT = rpcp.ORIGIN
WHERE rpcpre.ROWVERSION > (SELECT RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION FROM @watermark)

RETURN;
END


GO
PRINT N'Finished creating table function [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES]'
-- End creating table function [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES]


GRANT SELECT ON [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES]
PRINT N'Creating inline table function [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES].'
GO


ALTER FUNCTION [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES]
(
    @watermark AS [crt].[PRODUCTCHANGETRACKINGANCHORSET] READONLY 
)
RETURNS TABLE
RETURN

SELECT 
erp.RECID,
erp.ROWVERSION AS SEQUENCE
FROM ax.ECORESPRODUCT erp
INNER JOIN ax.ECORESPRODUCTTRANSLATION erpt ON erpt.PRODUCT = erp.RECID
WHERE erpt.ROWVERSION > (SELECT ECORESPRODUCTTRANSLATION FROM @watermark)


GO
PRINT N'Finished creating table function [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES]'
-- End creating table function [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES]


GRANT SELECT ON [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTIDSWITHTRANSLATIONCHANGES] TO [PublishersRole];
GO

-- Creating table function [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS]
PRINT N'Creating table function [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS]';

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS].'
GO


ALTER FUNCTION [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS]
(
@bi_ChannelId BIGINT
)
RETURNS @watermark TABLE
(
CHANNELID BIGINT,
ECORESPRODUCT BIGINT,
ECORESPRODUCTINSTANCEVALUE BIGINT,
ECORESINSTANCEVALUE BIGINT,
ECORESATTRIBUTE BIGINT,
ECORESATTRIBUTEVALUE BIGINT,
ECORESVALUE BIGINT,
ECORESBOOLEANVALUE BIGINT,
ECORESDATETIMEVALUE BIGINT,
ECORESCURRENCYVALUE BIGINT,
ECORESFLOATVALUE BIGINT,
ECORESINTVALUE BIGINT,
ECORESREFERENCEVALUE BIGINT,
ECORESTEXTVALUE BIGINT,
ECORESTEXTVALUETRANSLATION BIGINT,
ECORESPRODUCTTRANSLATION BIGINT,
ECORESPRODUCTVARIANTCOLOR BIGINT,
ECORESPRODUCTVARIANTCONFIGURATION BIGINT,
ECORESPRODUCTVARIANTDIMENSIONVALUE BIGINT,
ECORESPRODUCTVARIANTSIZE BIGINT,
ECORESPRODUCTVARIANTSTYLE BIGINT,
ECORESCOLOR BIGINT,
ECORESCONFIGURATION BIGINT,
ECORESSIZE BIGINT,
ECORESSTYLE BIGINT,
ECORESATTRIBUTEGROUPATTRIBUTE BIGINT,
ECORESCATEGORYATTRIBUTEGROUP BIGINT,
ECORESCATEGORYATTRIBUTELOOKUP BIGINT,
ECORESDISTINCTPRODUCTVARIANT BIGINT,
ECORESPRODUCTCATEGORY BIGINT,
RETAILCATEGORYCONTAINMENTLOOKUP BIGINT,
RETAILPUBCATALOGPRODUCT BIGINT,
RETAILPUBCATALOGPRODUCTCATEGORY BIGINT,
RETAILPUBCATALOGPRODUCTRELATION BIGINT,
RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION BIGINT,
RETAILPUBINTERNALORGATTRIBUTEGROUP BIGINT,
RETAILPUBINTORGINHERITANCEEXPLODED BIGINT,
RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA BIGINT,
RETAILPUBPRODUCTATTRIBUTEVALUE BIGINT,
RETAILPUBRETAILCHANNELTABLE BIGINT,
RETAILSHAREDPARAMETERS BIGINT,
RETAILSTANDARDATTRIBUTE BIGINT,
UNITOFMEASURE BIGINT
)
AS
BEGIN

INSERT @watermark(
CHANNELID,
ECORESPRODUCT,
ECORESPRODUCTINSTANCEVALUE,
ECORESINSTANCEVALUE,
ECORESATTRIBUTE,
ECORESATTRIBUTEVALUE,
ECORESVALUE,
ECORESBOOLEANVALUE,
ECORESDATETIMEVALUE,
ECORESCURRENCYVALUE,
ECORESFLOATVALUE,
ECORESINTVALUE,
ECORESREFERENCEVALUE,
ECORESTEXTVALUE,
ECORESTEXTVALUETRANSLATION,
ECORESPRODUCTTRANSLATION,
ECORESPRODUCTVARIANTCOLOR,
ECORESPRODUCTVARIANTCONFIGURATION,
ECORESPRODUCTVARIANTDIMENSIONVALUE,
ECORESPRODUCTVARIANTSIZE,
ECORESPRODUCTVARIANTSTYLE,
ECORESCOLOR,
ECORESCONFIGURATION,
ECORESSIZE,
ECORESSTYLE,
ECORESATTRIBUTEGROUPATTRIBUTE,
ECORESCATEGORYATTRIBUTEGROUP,
ECORESCATEGORYATTRIBUTELOOKUP,
ECORESDISTINCTPRODUCTVARIANT,
ECORESPRODUCTCATEGORY,
RETAILCATEGORYCONTAINMENTLOOKUP,
RETAILPUBCATALOGPRODUCT,
RETAILPUBCATALOGPRODUCTCATEGORY,
RETAILPUBCATALOGPRODUCTRELATION,
RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION,
RETAILPUBINTERNALORGATTRIBUTEGROUP,
RETAILPUBINTORGINHERITANCEEXPLODED,
RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA,
RETAILPUBPRODUCTATTRIBUTEVALUE,
RETAILPUBRETAILCHANNELTABLE,
RETAILSHAREDPARAMETERS,
RETAILSTANDARDATTRIBUTE,
UNITOFMEASURE
)
VALUES (
@bi_ChannelId,
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCT), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTINSTANCEVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESINSTANCEVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESATTRIBUTE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESATTRIBUTEVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESBOOLEANVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESDATETIMEVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESCURRENCYVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESFLOATVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESINTVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESREFERENCEVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESTEXTVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESTEXTVALUETRANSLATION), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTTRANSLATION), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTVARIANTCOLOR), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTVARIANTCONFIGURATION), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTVARIANTDIMENSIONVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTVARIANTSIZE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTVARIANTSTYLE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESCOLOR), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESCONFIGURATION), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESSIZE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESSTYLE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESATTRIBUTEGROUPATTRIBUTE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESCATEGORYATTRIBUTEGROUP), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESCATEGORYATTRIBUTELOOKUP), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESDISTINCTPRODUCTVARIANT), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.ECORESPRODUCTCATEGORY), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILCATEGORYCONTAINMENTLOOKUP), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBCATALOGPRODUCT), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBCATALOGPRODUCTCATEGORY), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBCATALOGPRODUCTRELATION), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBINTERNALORGATTRIBUTEGROUP), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBINTORGINHERITANCEEXPLODED), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBPRODUCTATTRIBUTEVALUE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILPUBRETAILCHANNELTABLE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILSHAREDPARAMETERS), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.RETAILSTANDARDATTRIBUTE), 0),
ISNULL((SELECT MAX(ROWVERSION) FROM ax.UNITOFMEASURE), 0)
)

RETURN;
END


GO
PRINT N'Finished creating table function [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS]'
-- End creating table function [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS]


GRANT SELECT ON [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETRETAILTRANSACTIONCATEGORIES]
PRINT N'Creating inline table function [crt].[GETRETAILTRANSACTIONCATEGORIES]';

GO
IF OBJECT_ID(N'[crt].[GETRETAILTRANSACTIONCATEGORIES]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETRETAILTRANSACTIONCATEGORIES] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETRETAILTRANSACTIONCATEGORIES].'
GO


-- Gets the retail transaction information for items and retail categories. Used by GetTop10ProductsReport.
ALTER FUNCTION [crt].[GETRETAILTRANSACTIONCATEGORIES]
(
    @bi_ChannelId   BIGINT,
    @nvc_DataAreaId NVARCHAR(4)
)
RETURNS TABLE
RETURN
    WITH RETAILTRANSACTIONSALESTRANSBATCH AS
    (
        SELECT DISTINCT
            ROW_NUMBER() OVER (PARTITION BY rta.SALESORDERID,it.ITEMID, rta.TYPE ORDER BY rta.TRANSACTIONID DESC) AS ROWNO
            ,rta.[SALESORDERID]
            ,rta.[TYPE]
            ,rtt.[NETAMOUNT]
            ,rtt.[TAXAMOUNT]
            ,rta.[PAYMENTAMOUNT]
            ,it.[ITEMID]
            ,erpt.[NAME] AS PRODUCTNAME
            ,it.[PRODUCT]
            ,rta.[TRANSDATE]
            ,rta.[STORE]
            ,rtt.[QTY]
            ,rta.[CHANNEL]
            ,rta.[TRANSACTIONID]
        FROM [ax].RETAILTRANSACTIONTABLE rta WITH (NOLOCK)
        INNER JOIN [ax].RETAILTRANSACTIONSALESTRANS rtt WITH (NOLOCK) ON rtt.TERMINALID = rta.TERMINAL AND rtt.TRANSACTIONID = rta.TRANSACTIONID AND rtt.CHANNEL = rta.CHANNEL
        INNER JOIN [crt].CHANNELLANGUAGESVIEW clv ON clv.CHANNEL = @bi_ChannelId AND clv.ISDEFAULT = 1 -- Use default channel language
        INNER JOIN [ax].INVENTTABLE it (NOLOCK) ON it.ITEMID = rtt.ITEMID AND it.DATAAREAID = @nvc_DataAreaId
        INNER JOIN [ax].ECORESPRODUCTTRANSLATION erpt ON erpt.PRODUCT = it.PRODUCT AND erpt.LANGUAGEID = clv.LANGUAGEID
        WHERE rta.CHANNEL = @bi_ChannelId AND rta.TYPE = 2 OR rta.TYPE = 19 OR rta.TYPE = 14 -- TYPE 2 SALES TRANSACTION TYPE 19 CUSTOMER ORDER TYPE 14 SALES ORDER
    )
    SELECT
         TYPE,
         NETAMOUNT,
         TAXAMOUNT,
         PAYMENTAMOUNT,
         ITEMID,
         PRODUCTNAME,
         PRODUCT,
         TRANSDATE,
         STORE,
         QTY,
         CHANNEL,
         TRANSACTIONID
    FROM RETAILTRANSACTIONSALESTRANSBATCH
    WHERE
        (ROWNO = 1 OR SALESORDERID IS NULL OR LEN(LTRIM(RTRIM(SALESORDERID))) = 0)
        -- TO EXCLUDE VOIDED TRANSACTION BUT INCLUDE RECALLED ORDER
        AND ((PAYMENTAMOUNT <> 0.00) OR (PAYMENTAMOUNT = 0.00 AND LEN(LTRIM(RTRIM(SALESORDERID))) > 0))
        -- TO EXCLUDE CANCELLED ORDER TRANSACTION
        AND (NOT(PAYMENTAMOUNT < 0.00 AND QTY < 0.00))


GO
PRINT N'Finished creating inline table function [crt].[GETRETAILTRANSACTIONCATEGORIES]'
-- End creating inline table function [crt].[GETRETAILTRANSACTIONCATEGORIES]


GRANT SELECT ON [crt].[GETRETAILTRANSACTIONCATEGORIES] TO [UsersRole];
GO

-- Creating table function [crt].[FINDPRODUCTSBYKEYWORD]
PRINT N'Creating table function [crt].[FINDPRODUCTSBYKEYWORD]';

GO
IF OBJECT_ID(N'[crt].[FINDPRODUCTSBYKEYWORD]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[FINDPRODUCTSBYKEYWORD] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[FINDPRODUCTSBYKEYWORD].'
GO


ALTER FUNCTION [crt].[FINDPRODUCTSBYKEYWORD]
(
    @bi_ChannelId           BIGINT,
    @dt_ChannelDate         DATE,
    @nvc_SearchCondition    NVARCHAR(4000),
    @nvc_LanguageId         NVARCHAR(7)
)
RETURNS @IDS TABLE
(
    RECID BIGINT
)
AS
BEGIN
    DECLARE @tvp_ProductIds   [crt].[RECORDIDTABLETYPE]

    -- This dummy non existing value is needed for normal operation of the function SearchProductsByKeywords
    INSERT INTO @tvp_ProductIds VALUES (0)

    INSERT @IDS
    SELECT RECID
    FROM [crt].SEARCHPRODUCTSBYKEYWORD(@bi_ChannelId, @dt_ChannelDate, @nvc_SearchCondition, @nvc_LanguageId, @tvp_ProductIds)

    RETURN;
END


GO
PRINT N'Finished creating table function [crt].[FINDPRODUCTSBYKEYWORD]'
-- End creating table function [crt].[FINDPRODUCTSBYKEYWORD]


GRANT SELECT ON [crt].[FINDPRODUCTSBYKEYWORD] TO [UsersRole];
GO

GRANT SELECT ON [crt].[FINDPRODUCTSBYKEYWORD] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL]
PRINT N'Creating inline table function [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL]';

GO
IF OBJECT_ID(N'[crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL].'
GO


-- Returns catalogs published to the specified channel.
ALTER FUNCTION [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL]
(
    @bi_ChannelId       BIGINT
)
RETURNS TABLE
RETURN
    SELECT
        pccv.[CATALOG],
        rpct.[FRIENDLYNAME] AS [NAME],
        rpct.[DESCRIPTION],
        rpct.[LANGUAGE],
        rpct.[IMAGE],
        rpc.[ENABLESNAPSHOT],
        rpc.[PUBLISHEDVALIDFROM] AS [VALIDFROM],
        rpc.[PUBLISHEDVALIDTO] AS [VALIDTO],
        rpc.[CREATEDDATETIME],
        rpc.[MODIFIEDDATETIME],
        rpc.[PUBLISHEDDATETIME]
    FROM crt.PUBCATALOGCHANNELVIEW pccv
        INNER JOIN ax.RETAILPUBCATALOG rpc ON rpc.[ORIGIN] = pccv.[CATALOG]
        INNER JOIN ax.RETAILPUBCATALOGTRANSLATION rpct ON rpct.[CATALOG] = pccv.[CATALOG]
    WHERE pccv.[CHANNEL] = @bi_ChannelId


GO
PRINT N'Finished creating inline table function [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL]'
-- End creating inline table function [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL]


GRANT SELECT ON [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETCATALOGSPUBLISHEDTOACTIVECHANNEL] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETSALESORDER]
PRINT N'Creating inline table function [crt].[GETSALESORDER]';

GO
IF OBJECT_ID(N'[crt].[GETSALESORDER]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETSALESORDER] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETSALESORDER].'
GO


-- Gets catalog channel product's hieararchy
ALTER FUNCTION [crt].[GETSALESORDER]
(
    @nvc_CustomerName NVARCHAR(400)
)
RETURNS TABLE
RETURN
    SELECT
        RT.CHANNEL AS 'CHANNELID'
        ,RT.TRANSACTIONID AS 'TRANSACTIONID'
        ,CASE
                WHEN (RT.SALESORDERID <> '') THEN RT.SALESORDERID
                ELSE COALESCE(OS.SALESID, '')
        END AS 'SALESID'
        ,RT.CREATEDDATETIME AS 'ORDERPLACEDDATE'
        ,(RT.GROSSAMOUNT * -1.0) AS 'GROSSAMOUNT'
        ,CASE WHEN RT.TYPE = 7 THEN    -- TYPE = 7: TenderDeclaration
(
SELECT SUM(TD.AMOUNTTENDERED)
FROM [ax].RETAILTRANSACTIONTENDERDECLARATIONTRANS TD
WHERE 
TD.TRANSACTIONID = RT.TRANSACTIONID
AND TD.TERMINAL = RT.TERMINAL
AND TD.DATAAREAID = RT.DATAAREAID
AND TD.TRANSACTIONSTATUS = 0    -- 0: Normal status transaction
AND TD.CHANNEL = RT.CHANNEL
)
WHEN RT.TYPE = 16 THEN    -- TYPE = 16: BankDrop
(
SELECT SUM(B.AMOUNTTENDERED)
FROM [ax].RETAILTRANSACTIONBANKEDTENDERTRANS B
WHERE 
B.TRANSACTIONID = RT.TRANSACTIONID
AND B.TERMINAL = RT.TERMINAL
AND B.DATAAREAID = RT.DATAAREAID
AND B.TRANSACTIONSTATUS = 0    -- 0: Normal status transaction
AND B.CHANNEL = RT.CHANNEL
)
WHEN RT.TYPE = 17 THEN    -- TYPE = 17: SafeDrop
(
SELECT SUM(S.AMOUNTTENDERED)
FROM [ax].RETAILTRANSACTIONSAFETENDERTRANS S
WHERE 
S.TRANSACTIONID = RT.TRANSACTIONID
AND S.TERMINAL = RT.TERMINAL
AND S.DATAAREAID = RT.DATAAREAID
AND S.TRANSACTIONSTATUS = 0    -- 0: Normal status transaction
AND S.CHANNEL = RT.CHANNEL
)
WHEN RT.TYPE = 3 THEN    -- TYPE = 3: Payment
(
SELECT SUM(P.AMOUNTTENDERED)
FROM [ax].RETAILTRANSACTIONPAYMENTTRANS P
WHERE
P.TRANSACTIONID = RT.TRANSACTIONID
AND P.TERMINAL = RT.TERMINAL
AND P.DATAAREAID  = RT.DATAAREAID
AND P.TRANSACTIONSTATUS = 0    -- 0: Normal status transaction
AND P.CHANNEL = RT.CHANNEL
)
ELSE (RT.GROSSAMOUNT * -1.0) END AS 'TOTALAMOUNT'
        ,RT.PAYMENTAMOUNT AS 'AMOUNTPAID'
        ,RT.TERMINAL AS 'TERMINAL'
        ,RT.STORE AS 'STORE'
        ,RT.STAFF AS 'STAFF'
        ,RT.CUSTACCOUNT AS 'CUSTOMERID'
        ,RT.RECEIPTEMAIL AS 'RECEIPTEMAIL'
        ,RT.TYPE
        ,RT.DISCAMOUNT AS 'DISCOUNTAMOUNT'
        ,ISNULL(AT.DELIVERYNAME,DPT.NAME) AS 'NAME'
        ,COALESCE((
            SELECT SUM(TAXAMOUNT * -1.0)
            FROM [ax].RETAILTRANSACTIONSALESTRANS RTST
            WHERE
                RTST.TRANSACTIONID = RT.TRANSACTIONID
                AND RTST.TERMINALID = RT.TERMINAL
                AND RTST.STORE = RT.STORE
                AND RTST.CHANNEL = RT.CHANNEL
AND RTST.TRANSACTIONSTATUS <> 1-- Excludes the voided line
), 0) AS 'TAXAMOUNT'
,COALESCE((
            SELECT TOP 1 ISINCLUDEDINPRICE
            FROM [ax].RETAILTRANSACTIONTAXTRANS TT
            WHERE
                TT.TRANSACTIONID = RT.TRANSACTIONID
                AND TT.TERMINALID = RT.TERMINAL
                AND TT.STOREID = RT.STORE
                AND TT.CHANNEL = RT.CHANNEL ), 0) AS 'ISTAXINCLUDEDINPRICE'
        ,COALESCE((
            SELECT SUM(CALCULATEDAMOUNT)
            FROM [ax].RETAILTRANSACTIONMARKUPTRANS MT
            WHERE
                MT.TRANSACTIONID = RT.TRANSACTIONID
                AND MT.TERMINALID = RT.TERMINAL
                AND MT.STORE = RT.STORE
                AND MT.CHANNEL = RT.CHANNEL), 0) AS 'CHARGEAMOUNT'
        ,RT.CHANNELREFERENCEID AS 'CHANNELREFERENCEID'
        ,RT.INVENTLOCATIONID AS 'INVENTLOCATIONID'
        ,RT.INVENTSITEID AS 'INVENTSITEID'
        ,RT.DLVMODE AS 'DELIVERYMODE'
        ,RT.SHIPPINGDATEREQUESTED AS 'REQUESTEDDELIVERYDATE'
        ,RT.LOGISTICSPOSTALADDRESS AS 'LOGISTICSPOSTALADDRESS'
        ,RT.RECEIPTID AS 'RECEIPTID'
        ,RT.LOYALTYCARDID AS 'LOYALTYCARDID'
        ,RT.ENTRYSTATUS AS 'ENTRYSTATUS'
,CASE
        WHEN (AT.EMAIL IS NOT NULL AND AT.EMAIL <> '') THEN AT.EMAIL
                WHEN (RT.RECEIPTEMAIL IS NOT NULL AND RT.RECEIPTEMAIL <> '') THEN RT.RECEIPTEMAIL
                ELSE CT.EMAIL
         END  AS 'EMAIL'
        ,ISNULL(AT.PHONE,'') AS 'PHONE'
        ,ISNULL(OS.STATUS, 0) AS 'STATUS'
        ,DATEADD(second, RT.TRANSTIME, CAST(RT.TRANSDATE AS DATETIME)) AS 'BEGINDATETIME'
        ,RT.BUSINESSDATE
        ,RT.STATEMENTCODE
        ,RT.COMMENT AS 'COMMENT'
        ,CO.CANCELLATIONCHARGE AS 'CANCELLATIONCHARGE'
        ,CO.DEPOSITOVERRIDE AS 'DEPOSITOVERRIDE'
        ,CO.REQUIREDDEPOSIT AS 'REQUIREDDEPOSIT'
        ,CO.CALCULATEDDEPOSIT AS 'CALCULATEDDEPOSIT'
        ,CO.PREPAYMENTPAID AS 'PREPAYMENTPAID'
        ,CO.PREPAYMENTINVOICED AS 'PREPAYMENTINVOICED'
,ISNULL((
SELECT TOP 1 1 AS 'HASREDEEMLINE' FROM [ax].RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS RPT
WHERE RPT.DATAAREAID = RT.DATAAREAID
AND RPT.TRANSACTIONID = RT.TRANSACTIONID
                AND RPT.TERMINALID = RT.TERMINAL
                AND RPT.STOREID = RT.STORE
                AND RPT.CHANNEL = RT.CHANNEL
AND RPT.ENTRYTYPE = 2), 0) AS 'HASLOYALTYPAYMENT' -- EntryType 2 is Redeem. HASLOYALTYPAYMENT = 1 if true, 0 if false.
    FROM [ax].RETAILTRANSACTIONTABLE RT
    LEFT JOIN [ax].RETAILTRANSACTIONORDERSTATUS OS ON
        OS.TRANSACTIONID = RT.TRANSACTIONID
        AND OS.TERMINAL = RT.TERMINAL
        AND OS.STORE = RT.STORE
        AND OS.CHANNEL = RT.CHANNEL
    LEFT JOIN [ax].RETAILTRANSACTIONADDRESSTRANS AT ON
        AT.TRANSACTIONID = RT.TRANSACTIONID
        AND AT.TERMINAL = RT.TERMINAL
        AND AT.STORE = RT.STORE
        AND AT.CHANNEL = RT.CHANNEL
        AND AT.SALELINENUM = 0      -- SaleLineNum 0 = Header level address
    LEFT JOIN [crt].[CUSTOMERORDERTRANSACTION] CO ON
        CO.CHANNEL = RT.CHANNEL
        AND CO.STORE = RT.STORE
        AND CO.TERMINAL = RT.TERMINAL
        AND CO.TRANSACTIONID = RT.TRANSACTIONID
        AND CO.DATAAREAID = RT.DATAAREAID
   LEFT JOIN [crt].[CUSTOMERSVIEW] CT ON CT.ACCOUNTNUMBER = RT.CUSTACCOUNT
        AND CT.DATAAREAID = RT.DATAAREAID
    LEFT JOIN [ax].DIRPARTYTABLE DPT ON CT.PARTY = DPT.RECID
    WHERE @nvc_CustomerName = '""' OR CONTAINS(AT.DELIVERYNAME, @nvc_CustomerName) OR CONTAINS(DPT.NAME, @nvc_CustomerName)


GO
PRINT N'Finished creating inline table function [crt].[GETSALESORDER]'
-- End creating inline table function [crt].[GETSALESORDER]


GRANT SELECT ON [crt].[GETSALESORDER] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETSALESORDER] TO [PublishersRole];
GO

-- Creating scalar function [crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS]
PRINT N'Creating scalar function [crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS]';

GO
IF OBJECT_ID(N'[crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS].'
GO


ALTER FUNCTION [crt].GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS()
RETURNS INT
BEGIN
    RETURN 0; -- 0: The request is open
END


GO
PRINT N'Finished creating scalar function [crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS]'
-- End creating scalar function [crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS]


GRANT EXECUTE ON [crt].[GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS] TO [UsersRole];
GO

-- Creating scalar function [crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS]
PRINT N'Creating scalar function [crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS]';

GO
IF OBJECT_ID(N'[crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS]', N'FN') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS] () RETURNS int AS BEGIN RETURN 1 END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create scalar function [crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS].'
GO


ALTER FUNCTION [crt].GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS()
RETURNS INT
BEGIN
    RETURN 1; -- 1: The request is completed
END


GO
PRINT N'Finished creating scalar function [crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS]'
-- End creating scalar function [crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS]


GRANT EXECUTE ON [crt].[GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS] TO [UsersRole];
GO

-- Creating inline table function [crt].[GETRETAILINFOCODESTRANSLATED]
PRINT N'Creating inline table function [crt].[GETRETAILINFOCODESTRANSLATED]';

GO
IF OBJECT_ID(N'[crt].[GETRETAILINFOCODESTRANSLATED]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETRETAILINFOCODESTRANSLATED] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETRETAILINFOCODESTRANSLATED].'
GO


ALTER FUNCTION [crt].[GETRETAILINFOCODESTRANSLATED](@languageId nvarchar(32), @defaultlanguageId nvarchar(32), @DataAreaId nvarchar(4))
RETURNS TABLE
RETURN
SELECT 
icv.[INFOCODEID],
icv.[RECID],
icv.[ONCEPERTRANSACTION],
icv.[PRINTPROMPTONRECEIPT],
icv.[PRINTINPUTONRECEIPT],
icv.[PRINTINPUTNAMEONRECEIPT],
icv.[INPUTTYPE],
icv.[MINIMUMVALUE],
icv.[MAXIMUMVALUE],
icv.[MINIMUMLENGTH],
icv.[MAXIMUMLENGTH],
icv.[INPUTREQUIRED],
icv.[LINKEDINFOCODEID],
icv.[RANDOMFACTOR],
icv.[RETAILUSEINFOCODE],
icv.[GROUPID],
icv.[PRIORITY],
icv.[DATAAREAID],
ISNULL(rict.[DESCRIPTION], ISNULL(rictd.[DESCRIPTION], icv.[INFOCODEID])) 'DESCRIPTION',
ISNULL(rict.[PROMPT], ISNULL(rictd.[PROMPT], icv.[INFOCODEID])) 'PROMPT',
ISNULL(rict.[LANGUAGEID], rictd.[LANGUAGEID]) 'LANGUAGEID'
FROM [crt].[INFOCODEVIEW] icv
LEFT JOIN [ax].[RETAILINFOCODETRANSLATION] rict
ON icv.[RECID]= rict.[INFOCODE]
AND icv.[DATAAREAID]= rict.[DATAAREAID]
AND rict.[LANGUAGEID]= @languageId
LEFT JOIN [ax].[RETAILINFOCODETRANSLATION] rictd
ON icv.[RECID]= rictd.[INFOCODE]
AND icv.[DATAAREAID]= rictd.[DATAAREAID]
AND rictd.[LANGUAGEID]= @defaultlanguageId
WHERE icv.[DATAAREAID] = @DataAreaId


GO
PRINT N'Finished creating inline table function [crt].[GETRETAILINFOCODES]'
-- End creating inline table function [crt].[GETRETAILINFOCODES]


GRANT SELECT ON [crt].[GETRETAILINFOCODESTRANSLATED] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETRETAILINFOCODESTRANSLATED] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETRETAILINFOSUBCODESTRANSLATED]
PRINT N'Creating inline table function [crt].[GETRETAILINFOSUBCODESTRANSLATED]';

GO
IF OBJECT_ID(N'[crt].[GETRETAILINFOSUBCODESTRANSLATED]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETRETAILINFOSUBCODESTRANSLATED] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETRETAILINFOSUBCODESTRANSLATED].'
GO


ALTER FUNCTION [crt].[GETRETAILINFOSUBCODESTRANSLATED](@languageId nvarchar(32), @defaultlanguageId nvarchar(32), @DataAreaId nvarchar(4))
RETURNS TABLE
RETURN
SELECT
iscv.[INFOCODEID],
iscv.[SUBCODEID],
iscv.[RECID],
iscv.[TRIGGERFUNCTION],
iscv.[TRIGGERCODE],
iscv.[NEWSALESLINE],
iscv.[PRICETYPE],
iscv.[AMOUNTPERCENT],
iscv.[DATAAREAID],
ISNULL(risct.[DESCRIPTION], ISNULL(risctd.[DESCRIPTION], iscv.[SUBCODEID])) 'DESCRIPTION',
ISNULL(risct.[LANGUAGEID], risctd.[LANGUAGEID]) 'LANGUAGEID'
FROM [crt].[INFOSUBCODEVIEW] iscv
LEFT JOIN [ax].[RETAILINFORMATIONSUBCODETRANSLATION] risct
ONiscv.[RECID]= risct.[INFOSUBCODE] 
AND risct.[LANGUAGEID]= @languageId
LEFT JOIN [ax].[RETAILINFORMATIONSUBCODETRANSLATION] risctd
ONiscv.[RECID]= risctd.[INFOSUBCODE] 
AND risctd.[LANGUAGEID]= @defaultlanguageId
WHERE iscv.[DATAAREAID] = @DataAreaId


GO
PRINT N'Finished creating inline table function [crt].[GETRETAILINFOSUBCODES]'
-- End creating inline table function [crt].[GETRETAILINFOSUBCODES]


GRANT SELECT ON [crt].[GETRETAILINFOSUBCODESTRANSLATED] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETRETAILINFOSUBCODESTRANSLATED] TO [PublishersRole];
GO

-- Creating table function [crt].[GETMERGEDASSORTMENTRULES]
PRINT N'Creating table function [crt].[GETMERGEDASSORTMENTRULES]';

GO
IF OBJECT_ID(N'[crt].[GETMERGEDASSORTMENTRULES]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETMERGEDASSORTMENTRULES] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETMERGEDASSORTMENTRULES].'
GO


ALTER FUNCTION [crt].[GETMERGEDASSORTMENTRULES]
(
    @bi_ChannelId           BIGINT, -- The unique channel identifier.
    @dt_ChannelDate         DATE,   -- The current date in the channel's time zone.
    @b_IsForwardLooking     BIT,    -- A value indicating whether to include products in future assortments.
    @b_ProductIdsPassed     BIT,    -- A value indicating whether @tvp_ProductIds has been populated. If false, all assorted products are returned.
    @tvp_ProductIds         [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS @MERGEDASSORTMENTRULES TABLE
(
    [PRODUCTID] BIGINT NOT NULL,
    [VARIANTID] BIGINT NOT NULL,
    [ITEMID] NVARCHAR(20) NOT NULL,
    [LINETYPE] INT NOT NULL,
    [VALIDFROM] DATE NOT NULL,
    [VALIDTO] DATE NOT NULL
)
AS
BEGIN
    DECLARE @i_Sequence BIGINT;
    DECLARE @bi_ProductId BIGINT;
    DECLARE @bi_VariantId BIGINT;
    DECLARE @b_LineType INT;
    DECLARE @dt_ValidFrom DATE;
    DECLARE @dt_ValidTo DATE;

    -- Create a temporary table to merge any overlapping dates.
    DECLARE @tbl_WorkingSet TABLE (
        PRODUCTID BIGINT NOT NULL,
        VARIANTID BIGINT NOT NULL,
        ITEMID NVARCHAR(20) NOT NULL,
        LINETYPE INT NOT NULL,
        VALIDFROM DATE NOT NULL,
        VALIDTO DATE NOT NULL,
        SEQUENCE BIGINT
    )

    -- Populate the working set with all applicable assortment rules.
    INSERT @tbl_WorkingSet (PRODUCTID, ITEMID, VARIANTID, LINETYPE, VALIDFROM, VALIDTO, SEQUENCE)
    SELECT ral.PRODUCTID, it.ITEMID, ral.VARIANTID, ral.LINETYPE, ral.VALIDFROM, ral.VALIDTO, NULL
    FROM [ax].RETAILASSORTMENTLOOKUP ral
    INNER JOIN @tvp_ProductIds ids ON @b_ProductIdsPassed = 0 OR ids.RECID = ral.PRODUCTID
    INNER JOIN [ax].RETAILASSORTMENTLOOKUPCHANNELGROUP ralcg ON ralcg.ASSORTMENTID = ral.ASSORTMENTID
    INNER JOIN [ax].RETAILCHANNELTABLE rct ON rct.OMOPERATINGUNITID = ralcg.OMOPERATINGUNITID AND rct.RECID = @bi_ChannelId -- Resolve OM to channel
    INNER JOIN [ax].INVENTTABLE it ON it.PRODUCT = ral.PRODUCTID AND it.DATAAREAID = rct.INVENTLOCATIONDATAAREAID -- Include only Released items
    WHERE ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN ral.VALIDFROM AND ral.VALIDTO) OR
        (@b_IsForwardLooking = 1 AND ral.VALIDTO >= @dt_ChannelDate))
    ORDER BY ral.PRODUCTID, ral.VARIANTID, it.ITEMID, ral.LINETYPE, ral.VALIDFROM

    SELECT TOP 1
        @i_Sequence = 0,
        @bi_ProductId = PRODUCTID,
        @bi_VariantId = VARIANTID,
        @b_LineType = LINETYPE,
        @dt_ValidFrom = VALIDFROM,
        @dt_ValidTo = VALIDTO
    FROM @tbl_WorkingSet
    ORDER BY PRODUCTID, VARIANTID, ITEMID, LINETYPE, VALIDFROM

    UPDATE @tbl_WorkingSet
    SET @i_Sequence =
        CASE
            WHEN VALIDFROM > @dt_ValidTo THEN @i_Sequence + 1
            WHEN PRODUCTID > @bi_ProductId AND VARIANTID > @bi_VariantId THEN @i_Sequence + 1
            ELSE @i_Sequence
        END,
        @dt_ValidFrom =
        CASE
            WHEN VALIDTO > @dt_ValidTo THEN VALIDFROM
            WHEN PRODUCTID > @bi_ProductId AND VARIANTID > @bi_VariantId THEN VALIDFROM
            ELSE @dt_ValidFrom
        END,
        @dt_ValidTo =
        CASE
            WHEN VALIDTO > @dt_ValidTo THEN VALIDTO
            WHEN PRODUCTID > @bi_ProductId AND VARIANTID > @bi_VariantId THEN VALIDTO
            ELSE @dt_ValidTo
        END,
        SEQUENCE = @i_Sequence,
        @bi_ProductId = PRODUCTID,
        @bi_VariantId = VARIANTID

    -- Return the assortment rules with merged date ranges.
    INSERT @MERGEDASSORTMENTRULES
    SELECT PRODUCTID, VARIANTID, ITEMID, LINETYPE, MIN(VALIDFROM) AS VALIDFROM, MAX(VALIDTO) AS VALIDTO
    FROM @tbl_WorkingSet
    GROUP BY PRODUCTID, VARIANTID, ITEMID, LINETYPE, SEQUENCE
    ORDER BY SEQUENCE

    RETURN
END;


GO
PRINT N'Finished creating table function [crt].[GETMERGEDASSORTMENTRULES]'
-- End creating table function [crt].[GETMERGEDASSORTMENTRULES]


GRANT SELECT ON [crt].[GETMERGEDASSORTMENTRULES] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETMERGEDASSORTMENTRULES] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETASSORTEDPRODUCTS]
PRINT N'Creating inline table function [crt].[GETASSORTEDPRODUCTS]';

GO
IF OBJECT_ID(N'[crt].[GETASSORTEDPRODUCTS]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETASSORTEDPRODUCTS] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETASSORTEDPRODUCTS].'
GO


-- Gets all assorted products including standalone products, master products, variant products and temporary products due to virtual catalog.
ALTER FUNCTION [crt].[GETASSORTEDPRODUCTS]
(
    @bi_ChannelId           BIGINT, -- The unique channel identifier.
    @dt_ChannelDate         DATE,   -- The current date in the channel's time zone.
    @b_IsForwardLooking     BIT,    -- A value indicating whether to include products in future assortments.
    @b_SkipVariantExpansion BIT,    -- A value indicating whether product masters are to be expanded.
    @b_ProductIdsPassed     BIT,    -- A value indicating whether @tvp_ProductIds has been populated. If false, all assorted products are returned.
    @tvp_ProductIds         [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS TABLE
RETURN

    WITH
    cte_MergedAssortmentRules AS
    (
        -- Merge all overlapping assortment rules.
        SELECT PRODUCTID, ITEMID, VARIANTID, LINETYPE, VALIDFROM, VALIDTO
        FROM [crt].GETMERGEDASSORTMENTRULES(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking, @b_ProductIdsPassed, @tvp_ProductIds) ral
    ),
    cte_ExplicitlyExcludedProductsAndVariants (PRODUCTID, VARIANTID, VALIDFROM, VALIDTO) AS
    (
        SELECT PRODUCTID, VARIANTID, VALIDFROM, VALIDTO
        FROM cte_MergedAssortmentRules
        WHERE LINETYPE = 0
    )

    -- Retrieve implicitly included product variants for explicitly included product masters.
    SELECT
        pv.PRODUCTMASTER AS 'PRODUCTID',
        ral.ITEMID,
        pv.RECID AS 'VARIANTID',
        0 AS 'ISREMOTE',
        dr.VALIDFROM,
        dr.VALIDTO
    FROM cte_MergedAssortmentRules ral
    INNER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON pv.PRODUCTMASTER = ral.PRODUCTID -- Include variants only
    LEFT OUTER JOIN cte_ExplicitlyExcludedProductsAndVariants epv ON epv.PRODUCTID = ral.PRODUCTID AND (epv.VARIANTID = 0 OR epv.VARIANTID = pv.RECID)
        AND NOT (ral.VALIDFROM > epv.VALIDTO OR ral.VALIDTO < epv.VALIDFROM)
    CROSS APPLY [crt].GETINCLUDEDDATERANGES(ral.VALIDFROM, ral.VALIDTO, epv.VALIDFROM, epv.VALIDTO) dr
    WHERE ral.LINETYPE = 1 AND ral.VARIANTID = 0 AND @b_SkipVariantExpansion = 0 AND
        ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN dr.VALIDFROM AND dr.VALIDTO) OR
            (@b_IsForwardLooking = 1 AND dr.VALIDTO >= @dt_ChannelDate))

    UNION ALL

    -- Retrieve explicitly included products and/or variants that have not been excluded.
    SELECT
        ral.PRODUCTID,
        ral.ITEMID,
        ral.VARIANTID,
        0 AS 'ISREMOTE',
        dr.VALIDFROM,
        dr.VALIDTO
    FROM cte_MergedAssortmentRules ral
    LEFT OUTER JOIN cte_ExplicitlyExcludedProductsAndVariants epv ON epv.PRODUCTID = ral.PRODUCTID AND (epv.VARIANTID = 0 OR epv.VARIANTID = ral.VARIANTID)
        AND NOT (ral.VALIDFROM > epv.VALIDTO OR ral.VALIDTO < epv.VALIDFROM)
    CROSS APPLY [crt].GETINCLUDEDDATERANGES(ral.VALIDFROM, ral.VALIDTO, epv.VALIDFROM, epv.VALIDTO) dr
    WHERE ral.LINETYPE = 1 AND
        ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN dr.VALIDFROM AND dr.VALIDTO) OR
            (@b_IsForwardLooking = 1 AND dr.VALIDTO >= @dt_ChannelDate))

    UNION

    -- Retrieve product masters that have been implicitly included by variant inclusions.
    SELECT
        ral.PRODUCTID AS 'PRODUCTID',
        ral.ITEMID,
        0 AS 'VARIANTID',
        0 AS 'ISREMOTE',
        dr.VALIDFROM,
        dr.VALIDTO
    FROM cte_MergedAssortmentRules ral
    LEFT OUTER JOIN cte_ExplicitlyExcludedProductsAndVariants epv ON epv.PRODUCTID = ral.PRODUCTID AND (epv.VARIANTID = 0 OR epv.VARIANTID = ral.VARIANTID)
        AND NOT (ral.VALIDFROM > epv.VALIDTO OR ral.VALIDTO < epv.VALIDFROM)
    CROSS APPLY [crt].GETINCLUDEDDATERANGES(ral.VALIDFROM, ral.VALIDTO, epv.VALIDFROM, epv.VALIDTO) dr
    WHERE ral.LINETYPE = 1 AND ral.VARIANTID != 0 AND
        ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN dr.VALIDFROM AND dr.VALIDTO) OR
            (@b_IsForwardLooking = 1 AND dr.VALIDTO >= @dt_ChannelDate))

    UNION ALL

    -- Retrieve temporarily assorted products that have been downloaded by way of virtual catalog.
    SELECT
        tap.PRODUCTID AS 'PRODUCTID',
        tap.ITEMID,
        0 AS 'VARIANTID',
        1 AS 'ISREMOTE',
        tap.VALIDFROM,
        tap.VALIDTO
    FROM [crt].TMPASSORTEDPRODUCTS tap
    INNER JOIN @tvp_ProductIds ids ON @b_ProductIdsPassed = 0 OR ids.RECID = tap.PRODUCTID
    WHERE tap.CHANNELID = @bi_ChannelId AND @dt_ChannelDate BETWEEN tap.VALIDFROM AND tap.VALIDTO


GO
PRINT N'Finished creating inline table function [crt].[GETASSORTEDPRODUCTS]'
-- End creating inline table function [crt].[GETASSORTEDPRODUCTS]


GRANT SELECT ON [crt].[GETASSORTEDPRODUCTS] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETASSORTEDPRODUCTS] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM]
PRINT N'Creating inline table function [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM]';

GO
IF OBJECT_ID(N'[crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM].'
GO


-- Returns the row from AssortedInventDimCombination for the specified channel, date, and item id.
ALTER FUNCTION [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM]
(
@bi_ChannelId BIGINT,
@dt_ChannelDate DATE,
@nvc_ItemId NVARCHAR(20)
)
RETURNS TABLE
RETURN
    SELECT RCT.RECID AS STORERECID, IDC.ITEMID, IDC.INVENTDIMID, IDC.DISTINCTPRODUCTVARIANT, IDC.CREATEDDATETIME, IDC.DATAAREAID, IDC.RECID, IDC.RETAILVARIANTID
    FROM [ax].RETAILCHANNELTABLE RCT
INNER JOIN [ax].INVENTTABLE IT ON IT.DATAAREAID = RCT.INVENTLOCATIONDATAAREAID
INNER JOIN [ax].INVENTDIMCOMBINATION IDC ON IDC.ITEMID = IT.ITEMID AND IDC.DATAAREAID = IT.DATAAREAID
    WHERE RCT.RECID = @bi_ChannelId
AND IT.ITEMID = @nvc_ItemId
AND (EXISTS
    (
SELECT ral.RECID
FROM [ax].RETAILASSORTMENTLOOKUP ral
INNER JOIN [ax].RETAILASSORTMENTLOOKUPCHANNELGROUP ralcg on ralcg.ASSORTMENTID = ral.ASSORTMENTID
LEFT OUTER JOIN [ax].INVENTDIMCOMBINATION idc on idc.ITEMID = it.ITEMID and idc.DATAAREAID = it.DATAAREAID and (ral.VARIANTID = idc.DISTINCTPRODUCTVARIANT or ral.VARIANTID = 0)
WHERE ral.PRODUCTID = IT.PRODUCT
AND ralcg.OMOPERATINGUNITID = rct.OMOPERATINGUNITID
AND @dt_ChannelDate >= ral.VALIDFROM and @dt_ChannelDate <= ral.VALIDTO -- Enforce date effectivity
GROUP BY ralcg.ASSORTMENTID, idc.INVENTDIMID, ral.VARIANTID, ral.VALIDFROM, ral.VALIDTO, ral.RECID
HAVING MIN(ral.LINETYPE) = 1 -- Remove excluded products
    )
OR EXISTS (
        SELECT TAP.PRODUCTID
        FROM [crt].TMPASSORTEDPRODUCTS TAP
        WHERE
            TAP.PRODUCTID = IT.PRODUCT AND
            TAP.CHANNELID = RCT.RECID AND
            @dt_ChannelDate BETWEEN TAP.VALIDFROM and TAP.VALIDTO -- Enforce date effectivity
        ))



GO
PRINT N'Finished creating inline table function [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM]'
-- End creating inline table function [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM]


GRANT SELECT ON [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETASSORTEDINVENTDIMCOMBINATIONFORITEM] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETASSORTEDINVENTITEM]
PRINT N'Creating inline table function [crt].[GETASSORTEDINVENTITEM]';

GO
IF OBJECT_ID(N'[crt].[GETASSORTEDINVENTITEM]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETASSORTEDINVENTITEM] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETASSORTEDINVENTITEM].'
GO


-- Returns the row from AssortedItemsView for the specified channel, date, and item id.
ALTER FUNCTION [crt].[GETASSORTEDINVENTITEM]
(
@bi_ChannelId BIGINT,
@dt_ChannelDate DATE,
@nvc_ItemId NVARCHAR(20)
)
RETURNS TABLE
RETURN
    SELECT RCT.RECID AS STORERECID, 
IT.[ITEMID],
CONVERT([nvarchar](60), '') AS 'ITEMNAME',
IT.[ITEMTYPE],
IT.[PURCHMODEL],
IT.[HEIGHT],
IT.[WIDTH],
IT.[SALESMODEL],
IT.[REQGROUPID],
IT.[PRIMARYVENDORID],
IT.[NETWEIGHT],
IT.[DEPTH],
IT.[UNITVOLUME],
IT.[DENSITY],
CONVERT([nvarchar](10), '') AS 'DIMENSION',
CONVERT([nvarchar](10), '') AS 'DIMENSION2_',
CONVERT([nvarchar](10), '') AS 'DIMENSION3_',
IT.[COSTMODEL],
IT.[USEALTITEMID],
IT.[ALTITEMID],
CONVERT([int], 0) AS 'BOMMANUALCONSUMP',
CONVERT([int], 0) AS 'BOMMANUALRECEIPT',
CONVERT([int], 0) AS 'STOPEXPLODE',
IT.[BATCHNUMGROUPID],
IT.[PRODPOOLID],
IT.[PROPERTYID],
IT.[ABCTIEUP],
IT.[ABCREVENUE],
IT.[ABCVALUE],
IT.[ABCCONTRIBUTIONMARGIN],
IT.[SALESPERCENTMARKUP],
IT.[SALESCONTRIBUTIONRATIO],
IT.[SALESPRICEMODELBASIC],
CONVERT([numeric](28, 12), 0) AS 'MINAVERAGESETTLE',
IT.[NAMEALIAS],
IT.[PRODGROUPID],
IT.[PROJCATEGORYID],
IT.[GROSSDEPTH],
IT.[GROSSWIDTH],
IT.[GROSSHEIGHT],
IT.[SORTCODE],
IT.[SERIALNUMGROUPID],
CONVERT([nvarchar](10), '') AS 'DIMGROUPID',
IT.[ITEMBUYERGROUPID],
IT.[WMSPICKINGQTYTIME],
IT.[TARAWEIGHT],
CONVERT([int], 0) AS 'ITEMDIMCOMBINATIONAUTOCREATE',
IT.[ITEMDIMCOSTPRICE],
CONVERT([nvarchar](20), '') AS 'ITEMIDCOMPANY',
IT.[PBAITEMCONFIGURABLE],
IT.[PBAINVENTITEMGROUPID],
IT.[PRODUCT],
IT.[DATAAREAID],
IT.[RECID],
IT.[TAXFISCALCLASSIFICATION_BR],
IT.[EXCEPTIONCODE_BR],
IT.[TAXSERVICECODE_BR],
IT.[INVENTPRODUCTTYPE_BR],
IT.[TAXATIONORIGIN_BR],
IT.[APPROXTAXVALUE_BR],
ISNULL(IIGI.ITEMGROUPID, '') AS ITEMGROUPID
    FROM [ax].RETAILCHANNELTABLE RCT
INNER JOIN [ax].INVENTTABLE IT ON IT.DATAAREAID = RCT.INVENTLOCATIONDATAAREAID
LEFT JOIN [ax].INVENTITEMGROUPITEM IIGI ON IT.DATAAREAID = IIGI.ITEMDATAAREAID AND IT.ITEMID = IIGI.ITEMID
    WHERE RCT.RECID = @bi_ChannelId
AND IT.ITEMID = @nvc_ItemId
AND (EXISTS
    (
SELECT ral.RECID
FROM [ax].RETAILASSORTMENTLOOKUP ral
INNER JOIN [ax].RETAILASSORTMENTLOOKUPCHANNELGROUP ralcg on ralcg.ASSORTMENTID = ral.ASSORTMENTID
LEFT OUTER JOIN [ax].INVENTDIMCOMBINATION idc on idc.ITEMID = it.ITEMID and idc.DATAAREAID = it.DATAAREAID and (ral.VARIANTID = idc.DISTINCTPRODUCTVARIANT or ral.VARIANTID = 0)
WHERE ral.PRODUCTID = IT.PRODUCT
AND ralcg.OMOPERATINGUNITID = rct.OMOPERATINGUNITID
AND @dt_ChannelDate >= ral.VALIDFROM and @dt_ChannelDate <= ral.VALIDTO -- Enforce date effectivity
GROUP BY ralcg.ASSORTMENTID, idc.INVENTDIMID, ral.VARIANTID, ral.VALIDFROM, ral.VALIDTO, ral.RECID
HAVING MIN(ral.LINETYPE) = 1 -- Remove excluded products
    )
OR EXISTS (
        SELECT TAP.PRODUCTID
        FROM [crt].TMPASSORTEDPRODUCTS TAP
        WHERE
            TAP.PRODUCTID = IT.PRODUCT AND
            TAP.CHANNELID = RCT.RECID AND
            @dt_ChannelDate BETWEEN TAP.VALIDFROM and TAP.VALIDTO -- Enforce date effectivity
        ))



GO
PRINT N'Finished creating inline table function [crt].[GETASSORTEDINVENTITEM]'
-- End creating inline table function [crt].[GETASSORTEDINVENTITEM]


GRANT SELECT ON [crt].[GETASSORTEDINVENTITEM] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETASSORTEDINVENTITEM] TO [PublishersRole];
GO

-- Creating inline table function [crt].[GETVARIANTS]
PRINT N'Creating inline table function [crt].[GETVARIANTS]';

GO
IF OBJECT_ID(N'[crt].[GETVARIANTS]', N'IF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETVARIANTS] () RETURNS TABLE AS RETURN SELECT 1 AS [dummy]')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create inline table function [crt].[GETVARIANTS].'
GO


-- Gets the list of variants for the specified list of distinct product variant identifiers.
ALTER FUNCTION [crt].[GETVARIANTS]
(
    @bi_ChannelId                   BIGINT,
    @dt_ChannelDate                 DATE,
    @tvp_DistinctProductVariantIds  [crt].[RECORDIDTABLETYPE] READONLY
)
RETURNS TABLE
RETURN
    SELECT
        idc.RECID AS 'RECID',
        it.ITEMID,
        idc.RETAILVARIANTID AS 'VARIANTID',
        id.INVENTDIMID AS 'INVENTDIMID',
        idc.DISTINCTPRODUCTVARIANT,
        id.INVENTSIZEID AS 'SIZEID',
        id.INVENTCOLORID AS 'COLORID',
        id.INVENTSTYLEID AS 'STYLEID',
        id.CONFIGID AS 'CONFIGID',
        ISNULL(dvc.NAME, '') AS 'COLOR',
        ISNULL(dvsz.NAME, '') AS 'SIZE',
        ISNULL(dvst.NAME, '') AS 'STYLE',
        ISNULL(dvcfg.NAME, '') AS 'CONFIG'
    FROM @tvp_DistinctProductVariantIds ids
    INNER JOIN [ax].RETAILCHANNELTABLE rct ON rct.RECID = @bi_ChannelId
    INNER JOIN [crt].CHANNELLANGUAGESVIEW clv ON clv.CHANNEL = rct.RECID AND clv.ISDEFAULT = 1 -- Use default channel language
    INNER JOIN [ax].INVENTDIMCOMBINATION idc ON idc.DISTINCTPRODUCTVARIANT = ids.RECID AND idc.DATAAREAID = rct.INVENTLOCATIONDATAAREAID
    INNER JOIN [ax].INVENTTABLE it ON it.ITEMID = idc.ITEMID AND it.DATAAREAID = idc.DATAAREAID
    INNER JOIN [ax].INVENTDIM id ON id.INVENTDIMID = idc.INVENTDIMID AND id.DATAAREAID = idc.DATAAREAID
    -- Color
    LEFT OUTER JOIN [ax].ECORESCOLOR erc ON erc.NAME = id.INVENTCOLORID
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERCOLOR erpmc ON erpmc.COLOR = erc.RECID AND erpmc.COLORPRODUCTMASTER = it.PRODUCT
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERDIMVALUETRANSLATION dvc ON DVC.PRODUCTMASTERDIMENSIONVALUE = erpmc.RECID AND dvc.LANGUAGEID = clv.LANGUAGEID
    -- Size
    LEFT OUTER JOIN [ax].ECORESSIZE ers ON ers.NAME = id.INVENTSIZEID
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERSIZE erpms ON erpms.SIZE = ers.RECID AND erpms.SIZEPRODUCTMASTER = it.PRODUCT
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERDIMVALUETRANSLATION dvsz ON dvsz.PRODUCTMASTERDIMENSIONVALUE = erpms.RECID AND dvsz.LANGUAGEID = clv.LANGUAGEID
    -- Style
    LEFT OUTER JOIN [ax].ECORESSTYLE erst ON erst .NAME = id.INVENTSTYLEID
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERSTYLE erpmst ON erpmst.STYLE = erst .RECID AND erpmst.STYLEPRODUCTMASTER = it.PRODUCT
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERDIMVALUETRANSLATION dvst ON dvst.PRODUCTMASTERDIMENSIONVALUE = erpmst.RECID AND dvst.LANGUAGEID = clv.LANGUAGEID
    -- Configuration
    LEFT OUTER JOIN [ax].ECORESCONFIGURATION ercfg ON ercfg.NAME = id.CONFIGID
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERCONFIGURATION erpmcfg ON erpmcfg.CONFIGURATION = ercfg.RECID AND erpmcfg.CONFIGPRODUCTMASTER = it.PRODUCT
    LEFT OUTER JOIN [ax].ECORESPRODUCTMASTERDIMVALUETRANSLATION dvcfg ON dvcfg.PRODUCTMASTERDIMENSIONVALUE = erpmcfg.RECID AND dvcfg.LANGUAGEID = clv.LANGUAGEID



GO
PRINT N'Finished creating inline table function [crt].[GETVARIANTS]'
-- End creating inline table function [crt].[GETVARIANTS]


GRANT SELECT ON [crt].[GETVARIANTS] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETVARIANTS] TO [PublishersRole];
GO

-- Creating table function [crt].[GETVARIANTSBYVARIANTIDS]
PRINT N'Creating table function [crt].[GETVARIANTSBYVARIANTIDS]';

GO
IF OBJECT_ID(N'[crt].[GETVARIANTSBYVARIANTIDS]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETVARIANTSBYVARIANTIDS] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETVARIANTSBYVARIANTIDS].'
GO


-- Gets the list of variants for the specified list of retail variant identifiers.
ALTER FUNCTION [crt].[GETVARIANTSBYVARIANTIDS]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @tvp_VariantIds     [crt].[STRINGIDTABLETYPE]    READONLY
)
RETURNS @VARIANTS TABLE
(
    RECID                   BIGINT,
    ITEMID                  NVARCHAR(20),
    VARIANTID               NVARCHAR(10),
    INVENTDIMID             NVARCHAR(20),
    DISTINCTPRODUCTVARIANT  BIGINT,
    SIZEID                  NVARCHAR(10),
    COLORID                 NVARCHAR(10),
    STYLEID                 NVARCHAR(10),
    CONFIGID                NVARCHAR(10),
    COLOR                   NVARCHAR(60),
    SIZE                    NVARCHAR(60),
    STYLE                   NVARCHAR(60),
    CONFIG                  NVARCHAR(60)
)
AS
BEGIN
    DECLARE @tvp_DistinctProductVariantIds [crt].[RECORDIDTABLETYPE];
    DECLARE @nvc_DataAreaId NVARCHAR(4);

    -- Get the data area for the specified channel identifier.
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId;

    -- Convert the retail variant identifier into distinct product variant identifiers.
    INSERT INTO @tvp_DistinctProductVariantIds (RECID)
    SELECT idc.DISTINCTPRODUCTVARIANT
    FROM @tvp_VariantIds ids
    INNER JOIN [ax].INVENTDIMCOMBINATION idc ON idc.RETAILVARIANTID = ids.STRINGID AND idc.DATAAREAID = @nvc_DataAreaId

    -- Retrieve the variants.
    INSERT @VARIANTS
    SELECT
        v.RECID,
        v.ITEMID,
        v.VARIANTID,
        v.INVENTDIMID,
        v.DISTINCTPRODUCTVARIANT,
        v.SIZEID,
        v.COLORID,
        v.STYLEID,
        v.CONFIGID,
        v.COLOR,
        v.SIZE,
        v.STYLE,
        v.CONFIG
    FROM [crt].GETVARIANTS(@bi_ChannelId, @dt_ChannelDate, @tvp_DistinctProductVariantIds) v

    RETURN;
END


GO
PRINT N'Finished creating table function [crt].[GETVARIANTSBYVARIANTIDS]'
-- End creating table function [crt].[GETVARIANTSBYVARIANTIDS]


GRANT SELECT ON [crt].[GETVARIANTSBYVARIANTIDS] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETVARIANTSBYVARIANTIDS] TO [PublishersRole];
GO

-- Creating table function [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS]
PRINT N'Creating table function [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS]';

GO
IF OBJECT_ID(N'[crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS].'
GO


-- Gets the list of variants for the specified list of item and inventory dimension identifiers.
ALTER FUNCTION [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS]
(
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @tvp_ItemVariantIds [crt].[ITEMVARIANTINVENTDIMTABLETYPE]    READONLY
)
RETURNS @VARIANTS TABLE
(
    RECID                   BIGINT,
    ITEMID                  NVARCHAR(20),
    VARIANTID               NVARCHAR(10),
    INVENTDIMID             NVARCHAR(20),
    DISTINCTPRODUCTVARIANT  BIGINT,
    SIZEID                  NVARCHAR(10),
    COLORID                 NVARCHAR(10),
    STYLEID                 NVARCHAR(10),
    CONFIGID                NVARCHAR(10),
    COLOR                   NVARCHAR(60),
    SIZE                    NVARCHAR(60),
    STYLE                   NVARCHAR(60),
    CONFIG                  NVARCHAR(60)
)
AS
BEGIN
    DECLARE @tvp_DistinctProductVariantIds [crt].[RECORDIDTABLETYPE];
    DECLARE @nvc_DataAreaId NVARCHAR(4);

    -- Get the data area for the specified channel identifier.
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId;

    -- Convert the ItemId, VariantInventDimId pairs into distinct product variant identifiers.
    INSERT INTO @tvp_DistinctProductVariantIds (RECID)
    SELECT idc.DISTINCTPRODUCTVARIANT
    FROM @tvp_ItemVariantIds ids
    INNER JOIN [ax].INVENTDIMCOMBINATION idc ON idc.ITEMID = ids.ITEMID AND idc.INVENTDIMID = ids.VARIANTINVENTDIMID AND idc.DATAAREAID = @nvc_DataAreaId

    -- Retrieve the variants.
    INSERT @VARIANTS
    SELECT
        v.RECID,
        v.ITEMID,
        v.VARIANTID,
        v.INVENTDIMID,
        v.DISTINCTPRODUCTVARIANT,
        v.SIZEID,
        v.COLORID,
        v.STYLEID,
        v.CONFIGID,
        v.COLOR,
        v.SIZE,
        v.STYLE,
        v.CONFIG
    FROM [crt].GETVARIANTS(@bi_ChannelId, @dt_ChannelDate, @tvp_DistinctProductVariantIds) v

    RETURN;
END


GO
PRINT N'Finished creating table function [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS]'
-- End creating table function [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS]


GRANT SELECT ON [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS] TO [UsersRole];
GO

GRANT SELECT ON [crt].[GETVARIANTSBYITEMIDANDINVENTDIMIDS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETNOTEXISTINGLANGUAGES]
PRINT N'Creating stored procedure [crt].[GETNOTEXISTINGLANGUAGES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETNOTEXISTINGLANGUAGES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETNOTEXISTINGLANGUAGES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETNOTEXISTINGLANGUAGES].';
END
GO


ALTER PROCEDURE [crt].[GETNOTEXISTINGLANGUAGES]
    @bi_ChannelId BIGINT,
    @tvp_LanguageIds crt.LANGUAGEIDTABLETYPE READONLY

AS
BEGIN
    SET NOCOUNT ON

    SELECT
      LISTID, LANGUAGEID
    FROM [crt].[CATALOGLISTMAPPING]
WHERE CHANNELID = @bi_ChannelId
  AND LANGUAGEID NOT IN (SELECT LANGUAGEID FROM @tvp_LanguageIds)
    GROUP BY LISTID, LANGUAGEID

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETNOTEXISTINGLANGUAGES]'
GO
-- End creating stored procedure [crt].[GETNOTEXISTINGLANGUAGES]


GRANT EXECUTE ON [crt].[GETNOTEXISTINGLANGUAGES] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETNOTEXISTINGLANGUAGES] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[SAVEPRODUCTDATA]
PRINT N'Creating stored procedure [crt].[SAVEPRODUCTDATA]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVEPRODUCTDATA]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVEPRODUCTDATA] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVEPRODUCTDATA].';
END
GO


ALTER PROCEDURE [crt].[SAVEPRODUCTDATA]
    @bi_ChannelId       BIGINT,
    @xml_ProductData    XML
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;
    DECLARE @nvc_DataAreaId             NVARCHAR(4);
 
    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Resolve the data area from the specified channel identifier.
    SELECT @nvc_DataAreaId = rct.[INVENTLOCATIONDATAAREAID] FROM [ax].RETAILCHANNELTABLE rct WHERE [rct].RECID = @bi_ChannelId

-- Generated stats: 58 distinct tables spanning 61 unique paths.

-- InventTable
PRINT 'Upserting into [ax].INVENTTABLE ..'
MERGE [ax].INVENTTABLE AS target
USING (
SELECT DISTINCT
CASE T.c.value('(ABCContributionMargin)[1]', 'NVARCHAR(4000)')
WHEN 'None' THEN 0
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS [ABCCONTRIBUTIONMARGIN],
CASE T.c.value('(ABCRevenue)[1]', 'NVARCHAR(4000)')
WHEN 'None' THEN 0
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS [ABCREVENUE],
CASE T.c.value('(ABCTieUp)[1]', 'NVARCHAR(4000)')
WHEN 'None' THEN 0
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS [ABCTIEUP],
CASE T.c.value('(ABCValue)[1]', 'NVARCHAR(4000)')
WHEN 'None' THEN 0
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS [ABCVALUE],
ISNULL(T.c.value('(AltItemId)[1]', 'NVARCHAR(20)'), '') AS [ALTITEMID],
ISNULL(T.c.value('(ApproxTaxValue_BR)[1]', 'NUMERIC(32, 16)'), '0') AS [APPROXTAXVALUE_BR],
ISNULL(T.c.value('(BatchNumGroupId)[1]', 'NVARCHAR(10)'), '') AS [BATCHNUMGROUPID],
CASE T.c.value('(CostModel)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [COSTMODEL],
ISNULL(T.c.value('(Density)[1]', 'NUMERIC(32, 16)'), '0') AS [DENSITY],
ISNULL(T.c.value('(Depth)[1]', 'NUMERIC(32, 16)'), '0') AS [DEPTH],
ISNULL(T.c.value('(ExceptionCode_BR)[1]', 'NVARCHAR(10)'), '') AS [EXCEPTIONCODE_BR],
ISNULL(T.c.value('(grossDepth)[1]', 'NUMERIC(32, 16)'), '0') AS [GROSSDEPTH],
ISNULL(T.c.value('(grossHeight)[1]', 'NUMERIC(32, 16)'), '0') AS [GROSSHEIGHT],
ISNULL(T.c.value('(grossWidth)[1]', 'NUMERIC(32, 16)'), '0') AS [GROSSWIDTH],
ISNULL(T.c.value('(Height)[1]', 'NUMERIC(32, 16)'), '0') AS [HEIGHT],
ISNULL(T.c.value('(InventProductType_BR)[1]', 'NVARCHAR(10)'), '') AS [INVENTPRODUCTTYPE_BR],
ISNULL(T.c.value('(ItemBuyerGroupId)[1]', 'NVARCHAR(10)'), '') AS [ITEMBUYERGROUPID],
CASE T.c.value('(ItemDimCostPrice)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [ITEMDIMCOSTPRICE],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
CASE T.c.value('(ItemType)[1]', 'NVARCHAR(4000)')
WHEN 'Item' THEN 0
WHEN 'DEL_BOM' THEN 1
WHEN 'Service' THEN 2
WHEN 'DEL_Formula' THEN 3
WHEN 'DEL_Asset_RU' THEN 4
ELSE 0
END AS [ITEMTYPE],
ISNULL(T.c.value('(NameAlias)[1]', 'NVARCHAR(20)'), '') AS [NAMEALIAS],
ISNULL(T.c.value('(NetWeight)[1]', 'NUMERIC(32, 16)'), '0') AS [NETWEIGHT],
ISNULL(T.c.value('(PBAInventItemGroupId)[1]', 'NVARCHAR(10)'), '') AS [PBAINVENTITEMGROUPID],
CASE T.c.value('(PBAItemConfigurable)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [PBAITEMCONFIGURABLE],
ISNULL(T.c.value('(PrimaryVendorId)[1]', 'NVARCHAR(20)'), '') AS [PRIMARYVENDORID],
ISNULL(T.c.value('(ProdGroupId)[1]', 'NVARCHAR(10)'), '') AS [PRODGROUPID],
ISNULL(T.c.value('(ProdPoolId)[1]', 'NVARCHAR(10)'), '') AS [PRODPOOLID],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT],
ISNULL(T.c.value('(projCategoryId)[1]', 'NVARCHAR(30)'), '') AS [PROJCATEGORYID],
ISNULL(T.c.value('(PropertyId)[1]', 'NVARCHAR(10)'), '') AS [PROPERTYID],
CASE T.c.value('(PurchModel)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [PURCHMODEL],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(ReqGroupId)[1]', 'NVARCHAR(10)'), '') AS [REQGROUPID],
ISNULL(T.c.value('(SalesContributionRatio)[1]', 'NUMERIC(32, 16)'), '0') AS [SALESCONTRIBUTIONRATIO],
CASE T.c.value('(SalesModel)[1]', 'NVARCHAR(4000)')
WHEN 'None' THEN 0
WHEN 'Contributionratio' THEN 1
WHEN 'PercentMarkup' THEN 2
ELSE 0
END AS [SALESMODEL],
ISNULL(T.c.value('(SalesPercentMarkup)[1]', 'NUMERIC(32, 16)'), '0') AS [SALESPERCENTMARKUP],
CASE T.c.value('(SalesPriceModelBasic)[1]', 'NVARCHAR(4000)')
WHEN 'PurchPrice' THEN 0
WHEN 'CostPrice' THEN 1
ELSE 0
END AS [SALESPRICEMODELBASIC],
ISNULL(T.c.value('(SerialNumGroupId)[1]', 'NVARCHAR(10)'), '') AS [SERIALNUMGROUPID],
ISNULL(T.c.value('(sortCode)[1]', 'INT'), '0') AS [SORTCODE],
ISNULL(T.c.value('(TaraWeight)[1]', 'NUMERIC(32, 16)'), '0') AS [TARAWEIGHT],
CASE T.c.value('(TaxationOrigin_BR)[1]', 'NVARCHAR(4000)')
WHEN 'National' THEN 0
WHEN 'DirectImport' THEN 1
WHEN 'Import' THEN 2
WHEN 'NationalImportContent' THEN 3
WHEN 'LegalAdjusts' THEN 4
WHEN 'NationalLessThan40ImportContent' THEN 5
WHEN 'ImportNoSimilar' THEN 6
WHEN 'ImportAcquiredInRegion' THEN 7
WHEN 'NationalGreaterThan70ImportContent' THEN 8
ELSE 0
END AS [TAXATIONORIGIN_BR],
ISNULL(T.c.value('(TaxFiscalClassification_BR)[1]', 'NVARCHAR(10)'), '') AS [TAXFISCALCLASSIFICATION_BR],
ISNULL(T.c.value('(TaxServiceCode_BR)[1]', 'NVARCHAR(10)'), '') AS [TAXSERVICECODE_BR],
ISNULL(T.c.value('(UnitVolume)[1]', 'NUMERIC(32, 16)'), '0') AS [UNITVOLUME],
CASE T.c.value('(UseAltItemId)[1]', 'NVARCHAR(4000)')
WHEN 'Never' THEN 0
WHEN 'InventWhen0' THEN 1
WHEN 'Always' THEN 2
ELSE 0
END AS [USEALTITEMID],
ISNULL(T.c.value('(Width)[1]', 'NUMERIC(32, 16)'), '0') AS [WIDTH],
DATEDIFF(second, '00:00:00', T.c.value('(WMSPickingQtyTime)[1]', 'time')) AS [WMSPICKINGQTYTIME],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable') AS T(c)
) AS source ([ABCCONTRIBUTIONMARGIN], [ABCREVENUE], [ABCTIEUP], [ABCVALUE], [ALTITEMID], [APPROXTAXVALUE_BR], [BATCHNUMGROUPID], [COSTMODEL], [DENSITY], [DEPTH], [EXCEPTIONCODE_BR], [GROSSDEPTH], [GROSSHEIGHT], [GROSSWIDTH], [HEIGHT], [INVENTPRODUCTTYPE_BR], [ITEMBUYERGROUPID], [ITEMDIMCOSTPRICE], [ITEMID], [ITEMTYPE], [NAMEALIAS], [NETWEIGHT], [PBAINVENTITEMGROUPID], [PBAITEMCONFIGURABLE], [PRIMARYVENDORID], [PRODGROUPID], [PRODPOOLID], [PRODUCT], [PROJCATEGORYID], [PROPERTYID], [PURCHMODEL], [RECID], [REQGROUPID], [SALESCONTRIBUTIONRATIO], [SALESMODEL], [SALESPERCENTMARKUP], [SALESPRICEMODELBASIC], [SERIALNUMGROUPID], [SORTCODE], [TARAWEIGHT], [TAXATIONORIGIN_BR], [TAXFISCALCLASSIFICATION_BR], [TAXSERVICECODE_BR], [UNITVOLUME], [USEALTITEMID], [WIDTH], [WMSPICKINGQTYTIME], [DATAAREAID])
ON (target.[ITEMID] = source.[ITEMID] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([ABCCONTRIBUTIONMARGIN], [ABCREVENUE], [ABCTIEUP], [ABCVALUE], [ALTITEMID], [APPROXTAXVALUE_BR], [BATCHNUMGROUPID], [COSTMODEL], [DENSITY], [DEPTH], [EXCEPTIONCODE_BR], [GROSSDEPTH], [GROSSHEIGHT], [GROSSWIDTH], [HEIGHT], [INVENTPRODUCTTYPE_BR], [ITEMBUYERGROUPID], [ITEMDIMCOSTPRICE], [ITEMID], [ITEMTYPE], [NAMEALIAS], [NETWEIGHT], [PBAINVENTITEMGROUPID], [PBAITEMCONFIGURABLE], [PRIMARYVENDORID], [PRODGROUPID], [PRODPOOLID], [PRODUCT], [PROJCATEGORYID], [PROPERTYID], [PURCHMODEL], [RECID], [REQGROUPID], [SALESCONTRIBUTIONRATIO], [SALESMODEL], [SALESPERCENTMARKUP], [SALESPRICEMODELBASIC], [SERIALNUMGROUPID], [SORTCODE], [TARAWEIGHT], [TAXATIONORIGIN_BR], [TAXFISCALCLASSIFICATION_BR], [TAXSERVICECODE_BR], [UNITVOLUME], [USEALTITEMID], [WIDTH], [WMSPICKINGQTYTIME], [DATAAREAID])
VALUES (source.[ABCCONTRIBUTIONMARGIN], source.[ABCREVENUE], source.[ABCTIEUP], source.[ABCVALUE], source.[ALTITEMID], source.[APPROXTAXVALUE_BR], source.[BATCHNUMGROUPID], source.[COSTMODEL], source.[DENSITY], source.[DEPTH], source.[EXCEPTIONCODE_BR], source.[GROSSDEPTH], source.[GROSSHEIGHT], source.[GROSSWIDTH], source.[HEIGHT], source.[INVENTPRODUCTTYPE_BR], source.[ITEMBUYERGROUPID], source.[ITEMDIMCOSTPRICE], source.[ITEMID], source.[ITEMTYPE], source.[NAMEALIAS], source.[NETWEIGHT], source.[PBAINVENTITEMGROUPID], source.[PBAITEMCONFIGURABLE], source.[PRIMARYVENDORID], source.[PRODGROUPID], source.[PRODPOOLID], source.[PRODUCT], source.[PROJCATEGORYID], source.[PROPERTYID], source.[PURCHMODEL], source.[RECID], source.[REQGROUPID], source.[SALESCONTRIBUTIONRATIO], source.[SALESMODEL], source.[SALESPERCENTMARKUP], source.[SALESPRICEMODELBASIC], source.[SERIALNUMGROUPID], source.[SORTCODE], source.[TARAWEIGHT], source.[TAXATIONORIGIN_BR], source.[TAXFISCALCLASSIFICATION_BR], source.[TAXSERVICECODE_BR], source.[UNITVOLUME], source.[USEALTITEMID], source.[WIDTH], source.[WMSPICKINGQTYTIME], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[ABCCONTRIBUTIONMARGIN] = source.[ABCCONTRIBUTIONMARGIN], target.[ABCREVENUE] = source.[ABCREVENUE], target.[ABCTIEUP] = source.[ABCTIEUP], target.[ABCVALUE] = source.[ABCVALUE], target.[ALTITEMID] = source.[ALTITEMID], target.[APPROXTAXVALUE_BR] = source.[APPROXTAXVALUE_BR], target.[BATCHNUMGROUPID] = source.[BATCHNUMGROUPID], target.[COSTMODEL] = source.[COSTMODEL], target.[DENSITY] = source.[DENSITY], target.[DEPTH] = source.[DEPTH], target.[EXCEPTIONCODE_BR] = source.[EXCEPTIONCODE_BR], target.[GROSSDEPTH] = source.[GROSSDEPTH], target.[GROSSHEIGHT] = source.[GROSSHEIGHT], target.[GROSSWIDTH] = source.[GROSSWIDTH], target.[HEIGHT] = source.[HEIGHT], target.[INVENTPRODUCTTYPE_BR] = source.[INVENTPRODUCTTYPE_BR], target.[ITEMBUYERGROUPID] = source.[ITEMBUYERGROUPID], target.[ITEMDIMCOSTPRICE] = source.[ITEMDIMCOSTPRICE], target.[ITEMID] = source.[ITEMID], target.[ITEMTYPE] = source.[ITEMTYPE], target.[NAMEALIAS] = source.[NAMEALIAS], target.[NETWEIGHT] = source.[NETWEIGHT], target.[PBAINVENTITEMGROUPID] = source.[PBAINVENTITEMGROUPID], target.[PBAITEMCONFIGURABLE] = source.[PBAITEMCONFIGURABLE], target.[PRIMARYVENDORID] = source.[PRIMARYVENDORID], target.[PRODGROUPID] = source.[PRODGROUPID], target.[PRODPOOLID] = source.[PRODPOOLID], target.[PRODUCT] = source.[PRODUCT], target.[PROJCATEGORYID] = source.[PROJCATEGORYID], target.[PROPERTYID] = source.[PROPERTYID], target.[PURCHMODEL] = source.[PURCHMODEL], target.[RECID] = source.[RECID], target.[REQGROUPID] = source.[REQGROUPID], target.[SALESCONTRIBUTIONRATIO] = source.[SALESCONTRIBUTIONRATIO], target.[SALESMODEL] = source.[SALESMODEL], target.[SALESPERCENTMARKUP] = source.[SALESPERCENTMARKUP], target.[SALESPRICEMODELBASIC] = source.[SALESPRICEMODELBASIC], target.[SERIALNUMGROUPID] = source.[SERIALNUMGROUPID], target.[SORTCODE] = source.[SORTCODE], target.[TARAWEIGHT] = source.[TARAWEIGHT], target.[TAXATIONORIGIN_BR] = source.[TAXATIONORIGIN_BR], target.[TAXFISCALCLASSIFICATION_BR] = source.[TAXFISCALCLASSIFICATION_BR], target.[TAXSERVICECODE_BR] = source.[TAXSERVICECODE_BR], target.[UNITVOLUME] = source.[UNITVOLUME], target.[USEALTITEMID] = source.[USEALTITEMID], target.[WIDTH] = source.[WIDTH], target.[WMSPICKINGQTYTIME] = source.[WMSPICKINGQTYTIME], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductImage
PRINT 'Upserting into [ax].ECORESPRODUCTIMAGE ..'
MERGE [ax].ECORESPRODUCTIMAGE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
CASE T.c.value('(DefaultImage)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [DEFAULTIMAGE],
ISNULL(T.c.value('(RefRecord)[1]', 'BIGINT'), '0') AS [REFRECORD],
ISNULL(T.c.value('(MediumSize)[1]', 'varbinary(max)'), NULL) AS [MEDIUMSIZE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/DocuRef/EcoResProductImage') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
CASE T.c.value('(DefaultImage)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [DEFAULTIMAGE],
ISNULL(T.c.value('(RefRecord)[1]', 'BIGINT'), '0') AS [REFRECORD],
ISNULL(T.c.value('(MediumSize)[1]', 'varbinary(max)'), NULL) AS [MEDIUMSIZE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/DocuRef/EcoResProductImage') AS T(c)
) AS source ([RECID], [DEFAULTIMAGE], [REFRECORD], [MEDIUMSIZE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [DEFAULTIMAGE], [REFRECORD], [MEDIUMSIZE])
VALUES (source.[RECID], source.[DEFAULTIMAGE], source.[REFRECORD], source.[MEDIUMSIZE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[DEFAULTIMAGE] = source.[DEFAULTIMAGE], target.[REFRECORD] = source.[REFRECORD], target.[MEDIUMSIZE] = source.[MEDIUMSIZE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailInventTable
PRINT 'Upserting into [ax].RETAILINVENTTABLE ..'
MERGE [ax].RETAILINVENTTABLE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(itemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
CASE T.c.value('(zeroPriceValid)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [ZEROPRICEVALID],
CASE T.c.value('(qtyBecomesNegative)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [QTYBECOMESNEGATIVE],
CASE T.c.value('(noDiscountAllowed)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [NODISCOUNTALLOWED],
CASE T.c.value('(keyingInPrice)[1]', 'NVARCHAR(4000)')
WHEN 'NotMandatory' THEN 0
WHEN 'NewPrice' THEN 1
WHEN 'HigherEqual' THEN 2
WHEN 'LowerEqual' THEN 3
WHEN 'NoPrice' THEN 4
ELSE 0
END AS [KEYINGINPRICE],
CASE T.c.value('(scaleItem)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [SCALEITEM],
CASE T.c.value('(keyingInQty)[1]', 'NVARCHAR(4000)')
WHEN 'NotMandatory' THEN 0
WHEN 'KeyIn' THEN 1
WHEN 'NotKeyIn' THEN 2
ELSE 0
END AS [KEYINGINQTY],
ISNULL(T.c.value('(dateBlocked)[1]', 'DATE'), '1900-01-01') AS [DATEBLOCKED],
ISNULL(T.c.value('(dateToBeBlocked)[1]', 'DATE'), '1900-01-01') AS [DATETOBEBLOCKED],
CASE T.c.value('(blockedOnPOS)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [BLOCKEDONPOS],
ISNULL(T.c.value('(baseComparisonUnitCode)[1]', 'NVARCHAR(10)'), '') AS [BASECOMPARISONUNITCODE],
ISNULL(T.c.value('(BarcodeSetupId)[1]', 'NVARCHAR(10)'), '') AS [BARCODESETUPID],
CASE T.c.value('(PrintVariantsShelfLabels)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [PRINTVARIANTSSHELFLABELS],
CASE T.c.value('(useEanStandardBarcode)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [USEEANSTANDARDBARCODE],
CASE T.c.value('(mustKeyInComment)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [MUSTKEYINCOMMENT],
ISNULL(T.c.value('(dateToActivateItem)[1]', 'DATE'), '1900-01-01') AS [DATETOACTIVATEITEM],
CASE T.c.value('(ProhibitReturn_RU)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [PROHIBITRETURN_RU],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/RetailInventTable') AS T(c)
) AS source ([RECID], [ITEMID], [ZEROPRICEVALID], [QTYBECOMESNEGATIVE], [NODISCOUNTALLOWED], [KEYINGINPRICE], [SCALEITEM], [KEYINGINQTY], [DATEBLOCKED], [DATETOBEBLOCKED], [BLOCKEDONPOS], [BASECOMPARISONUNITCODE], [BARCODESETUPID], [PRINTVARIANTSSHELFLABELS], [USEEANSTANDARDBARCODE], [MUSTKEYINCOMMENT], [DATETOACTIVATEITEM], [PROHIBITRETURN_RU], [DATAAREAID])
ON (target.[ITEMID] = source.[ITEMID] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [ITEMID], [ZEROPRICEVALID], [QTYBECOMESNEGATIVE], [NODISCOUNTALLOWED], [KEYINGINPRICE], [SCALEITEM], [KEYINGINQTY], [DATEBLOCKED], [DATETOBEBLOCKED], [BLOCKEDONPOS], [BASECOMPARISONUNITCODE], [BARCODESETUPID], [PRINTVARIANTSSHELFLABELS], [USEEANSTANDARDBARCODE], [MUSTKEYINCOMMENT], [DATETOACTIVATEITEM], [PROHIBITRETURN_RU], [DATAAREAID])
VALUES (source.[RECID], source.[ITEMID], source.[ZEROPRICEVALID], source.[QTYBECOMESNEGATIVE], source.[NODISCOUNTALLOWED], source.[KEYINGINPRICE], source.[SCALEITEM], source.[KEYINGINQTY], source.[DATEBLOCKED], source.[DATETOBEBLOCKED], source.[BLOCKEDONPOS], source.[BASECOMPARISONUNITCODE], source.[BARCODESETUPID], source.[PRINTVARIANTSSHELFLABELS], source.[USEEANSTANDARDBARCODE], source.[MUSTKEYINCOMMENT], source.[DATETOACTIVATEITEM], source.[PROHIBITRETURN_RU], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[ITEMID] = source.[ITEMID], target.[ZEROPRICEVALID] = source.[ZEROPRICEVALID], target.[QTYBECOMESNEGATIVE] = source.[QTYBECOMESNEGATIVE], target.[NODISCOUNTALLOWED] = source.[NODISCOUNTALLOWED], target.[KEYINGINPRICE] = source.[KEYINGINPRICE], target.[SCALEITEM] = source.[SCALEITEM], target.[KEYINGINQTY] = source.[KEYINGINQTY], target.[DATEBLOCKED] = source.[DATEBLOCKED], target.[DATETOBEBLOCKED] = source.[DATETOBEBLOCKED], target.[BLOCKEDONPOS] = source.[BLOCKEDONPOS], target.[BASECOMPARISONUNITCODE] = source.[BASECOMPARISONUNITCODE], target.[BARCODESETUPID] = source.[BARCODESETUPID], target.[PRINTVARIANTSSHELFLABELS] = source.[PRINTVARIANTSSHELFLABELS], target.[USEEANSTANDARDBARCODE] = source.[USEEANSTANDARDBARCODE], target.[MUSTKEYINCOMMENT] = source.[MUSTKEYINCOMMENT], target.[DATETOACTIVATEITEM] = source.[DATETOACTIVATEITEM], target.[PROHIBITRETURN_RU] = source.[PROHIBITRETURN_RU], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- InventDimCombination
PRINT 'Upserting into [ax].INVENTDIMCOMBINATION ..'
MERGE [ax].INVENTDIMCOMBINATION AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(DistinctProductVariant)[1]', 'BIGINT'), '0') AS [DISTINCTPRODUCTVARIANT],
ISNULL(T.c.value('(InventDimId)[1]', 'NVARCHAR(20)'), '') AS [INVENTDIMID],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RetailVariantId)[1]', 'NVARCHAR(10)'), '') AS [RETAILVARIANTID],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination') AS T(c)
) AS source ([DISTINCTPRODUCTVARIANT], [INVENTDIMID], [ITEMID], [RECID], [RETAILVARIANTID], [DATAAREAID])
ON (target.[ITEMID] = source.[ITEMID] AND target.[INVENTDIMID] = source.[INVENTDIMID] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([DISTINCTPRODUCTVARIANT], [INVENTDIMID], [ITEMID], [RECID], [RETAILVARIANTID], [DATAAREAID])
VALUES (source.[DISTINCTPRODUCTVARIANT], source.[INVENTDIMID], source.[ITEMID], source.[RECID], source.[RETAILVARIANTID], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[DISTINCTPRODUCTVARIANT] = source.[DISTINCTPRODUCTVARIANT], target.[INVENTDIMID] = source.[INVENTDIMID], target.[ITEMID] = source.[ITEMID], target.[RECID] = source.[RECID], target.[RETAILVARIANTID] = source.[RETAILVARIANTID], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProduct
PRINT 'Upserting into [ax].ECORESPRODUCT ..'
MERGE [ax].ECORESPRODUCT AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(DisplayProductNumber)[1]', 'NVARCHAR(70)'), '') AS [DISPLAYPRODUCTNUMBER],
CASE T.c.value('(ProductType)[1]', 'NVARCHAR(4000)')
WHEN 'Item' THEN 0
WHEN 'Service' THEN 1
ELSE 0
END AS [PRODUCTTYPE],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(SearchName)[1]', 'NVARCHAR(20)'), '') AS [SEARCHNAME],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [INSTANCERELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct') AS T(c)
UNION
SELECT DISTINCT
ISNULL(T.c.value('(DisplayProductNumber)[1]', 'NVARCHAR(70)'), '') AS [DISPLAYPRODUCTNUMBER],
CASE T.c.value('(ProductType)[1]', 'NVARCHAR(4000)')
WHEN 'Item' THEN 0
WHEN 'Service' THEN 1
ELSE 0
END AS [PRODUCTTYPE],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(SearchName)[1]', 'NVARCHAR(20)'), '') AS [SEARCHNAME],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [INSTANCERELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct') AS T(c)
) AS source ([DISPLAYPRODUCTNUMBER], [PRODUCTTYPE], [RECID], [SEARCHNAME], [RELATIONTYPE], [INSTANCERELATIONTYPE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([DISPLAYPRODUCTNUMBER], [PRODUCTTYPE], [RECID], [SEARCHNAME], [RELATIONTYPE], [INSTANCERELATIONTYPE])
VALUES (source.[DISPLAYPRODUCTNUMBER], source.[PRODUCTTYPE], source.[RECID], source.[SEARCHNAME], source.[RELATIONTYPE], source.[INSTANCERELATIONTYPE])
WHEN MATCHED THEN
UPDATE SET target.[DISPLAYPRODUCTNUMBER] = source.[DISPLAYPRODUCTNUMBER], target.[PRODUCTTYPE] = source.[PRODUCTTYPE], target.[RECID] = source.[RECID], target.[SEARCHNAME] = source.[SEARCHNAME], target.[RELATIONTYPE] = source.[RELATIONTYPE], target.[INSTANCERELATIONTYPE] = source.[INSTANCERELATIONTYPE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResDistinctProductVariant
PRINT 'Upserting into [ax].ECORESDISTINCTPRODUCTVARIANT ..'
MERGE [ax].ECORESDISTINCTPRODUCTVARIANT AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(ProductMaster)[1]', 'BIGINT'), '0') AS [PRODUCTMASTER]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResDistinctProductVariant') AS T(c)
) AS source ([RECID], [PRODUCTMASTER])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [PRODUCTMASTER])
VALUES (source.[RECID], source.[PRODUCTMASTER])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[PRODUCTMASTER] = source.[PRODUCTMASTER];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductCategory
PRINT 'Upserting into [ax].ECORESPRODUCTCATEGORY ..'
MERGE [ax].ECORESPRODUCTCATEGORY AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CategoryHierarchy)[1]', 'BIGINT'), '0') AS [CATEGORYHIERARCHY],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductCategory') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CategoryHierarchy)[1]', 'BIGINT'), '0') AS [CATEGORYHIERARCHY],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductCategory') AS T(c)
) AS source ([RECID], [CATEGORYHIERARCHY], [CATEGORY], [PRODUCT])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CATEGORYHIERARCHY], [CATEGORY], [PRODUCT])
VALUES (source.[RECID], source.[CATEGORYHIERARCHY], source.[CATEGORY], source.[PRODUCT])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CATEGORYHIERARCHY] = source.[CATEGORYHIERARCHY], target.[CATEGORY] = source.[CATEGORY], target.[PRODUCT] = source.[PRODUCT];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductInstanceValue
PRINT 'Upserting into [ax].ECORESPRODUCTINSTANCEVALUE ..'
MERGE [ax].ECORESPRODUCTINSTANCEVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue') AS T(c)
) AS source ([RECID], [PRODUCT])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [PRODUCT])
VALUES (source.[RECID], source.[PRODUCT])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[PRODUCT] = source.[PRODUCT];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResInstanceValue
PRINT 'Upserting into [ax].ECORESINSTANCEVALUE ..'
MERGE [ax].ECORESINSTANCEVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(InstanceRelationType)[1]', 'BIGINT'), '0') AS [INSTANCERELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(InstanceRelationType)[1]', 'BIGINT'), '0') AS [INSTANCERELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue') AS T(c)
) AS source ([RECID], [INSTANCERELATIONTYPE], [RELATIONTYPE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [INSTANCERELATIONTYPE], [RELATIONTYPE])
VALUES (source.[RECID], source.[INSTANCERELATIONTYPE], source.[RELATIONTYPE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[INSTANCERELATIONTYPE] = source.[INSTANCERELATIONTYPE], target.[RELATIONTYPE] = source.[RELATIONTYPE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResAttributeValue
PRINT 'Upserting into [ax].ECORESATTRIBUTEVALUE ..'
MERGE [ax].ECORESATTRIBUTEVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Value)[1]', 'BIGINT'), '0') AS [VALUE],
ISNULL(T.c.value('(InstanceValue)[1]', 'BIGINT'), '0') AS [INSTANCEVALUE],
ISNULL(T.c.value('(Attribute)[1]', 'BIGINT'), '0') AS [ATTRIBUTE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Value)[1]', 'BIGINT'), '0') AS [VALUE],
ISNULL(T.c.value('(InstanceValue)[1]', 'BIGINT'), '0') AS [INSTANCEVALUE],
ISNULL(T.c.value('(Attribute)[1]', 'BIGINT'), '0') AS [ATTRIBUTE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue') AS T(c)
) AS source ([RECID], [VALUE], [INSTANCEVALUE], [ATTRIBUTE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [VALUE], [INSTANCEVALUE], [ATTRIBUTE])
VALUES (source.[RECID], source.[VALUE], source.[INSTANCEVALUE], source.[ATTRIBUTE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[VALUE] = source.[VALUE], target.[INSTANCEVALUE] = source.[INSTANCEVALUE], target.[ATTRIBUTE] = source.[ATTRIBUTE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResValue
PRINT 'Upserting into [ax].ECORESVALUE ..'
MERGE [ax].ECORESVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(InstanceRelationType)[1]', 'BIGINT'), '0') AS [INSTANCERELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(InstanceRelationType)[1]', 'BIGINT'), '0') AS [INSTANCERELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue') AS T(c)
) AS source ([RECID], [INSTANCERELATIONTYPE], [RELATIONTYPE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [INSTANCERELATIONTYPE], [RELATIONTYPE])
VALUES (source.[RECID], source.[INSTANCERELATIONTYPE], source.[RELATIONTYPE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[INSTANCERELATIONTYPE] = source.[INSTANCERELATIONTYPE], target.[RELATIONTYPE] = source.[RELATIONTYPE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResBooleanValue
PRINT 'Upserting into [ax].ECORESBOOLEANVALUE ..'
MERGE [ax].ECORESBOOLEANVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
CASE T.c.value('(BooleanValue)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [BOOLEANVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResBooleanValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
CASE T.c.value('(BooleanValue)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [BOOLEANVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResBooleanValue') AS T(c)
) AS source ([RECID], [BOOLEANVALUE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [BOOLEANVALUE])
VALUES (source.[RECID], source.[BOOLEANVALUE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[BOOLEANVALUE] = source.[BOOLEANVALUE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResDateTimeValue
PRINT 'Upserting into [ax].ECORESDATETIMEVALUE ..'
MERGE [ax].ECORESDATETIMEVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(DateTimeValue)[1]', 'DATETIME'), '1900-01-01 00:00:00.000') AS [DATETIMEVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResDateTimeValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(DateTimeValue)[1]', 'DATETIME'), '1900-01-01 00:00:00.000') AS [DATETIMEVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResDateTimeValue') AS T(c)
) AS source ([RECID], [DATETIMEVALUE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [DATETIMEVALUE])
VALUES (source.[RECID], source.[DATETIMEVALUE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[DATETIMEVALUE] = source.[DATETIMEVALUE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResFloatValue
PRINT 'Upserting into [ax].ECORESFLOATVALUE ..'
MERGE [ax].ECORESFLOATVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(FloatValue)[1]', 'NUMERIC(32, 16)'), '0') AS [FLOATVALUE],
ISNULL(T.c.value('(FloatUnitOfMeasure)[1]', 'BIGINT'), '0') AS [FLOATUNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResFloatValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(FloatValue)[1]', 'NUMERIC(32, 16)'), '0') AS [FLOATVALUE],
ISNULL(T.c.value('(FloatUnitOfMeasure)[1]', 'BIGINT'), '0') AS [FLOATUNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResFloatValue') AS T(c)
) AS source ([RECID], [FLOATVALUE], [FLOATUNITOFMEASURE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [FLOATVALUE], [FLOATUNITOFMEASURE])
VALUES (source.[RECID], source.[FLOATVALUE], source.[FLOATUNITOFMEASURE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[FLOATVALUE] = source.[FLOATVALUE], target.[FLOATUNITOFMEASURE] = source.[FLOATUNITOFMEASURE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResIntValue
PRINT 'Upserting into [ax].ECORESINTVALUE ..'
MERGE [ax].ECORESINTVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(IntValue)[1]', 'INT'), '0') AS [INTVALUE],
ISNULL(T.c.value('(IntUnitOfMeasure)[1]', 'BIGINT'), '0') AS [INTUNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResIntValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(IntValue)[1]', 'INT'), '0') AS [INTVALUE],
ISNULL(T.c.value('(IntUnitOfMeasure)[1]', 'BIGINT'), '0') AS [INTUNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResIntValue') AS T(c)
) AS source ([RECID], [INTVALUE], [INTUNITOFMEASURE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [INTVALUE], [INTUNITOFMEASURE])
VALUES (source.[RECID], source.[INTVALUE], source.[INTUNITOFMEASURE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[INTVALUE] = source.[INTVALUE], target.[INTUNITOFMEASURE] = source.[INTUNITOFMEASURE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResTextValue
PRINT 'Upserting into [ax].ECORESTEXTVALUE ..'
MERGE [ax].ECORESTEXTVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(TextValue)[1]', 'NVARCHAR(1999)'), '') AS [TEXTVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResTextValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(TextValue)[1]', 'NVARCHAR(1999)'), '') AS [TEXTVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResTextValue') AS T(c)
) AS source ([RECID], [TEXTVALUE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [TEXTVALUE])
VALUES (source.[RECID], source.[TEXTVALUE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[TEXTVALUE] = source.[TEXTVALUE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResTextValueTranslation
PRINT 'Upserting into [ax].ECORESTEXTVALUETRANSLATION ..'
MERGE [ax].ECORESTEXTVALUETRANSLATION AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(TextValue)[1]', 'NVARCHAR(1999)'), '') AS [TEXTVALUE],
ISNULL(T.c.value('(TextValueTable)[1]', 'BIGINT'), '0') AS [TEXTVALUETABLE],
ISNULL(T.c.value('(Language)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResTextValue/EcoResTextValueTranslation') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(TextValue)[1]', 'NVARCHAR(1999)'), '') AS [TEXTVALUE],
ISNULL(T.c.value('(TextValueTable)[1]', 'BIGINT'), '0') AS [TEXTVALUETABLE],
ISNULL(T.c.value('(Language)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResTextValue/EcoResTextValueTranslation') AS T(c)
) AS source ([RECID], [TEXTVALUE], [TEXTVALUETABLE], [LANGUAGE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [TEXTVALUE], [TEXTVALUETABLE], [LANGUAGE])
VALUES (source.[RECID], source.[TEXTVALUE], source.[TEXTVALUETABLE], source.[LANGUAGE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[TEXTVALUE] = source.[TEXTVALUE], target.[TEXTVALUETABLE] = source.[TEXTVALUETABLE], target.[LANGUAGE] = source.[LANGUAGE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResCurrencyValue
PRINT 'Upserting into [ax].ECORESCURRENCYVALUE ..'
MERGE [ax].ECORESCURRENCYVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CurrencyValue)[1]', 'NUMERIC(32, 16)'), '0') AS [CURRENCYVALUE],
ISNULL(T.c.value('(CurrencyCode)[1]', 'NVARCHAR(3)'), '') AS [CURRENCYCODE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResCurrencyValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CurrencyValue)[1]', 'NUMERIC(32, 16)'), '0') AS [CURRENCYVALUE],
ISNULL(T.c.value('(CurrencyCode)[1]', 'NVARCHAR(3)'), '') AS [CURRENCYCODE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResCurrencyValue') AS T(c)
) AS source ([RECID], [CURRENCYVALUE], [CURRENCYCODE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CURRENCYVALUE], [CURRENCYCODE])
VALUES (source.[RECID], source.[CURRENCYVALUE], source.[CURRENCYCODE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CURRENCYVALUE] = source.[CURRENCYVALUE], target.[CURRENCYCODE] = source.[CURRENCYCODE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResReferenceValue
PRINT 'Upserting into [ax].ECORESREFERENCEVALUE ..'
MERGE [ax].ECORESREFERENCEVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RefFieldId)[1]', 'INT'), '0') AS [REFFIELDID],
ISNULL(T.c.value('(RefRecId)[1]', 'BIGINT'), '0') AS [REFRECID],
ISNULL(T.c.value('(RefTableId)[1]', 'INT'), '0') AS [REFTABLEID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResReferenceValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RefFieldId)[1]', 'INT'), '0') AS [REFFIELDID],
ISNULL(T.c.value('(RefRecId)[1]', 'BIGINT'), '0') AS [REFRECID],
ISNULL(T.c.value('(RefTableId)[1]', 'INT'), '0') AS [REFTABLEID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductInstanceValue/EcoResInstanceValue/EcoResAttributeValue/EcoResValue/EcoResReferenceValue') AS T(c)
) AS source ([RECID], [REFFIELDID], [REFRECID], [REFTABLEID])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [REFFIELDID], [REFRECID], [REFTABLEID])
VALUES (source.[RECID], source.[REFFIELDID], source.[REFRECID], source.[REFTABLEID])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[REFFIELDID] = source.[REFFIELDID], target.[REFRECID] = source.[REFRECID], target.[REFTABLEID] = source.[REFTABLEID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResTrackingDimensionGroupProduct
PRINT 'Upserting into [ax].ECORESTRACKINGDIMENSIONGROUPPRODUCT ..'
MERGE [ax].ECORESTRACKINGDIMENSIONGROUPPRODUCT AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(TrackingDimensionGroup)[1]', 'BIGINT'), '0') AS [TRACKINGDIMENSIONGROUP]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResTrackingDimensionGroupProduct') AS T(c)
UNION
SELECT DISTINCT
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(TrackingDimensionGroup)[1]', 'BIGINT'), '0') AS [TRACKINGDIMENSIONGROUP]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResTrackingDimensionGroupProduct') AS T(c)
) AS source ([PRODUCT], [RECID], [TRACKINGDIMENSIONGROUP])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([PRODUCT], [RECID], [TRACKINGDIMENSIONGROUP])
VALUES (source.[PRODUCT], source.[RECID], source.[TRACKINGDIMENSIONGROUP])
WHEN MATCHED THEN
UPDATE SET target.[PRODUCT] = source.[PRODUCT], target.[RECID] = source.[RECID], target.[TRACKINGDIMENSIONGROUP] = source.[TRACKINGDIMENSIONGROUP];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductTranslation
PRINT 'Upserting into [ax].ECORESPRODUCTTRANSLATION ..'
MERGE [ax].ECORESPRODUCTTRANSLATION AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(Description)[1]', 'NVARCHAR(1000)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(60)'), '') AS [NAME],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
T.c.value('(../RecId)[1]', 'BIGINT') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductTranslation') AS T(c)
UNION
SELECT DISTINCT
ISNULL(T.c.value('(Description)[1]', 'NVARCHAR(1000)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(60)'), '') AS [NAME],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
T.c.value('(../RecId)[1]', 'BIGINT') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductTranslation') AS T(c)
) AS source ([DESCRIPTION], [LANGUAGEID], [NAME], [RECID], [PRODUCT])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([DESCRIPTION], [LANGUAGEID], [NAME], [RECID], [PRODUCT])
VALUES (source.[DESCRIPTION], source.[LANGUAGEID], source.[NAME], source.[RECID], source.[PRODUCT])
WHEN MATCHED THEN
UPDATE SET target.[DESCRIPTION] = source.[DESCRIPTION], target.[LANGUAGEID] = source.[LANGUAGEID], target.[NAME] = source.[NAME], target.[RECID] = source.[RECID], target.[PRODUCT] = source.[PRODUCT];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductVariantDimensionValue
PRINT 'Upserting into [ax].ECORESPRODUCTVARIANTDIMENSIONVALUE ..'
MERGE [ax].ECORESPRODUCTVARIANTDIMENSIONVALUE AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(DistinctProductVariant)[1]', 'BIGINT'), '0') AS [DISTINCTPRODUCTVARIANT],
ISNULL(T.c.value('(ProductDimensionAttribute)[1]', 'BIGINT'), '0') AS [PRODUCTDIMENSIONATTRIBUTE],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [INSTANCERELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductVariantDimensionValue') AS T(c)
) AS source ([DISTINCTPRODUCTVARIANT], [PRODUCTDIMENSIONATTRIBUTE], [RECID], [RELATIONTYPE], [INSTANCERELATIONTYPE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([DISTINCTPRODUCTVARIANT], [PRODUCTDIMENSIONATTRIBUTE], [RECID], [RELATIONTYPE], [INSTANCERELATIONTYPE])
VALUES (source.[DISTINCTPRODUCTVARIANT], source.[PRODUCTDIMENSIONATTRIBUTE], source.[RECID], source.[RELATIONTYPE], source.[INSTANCERELATIONTYPE])
WHEN MATCHED THEN
UPDATE SET target.[DISTINCTPRODUCTVARIANT] = source.[DISTINCTPRODUCTVARIANT], target.[PRODUCTDIMENSIONATTRIBUTE] = source.[PRODUCTDIMENSIONATTRIBUTE], target.[RECID] = source.[RECID], target.[RELATIONTYPE] = source.[RELATIONTYPE], target.[INSTANCERELATIONTYPE] = source.[INSTANCERELATIONTYPE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductVariantColor
PRINT 'Upserting into [ax].ECORESPRODUCTVARIANTCOLOR ..'
MERGE [ax].ECORESPRODUCTVARIANTCOLOR AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Color)[1]', 'BIGINT'), '0') AS [COLOR]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductVariantDimensionValue/EcoResProductVariantColor') AS T(c)
) AS source ([RECID], [COLOR])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [COLOR])
VALUES (source.[RECID], source.[COLOR])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[COLOR] = source.[COLOR];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductVariantConfiguration
PRINT 'Upserting into [ax].ECORESPRODUCTVARIANTCONFIGURATION ..'
MERGE [ax].ECORESPRODUCTVARIANTCONFIGURATION AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Configuration)[1]', 'BIGINT'), '0') AS [CONFIGURATION]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductVariantDimensionValue/EcoResProductVariantConfiguration') AS T(c)
) AS source ([RECID], [CONFIGURATION])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CONFIGURATION])
VALUES (source.[RECID], source.[CONFIGURATION])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CONFIGURATION] = source.[CONFIGURATION];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductVariantSize
PRINT 'Upserting into [ax].ECORESPRODUCTVARIANTSIZE ..'
MERGE [ax].ECORESPRODUCTVARIANTSIZE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Size)[1]', 'BIGINT'), '0') AS [SIZE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductVariantDimensionValue/EcoResProductVariantSize') AS T(c)
) AS source ([RECID], [SIZE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [SIZE])
VALUES (source.[RECID], source.[SIZE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[SIZE] = source.[SIZE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductVariantStyle
PRINT 'Upserting into [ax].ECORESPRODUCTVARIANTSTYLE ..'
MERGE [ax].ECORESPRODUCTVARIANTSTYLE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Style)[1]', 'BIGINT'), '0') AS [STYLE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/EcoResProductVariantDimensionValue/EcoResProductVariantStyle') AS T(c)
) AS source ([RECID], [STYLE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [STYLE])
VALUES (source.[RECID], source.[STYLE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[STYLE] = source.[STYLE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailGroupMemberLine
PRINT 'Upserting into [ax].RETAILGROUPMEMBERLINE ..'
MERGE [ax].RETAILGROUPMEMBERLINE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT],
ISNULL(T.c.value('(Variant)[1]', 'BIGINT'), '0') AS [VARIANT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/RetailGroupMemberLine') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT],
ISNULL(T.c.value('(Variant)[1]', 'BIGINT'), '0') AS [VARIANT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/RetailGroupMemberLine') AS T(c)
) AS source ([RECID], [CATEGORY], [PRODUCT], [VARIANT])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CATEGORY], [PRODUCT], [VARIANT])
VALUES (source.[RECID], source.[CATEGORY], source.[PRODUCT], source.[VARIANT])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CATEGORY] = source.[CATEGORY], target.[PRODUCT] = source.[PRODUCT], target.[VARIANT] = source.[VARIANT];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailSpecialCategoryMember
PRINT 'Upserting into [ax].RETAILSPECIALCATEGORYMEMBER ..'
MERGE [ax].RETAILSPECIALCATEGORYMEMBER AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(RetailGroupMember)[1]', 'BIGINT'), '0') AS [RETAILGROUPMEMBER]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/RetailGroupMemberLine/RetailSpecialCategoryMember') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(RetailGroupMember)[1]', 'BIGINT'), '0') AS [RETAILGROUPMEMBER]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/RetailGroupMemberLine/RetailSpecialCategoryMember') AS T(c)
) AS source ([RECID], [CATEGORY], [RETAILGROUPMEMBER])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CATEGORY], [RETAILGROUPMEMBER])
VALUES (source.[RECID], source.[CATEGORY], source.[RETAILGROUPMEMBER])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CATEGORY] = source.[CATEGORY], target.[RETAILGROUPMEMBER] = source.[RETAILGROUPMEMBER];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailPubCatalogProduct
PRINT 'Upserting into [ax].RETAILPUBCATALOGPRODUCT ..'
MERGE [ax].RETAILPUBCATALOGPRODUCT AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Catalog)[1]', 'BIGINT'), '0') AS [CATALOG],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/RetailPubCatalogProduct') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Catalog)[1]', 'BIGINT'), '0') AS [CATALOG],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/RetailPubCatalogProduct') AS T(c)
) AS source ([RECID], [CATALOG], [ORIGIN], [PRODUCT])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CATALOG], [ORIGIN], [PRODUCT])
VALUES (source.[RECID], source.[CATALOG], source.[ORIGIN], source.[PRODUCT])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CATALOG] = source.[CATALOG], target.[ORIGIN] = source.[ORIGIN], target.[PRODUCT] = source.[PRODUCT];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailPubCatalogProductCategory
PRINT 'Upserting into [ax].RETAILPUBCATALOGPRODUCTCATEGORY ..'
MERGE [ax].RETAILPUBCATALOGPRODUCTCATEGORY AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CatalogProduct)[1]', 'BIGINT'), '0') AS [CATALOGPRODUCT],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(CategoryHierarchy)[1]', 'BIGINT'), '0') AS [CATEGORYHIERARCHY],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/RetailPubCatalogProduct/RetailPubCatalogProductCategory') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CatalogProduct)[1]', 'BIGINT'), '0') AS [CATALOGPRODUCT],
ISNULL(T.c.value('(Category)[1]', 'BIGINT'), '0') AS [CATEGORY],
ISNULL(T.c.value('(CategoryHierarchy)[1]', 'BIGINT'), '0') AS [CATEGORYHIERARCHY],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/RetailPubCatalogProduct/RetailPubCatalogProductCategory') AS T(c)
) AS source ([RECID], [CATALOGPRODUCT], [CATEGORY], [CATEGORYHIERARCHY], [ORIGIN])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CATALOGPRODUCT], [CATEGORY], [CATEGORYHIERARCHY], [ORIGIN])
VALUES (source.[RECID], source.[CATALOGPRODUCT], source.[CATEGORY], source.[CATEGORYHIERARCHY], source.[ORIGIN])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CATALOGPRODUCT] = source.[CATALOGPRODUCT], target.[CATEGORY] = source.[CATEGORY], target.[CATEGORYHIERARCHY] = source.[CATEGORYHIERARCHY], target.[ORIGIN] = source.[ORIGIN];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailPubCatalogProductRelation
PRINT 'Upserting into [ax].RETAILPUBCATALOGPRODUCTRELATION ..'
MERGE [ax].RETAILPUBCATALOGPRODUCTRELATION AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CatalogProduct)[1]', 'BIGINT'), '0') AS [CATALOGPRODUCT],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN],
ISNULL(T.c.value('(ProductRelationType)[1]', 'BIGINT'), '0') AS [PRODUCTRELATIONTYPE],
ISNULL(T.c.value('(RelatedProduct)[1]', 'BIGINT'), '0') AS [RELATEDPRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/RetailPubCatalogProduct/RetailPubCatalogProductRelation') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CatalogProduct)[1]', 'BIGINT'), '0') AS [CATALOGPRODUCT],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN],
ISNULL(T.c.value('(ProductRelationType)[1]', 'BIGINT'), '0') AS [PRODUCTRELATIONTYPE],
ISNULL(T.c.value('(RelatedProduct)[1]', 'BIGINT'), '0') AS [RELATEDPRODUCT]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/RetailPubCatalogProduct/RetailPubCatalogProductRelation') AS T(c)
) AS source ([RECID], [CATALOGPRODUCT], [ORIGIN], [PRODUCTRELATIONTYPE], [RELATEDPRODUCT])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CATALOGPRODUCT], [ORIGIN], [PRODUCTRELATIONTYPE], [RELATEDPRODUCT])
VALUES (source.[RECID], source.[CATALOGPRODUCT], source.[ORIGIN], source.[PRODUCTRELATIONTYPE], source.[RELATEDPRODUCT])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CATALOGPRODUCT] = source.[CATALOGPRODUCT], target.[ORIGIN] = source.[ORIGIN], target.[PRODUCTRELATIONTYPE] = source.[PRODUCTRELATIONTYPE], target.[RELATEDPRODUCT] = source.[RELATEDPRODUCT];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailPubCatalogProductRelationExclusion
PRINT 'Upserting into [ax].RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION ..'
MERGE [ax].RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CatalogProduct)[1]', 'BIGINT'), '0') AS [CATALOGPRODUCT],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN],
ISNULL(T.c.value('(ProductRelation)[1]', 'BIGINT'), '0') AS [PRODUCTRELATION]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/RetailPubCatalogProduct/RetailPubCatalogProductRelationExclusion') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(CatalogProduct)[1]', 'BIGINT'), '0') AS [CATALOGPRODUCT],
ISNULL(T.c.value('(Origin)[1]', 'BIGINT'), '0') AS [ORIGIN],
ISNULL(T.c.value('(ProductRelation)[1]', 'BIGINT'), '0') AS [PRODUCTRELATION]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/RetailPubCatalogProduct/RetailPubCatalogProductRelationExclusion') AS T(c)
) AS source ([RECID], [CATALOGPRODUCT], [ORIGIN], [PRODUCTRELATION])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CATALOGPRODUCT], [ORIGIN], [PRODUCTRELATION])
VALUES (source.[RECID], source.[CATALOGPRODUCT], source.[ORIGIN], source.[PRODUCTRELATION])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CATALOGPRODUCT] = source.[CATALOGPRODUCT], target.[ORIGIN] = source.[ORIGIN], target.[PRODUCTRELATION] = source.[PRODUCTRELATION];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailPubProductAttributeValue
PRINT 'Upserting into [ax].RETAILPUBPRODUCTATTRIBUTEVALUE ..'
MERGE [ax].RETAILPUBPRODUCTATTRIBUTEVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Attribute)[1]', 'BIGINT'), '0') AS [ATTRIBUTE],
ISNULL(T.c.value('(Catalog)[1]', 'BIGINT'), '0') AS [CATALOG],
ISNULL(T.c.value('(DateTimeValue)[1]', 'DATETIME'), '1900-01-01 00:00:00.000') AS [DATETIMEVALUE],
ISNULL(T.c.value('(FloatValue)[1]', 'NUMERIC(32, 16)'), '0') AS [FLOATVALUE],
ISNULL(T.c.value('(InternalOrganization)[1]', 'BIGINT'), '0') AS [INTERNALORGANIZATION],
ISNULL(T.c.value('(IntValue)[1]', 'INT'), '0') AS [INTVALUE],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT],
ISNULL(T.c.value('(TextValue)[1]', 'NVARCHAR(1999)'), '') AS [TEXTVALUE],
ISNULL(T.c.value('(UnitOfMeasure)[1]', 'BIGINT'), '0') AS [UNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/EcoResProduct/RetailPubProductAttributeValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Attribute)[1]', 'BIGINT'), '0') AS [ATTRIBUTE],
ISNULL(T.c.value('(Catalog)[1]', 'BIGINT'), '0') AS [CATALOG],
ISNULL(T.c.value('(DateTimeValue)[1]', 'DATETIME'), '1900-01-01 00:00:00.000') AS [DATETIMEVALUE],
ISNULL(T.c.value('(FloatValue)[1]', 'NUMERIC(32, 16)'), '0') AS [FLOATVALUE],
ISNULL(T.c.value('(InternalOrganization)[1]', 'BIGINT'), '0') AS [INTERNALORGANIZATION],
ISNULL(T.c.value('(IntValue)[1]', 'INT'), '0') AS [INTVALUE],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Product)[1]', 'BIGINT'), '0') AS [PRODUCT],
ISNULL(T.c.value('(TextValue)[1]', 'NVARCHAR(1999)'), '') AS [TEXTVALUE],
ISNULL(T.c.value('(UnitOfMeasure)[1]', 'BIGINT'), '0') AS [UNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/RetailPubProductAttributeValue') AS T(c)
) AS source ([RECID], [ATTRIBUTE], [CATALOG], [DATETIMEVALUE], [FLOATVALUE], [INTERNALORGANIZATION], [INTVALUE], [LANGUAGEID], [PRODUCT], [TEXTVALUE], [UNITOFMEASURE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [ATTRIBUTE], [CATALOG], [DATETIMEVALUE], [FLOATVALUE], [INTERNALORGANIZATION], [INTVALUE], [LANGUAGEID], [PRODUCT], [TEXTVALUE], [UNITOFMEASURE])
VALUES (source.[RECID], source.[ATTRIBUTE], source.[CATALOG], source.[DATETIMEVALUE], source.[FLOATVALUE], source.[INTERNALORGANIZATION], source.[INTVALUE], source.[LANGUAGEID], source.[PRODUCT], source.[TEXTVALUE], source.[UNITOFMEASURE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[ATTRIBUTE] = source.[ATTRIBUTE], target.[CATALOG] = source.[CATALOG], target.[DATETIMEVALUE] = source.[DATETIMEVALUE], target.[FLOATVALUE] = source.[FLOATVALUE], target.[INTERNALORGANIZATION] = source.[INTERNALORGANIZATION], target.[INTVALUE] = source.[INTVALUE], target.[LANGUAGEID] = source.[LANGUAGEID], target.[PRODUCT] = source.[PRODUCT], target.[TEXTVALUE] = source.[TEXTVALUE], target.[UNITOFMEASURE] = source.[UNITOFMEASURE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailKitVariantComponent
PRINT 'Upserting into [ax].RETAILKITVARIANTCOMPONENT ..'
MERGE [ax].RETAILKITVARIANTCOMPONENT AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Component)[1]', 'BIGINT'), '0') AS [COMPONENT],
ISNULL(T.c.value('(ComponentRecId)[1]', 'BIGINT'), '0') AS [COMPONENTRECID],
ISNULL(T.c.value('(KitVariant)[1]', 'BIGINT'), '0') AS [KITVARIANT],
ISNULL(T.c.value('(Quantity)[1]', 'NUMERIC(32, 16)'), '0') AS [QUANTITY],
ISNULL(T.c.value('(UnitOfMeasure)[1]', 'BIGINT'), '0') AS [UNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/RetailKitVariantComponent') AS T(c)
) AS source ([RECID], [COMPONENT], [COMPONENTRECID], [KITVARIANT], [QUANTITY], [UNITOFMEASURE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [COMPONENT], [COMPONENTRECID], [KITVARIANT], [QUANTITY], [UNITOFMEASURE])
VALUES (source.[RECID], source.[COMPONENT], source.[COMPONENTRECID], source.[KITVARIANT], source.[QUANTITY], source.[UNITOFMEASURE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[COMPONENT] = source.[COMPONENT], target.[COMPONENTRECID] = source.[COMPONENTRECID], target.[KITVARIANT] = source.[KITVARIANT], target.[QUANTITY] = source.[QUANTITY], target.[UNITOFMEASURE] = source.[UNITOFMEASURE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- InventDim
PRINT 'Upserting into [ax].INVENTDIM ..'
MERGE [ax].INVENTDIM AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(ConfigId)[1]', 'NVARCHAR(10)'), '') AS [CONFIGID],
ISNULL(T.c.value('(InventBatchId)[1]', 'NVARCHAR(20)'), '') AS [INVENTBATCHID],
ISNULL(T.c.value('(InventColorId)[1]', 'NVARCHAR(10)'), '') AS [INVENTCOLORID],
ISNULL(T.c.value('(InventDimId)[1]', 'NVARCHAR(20)'), '') AS [INVENTDIMID],
ISNULL(T.c.value('(InventGTDId_RU)[1]', 'NVARCHAR(30)'), '') AS [INVENTGTDID_RU],
ISNULL(T.c.value('(InventLocationId)[1]', 'NVARCHAR(10)'), '') AS [INVENTLOCATIONID],
ISNULL(T.c.value('(InventOwnerId_RU)[1]', 'NVARCHAR(20)'), '') AS [INVENTOWNERID_RU],
ISNULL(T.c.value('(InventProfileId_RU)[1]', 'NVARCHAR(10)'), '') AS [INVENTPROFILEID_RU],
ISNULL(T.c.value('(InventSerialId)[1]', 'NVARCHAR(20)'), '') AS [INVENTSERIALID],
ISNULL(T.c.value('(InventSiteId)[1]', 'NVARCHAR(10)'), '') AS [INVENTSITEID],
ISNULL(T.c.value('(InventSizeId)[1]', 'NVARCHAR(10)'), '') AS [INVENTSIZEID],
ISNULL(T.c.value('(InventStyleId)[1]', 'NVARCHAR(10)'), '') AS [INVENTSTYLEID],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(WMSLocationId)[1]', 'NVARCHAR(10)'), '') AS [WMSLOCATIONID],
ISNULL(T.c.value('(WMSPalletId)[1]', 'NVARCHAR(18)'), '') AS [WMSPALLETID],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventDimCombination/InventDim') AS T(c)
) AS source ([CONFIGID], [INVENTBATCHID], [INVENTCOLORID], [INVENTDIMID], [INVENTGTDID_RU], [INVENTLOCATIONID], [INVENTOWNERID_RU], [INVENTPROFILEID_RU], [INVENTSERIALID], [INVENTSITEID], [INVENTSIZEID], [INVENTSTYLEID], [RECID], [WMSLOCATIONID], [WMSPALLETID], [DATAAREAID])
ON (target.[INVENTDIMID] = source.[INVENTDIMID] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([CONFIGID], [INVENTBATCHID], [INVENTCOLORID], [INVENTDIMID], [INVENTGTDID_RU], [INVENTLOCATIONID], [INVENTOWNERID_RU], [INVENTPROFILEID_RU], [INVENTSERIALID], [INVENTSITEID], [INVENTSIZEID], [INVENTSTYLEID], [RECID], [WMSLOCATIONID], [WMSPALLETID], [DATAAREAID])
VALUES (source.[CONFIGID], source.[INVENTBATCHID], source.[INVENTCOLORID], source.[INVENTDIMID], source.[INVENTGTDID_RU], source.[INVENTLOCATIONID], source.[INVENTOWNERID_RU], source.[INVENTPROFILEID_RU], source.[INVENTSERIALID], source.[INVENTSITEID], source.[INVENTSIZEID], source.[INVENTSTYLEID], source.[RECID], source.[WMSLOCATIONID], source.[WMSPALLETID], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[CONFIGID] = source.[CONFIGID], target.[INVENTBATCHID] = source.[INVENTBATCHID], target.[INVENTCOLORID] = source.[INVENTCOLORID], target.[INVENTDIMID] = source.[INVENTDIMID], target.[INVENTGTDID_RU] = source.[INVENTGTDID_RU], target.[INVENTLOCATIONID] = source.[INVENTLOCATIONID], target.[INVENTOWNERID_RU] = source.[INVENTOWNERID_RU], target.[INVENTPROFILEID_RU] = source.[INVENTPROFILEID_RU], target.[INVENTSERIALID] = source.[INVENTSERIALID], target.[INVENTSITEID] = source.[INVENTSITEID], target.[INVENTSIZEID] = source.[INVENTSIZEID], target.[INVENTSTYLEID] = source.[INVENTSTYLEID], target.[RECID] = source.[RECID], target.[WMSLOCATIONID] = source.[WMSLOCATIONID], target.[WMSPALLETID] = source.[WMSPALLETID], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- InventItemBarcode
PRINT 'Upserting into [ax].INVENTITEMBARCODE ..'
MERGE [ax].INVENTITEMBARCODE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(itemBarCode)[1]', 'NVARCHAR(80)'), '') AS [ITEMBARCODE],
ISNULL(T.c.value('(itemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
ISNULL(T.c.value('(inventDimId)[1]', 'NVARCHAR(20)'), '') AS [INVENTDIMID],
ISNULL(T.c.value('(barcodeSetupId)[1]', 'NVARCHAR(10)'), '') AS [BARCODESETUPID],
CASE T.c.value('(useForPrinting)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [USEFORPRINTING],
CASE T.c.value('(useForInput)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [USEFORINPUT],
ISNULL(T.c.value('(description)[1]', 'NVARCHAR(60)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(qty)[1]', 'NUMERIC(32, 16)'), '0') AS [QTY],
ISNULL(T.c.value('(UnitID)[1]', 'NVARCHAR(10)'), '') AS [UNITID],
ISNULL(T.c.value('(RetailVariantId)[1]', 'NVARCHAR(10)'), '') AS [RETAILVARIANTID],
CASE T.c.value('(RetailShowForItem)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [RETAILSHOWFORITEM],
CASE T.c.value('(Blocked)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [BLOCKED],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventItemBarcode') AS T(c)
) AS source ([RECID], [ITEMBARCODE], [ITEMID], [INVENTDIMID], [BARCODESETUPID], [USEFORPRINTING], [USEFORINPUT], [DESCRIPTION], [QTY], [UNITID], [RETAILVARIANTID], [RETAILSHOWFORITEM], [BLOCKED], [DATAAREAID])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [ITEMBARCODE], [ITEMID], [INVENTDIMID], [BARCODESETUPID], [USEFORPRINTING], [USEFORINPUT], [DESCRIPTION], [QTY], [UNITID], [RETAILVARIANTID], [RETAILSHOWFORITEM], [BLOCKED], [DATAAREAID])
VALUES (source.[RECID], source.[ITEMBARCODE], source.[ITEMID], source.[INVENTDIMID], source.[BARCODESETUPID], source.[USEFORPRINTING], source.[USEFORINPUT], source.[DESCRIPTION], source.[QTY], source.[UNITID], source.[RETAILVARIANTID], source.[RETAILSHOWFORITEM], source.[BLOCKED], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[ITEMBARCODE] = source.[ITEMBARCODE], target.[ITEMID] = source.[ITEMID], target.[INVENTDIMID] = source.[INVENTDIMID], target.[BARCODESETUPID] = source.[BARCODESETUPID], target.[USEFORPRINTING] = source.[USEFORPRINTING], target.[USEFORINPUT] = source.[USEFORINPUT], target.[DESCRIPTION] = source.[DESCRIPTION], target.[QTY] = source.[QTY], target.[UNITID] = source.[UNITID], target.[RETAILVARIANTID] = source.[RETAILVARIANTID], target.[RETAILSHOWFORITEM] = source.[RETAILSHOWFORITEM], target.[BLOCKED] = source.[BLOCKED], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- InventSerial
PRINT 'Upserting into [ax].INVENTSERIAL ..'
MERGE [ax].INVENTSERIAL AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(Description)[1]', 'NVARCHAR(max)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(InventSerialId)[1]', 'NVARCHAR(20)'), '') AS [INVENTSERIALID],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
ISNULL(T.c.value('(ProdDate)[1]', 'DATE'), '1900-01-01') AS [PRODDATE],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RFIDTagId)[1]', 'NVARCHAR(24)'), '') AS [RFIDTAGID],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventSerial') AS T(c)
) AS source ([DESCRIPTION], [INVENTSERIALID], [ITEMID], [PRODDATE], [RECID], [RFIDTAGID], [DATAAREAID])
ON (target.[ITEMID] = source.[ITEMID] AND target.[INVENTSERIALID] = source.[INVENTSERIALID] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([DESCRIPTION], [INVENTSERIALID], [ITEMID], [PRODDATE], [RECID], [RFIDTAGID], [DATAAREAID])
VALUES (source.[DESCRIPTION], source.[INVENTSERIALID], source.[ITEMID], source.[PRODDATE], source.[RECID], source.[RFIDTAGID], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[DESCRIPTION] = source.[DESCRIPTION], target.[INVENTSERIALID] = source.[INVENTSERIALID], target.[ITEMID] = source.[ITEMID], target.[PRODDATE] = source.[PRODDATE], target.[RECID] = source.[RECID], target.[RFIDTAGID] = source.[RFIDTAGID], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailDlvModeProductExploded
PRINT 'Upserting into [ax].RETAILDLVMODEPRODUCTEXPLODED ..'
MERGE [ax].RETAILDLVMODEPRODUCTEXPLODED AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(DlvMode)[1]', 'BIGINT'), '0') AS [DLVMODE],
ISNULL(T.c.value('(InventDim)[1]', 'NVARCHAR(20)'), '') AS [INVENTDIM],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/RetailDlvModeProductExploded') AS T(c)
) AS source ([RECID], [DLVMODE], [INVENTDIM], [ITEMID], [DATAAREAID])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [DLVMODE], [INVENTDIM], [ITEMID], [DATAAREAID])
VALUES (source.[RECID], source.[DLVMODE], source.[INVENTDIM], source.[ITEMID], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[DLVMODE] = source.[DLVMODE], target.[INVENTDIM] = source.[INVENTDIM], target.[ITEMID] = source.[ITEMID], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailInventLinkedItem
PRINT 'Upserting into [ax].RETAILINVENTLINKEDITEM ..'
MERGE [ax].RETAILINVENTLINKEDITEM AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(itemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
ISNULL(T.c.value('(unit)[1]', 'NVARCHAR(10)'), '') AS [UNIT],
ISNULL(T.c.value('(linkedItemId)[1]', 'NVARCHAR(20)'), '') AS [LINKEDITEMID],
ISNULL(T.c.value('(qty)[1]', 'NUMERIC(32, 16)'), '0') AS [QTY],
CASE T.c.value('(blocked)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [BLOCKED],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/RetailInventLinkedItem') AS T(c)
) AS source ([RECID], [ITEMID], [UNIT], [LINKEDITEMID], [QTY], [BLOCKED], [DATAAREAID])
ON (target.[ITEMID] = source.[ITEMID] AND target.[UNIT] = source.[UNIT] AND target.[LINKEDITEMID] = source.[LINKEDITEMID] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [ITEMID], [UNIT], [LINKEDITEMID], [QTY], [BLOCKED], [DATAAREAID])
VALUES (source.[RECID], source.[ITEMID], source.[UNIT], source.[LINKEDITEMID], source.[QTY], source.[BLOCKED], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[ITEMID] = source.[ITEMID], target.[UNIT] = source.[UNIT], target.[LINKEDITEMID] = source.[LINKEDITEMID], target.[QTY] = source.[QTY], target.[BLOCKED] = source.[BLOCKED], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- InventTableModule
PRINT 'Upserting into [ax].INVENTTABLEMODULE ..'
MERGE [ax].INVENTTABLEMODULE AS target
USING (
SELECT DISTINCT
CASE T.c.value('(AllocateMarkup)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [ALLOCATEMARKUP],
CASE T.c.value('(EndDisc)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [ENDDISC],
CASE T.c.value('(InterCompanyBlocked)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [INTERCOMPANYBLOCKED],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
ISNULL(T.c.value('(LineDisc)[1]', 'NVARCHAR(10)'), '') AS [LINEDISC],
ISNULL(T.c.value('(Markup)[1]', 'NUMERIC(32, 16)'), '0') AS [MARKUP],
ISNULL(T.c.value('(MarkupGroupId)[1]', 'NVARCHAR(10)'), '') AS [MARKUPGROUPID],
ISNULL(T.c.value('(MaximumRetailPrice_IN)[1]', 'NUMERIC(32, 16)'), '0') AS [MAXIMUMRETAILPRICE_IN],
CASE T.c.value('(ModuleType)[1]', 'NVARCHAR(4000)')
WHEN 'Invent' THEN 0
WHEN 'Purch' THEN 1
WHEN 'Sales' THEN 2
ELSE 0
END AS [MODULETYPE],
ISNULL(T.c.value('(MultiLineDisc)[1]', 'NVARCHAR(10)'), '') AS [MULTILINEDISC],
ISNULL(T.c.value('(OverDeliveryPct)[1]', 'NUMERIC(32, 16)'), '0') AS [OVERDELIVERYPCT],
ISNULL(T.c.value('(Price)[1]', 'NUMERIC(32, 16)'), '0') AS [PRICE],
ISNULL(T.c.value('(PriceDate)[1]', 'DATE'), '1900-01-01') AS [PRICEDATE],
ISNULL(T.c.value('(PriceQty)[1]', 'NUMERIC(32, 16)'), '0') AS [PRICEQTY],
ISNULL(T.c.value('(PriceUnit)[1]', 'NUMERIC(32, 16)'), '0') AS [PRICEUNIT],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(SuppItemGroupId)[1]', 'NVARCHAR(10)'), '') AS [SUPPITEMGROUPID],
ISNULL(T.c.value('(TaxItemGroupId)[1]', 'NVARCHAR(10)'), '') AS [TAXITEMGROUPID],
ISNULL(T.c.value('(UnderDeliveryPct)[1]', 'NUMERIC(32, 16)'), '0') AS [UNDERDELIVERYPCT],
ISNULL(T.c.value('(UnitId)[1]', 'NVARCHAR(10)'), '') AS [UNITID],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventTableModule') AS T(c)
) AS source ([ALLOCATEMARKUP], [ENDDISC], [INTERCOMPANYBLOCKED], [ITEMID], [LINEDISC], [MARKUP], [MARKUPGROUPID], [MAXIMUMRETAILPRICE_IN], [MODULETYPE], [MULTILINEDISC], [OVERDELIVERYPCT], [PRICE], [PRICEDATE], [PRICEQTY], [PRICEUNIT], [RECID], [SUPPITEMGROUPID], [TAXITEMGROUPID], [UNDERDELIVERYPCT], [UNITID], [DATAAREAID])
ON (target.[ITEMID] = source.[ITEMID] AND target.[MODULETYPE] = source.[MODULETYPE] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([ALLOCATEMARKUP], [ENDDISC], [INTERCOMPANYBLOCKED], [ITEMID], [LINEDISC], [MARKUP], [MARKUPGROUPID], [MAXIMUMRETAILPRICE_IN], [MODULETYPE], [MULTILINEDISC], [OVERDELIVERYPCT], [PRICE], [PRICEDATE], [PRICEQTY], [PRICEUNIT], [RECID], [SUPPITEMGROUPID], [TAXITEMGROUPID], [UNDERDELIVERYPCT], [UNITID], [DATAAREAID])
VALUES (source.[ALLOCATEMARKUP], source.[ENDDISC], source.[INTERCOMPANYBLOCKED], source.[ITEMID], source.[LINEDISC], source.[MARKUP], source.[MARKUPGROUPID], source.[MAXIMUMRETAILPRICE_IN], source.[MODULETYPE], source.[MULTILINEDISC], source.[OVERDELIVERYPCT], source.[PRICE], source.[PRICEDATE], source.[PRICEQTY], source.[PRICEUNIT], source.[RECID], source.[SUPPITEMGROUPID], source.[TAXITEMGROUPID], source.[UNDERDELIVERYPCT], source.[UNITID], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[ALLOCATEMARKUP] = source.[ALLOCATEMARKUP], target.[ENDDISC] = source.[ENDDISC], target.[INTERCOMPANYBLOCKED] = source.[INTERCOMPANYBLOCKED], target.[ITEMID] = source.[ITEMID], target.[LINEDISC] = source.[LINEDISC], target.[MARKUP] = source.[MARKUP], target.[MARKUPGROUPID] = source.[MARKUPGROUPID], target.[MAXIMUMRETAILPRICE_IN] = source.[MAXIMUMRETAILPRICE_IN], target.[MODULETYPE] = source.[MODULETYPE], target.[MULTILINEDISC] = source.[MULTILINEDISC], target.[OVERDELIVERYPCT] = source.[OVERDELIVERYPCT], target.[PRICE] = source.[PRICE], target.[PRICEDATE] = source.[PRICEDATE], target.[PRICEQTY] = source.[PRICEQTY], target.[PRICEUNIT] = source.[PRICEUNIT], target.[RECID] = source.[RECID], target.[SUPPITEMGROUPID] = source.[SUPPITEMGROUPID], target.[TAXITEMGROUPID] = source.[TAXITEMGROUPID], target.[UNDERDELIVERYPCT] = source.[UNDERDELIVERYPCT], target.[UNITID] = source.[UNITID], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- InventItemSalesSetup
PRINT 'Upserting into [ax].INVENTITEMSALESSETUP ..'
MERGE [ax].INVENTITEMSALESSETUP AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(InventDimId)[1]', 'NVARCHAR(20)'), '') AS [INVENTDIMID],
ISNULL(T.c.value('(InventDimIdDefault)[1]', 'NVARCHAR(20)'), '') AS [INVENTDIMIDDEFAULT],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
CASE T.c.value('(MandatoryInventLocation)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [MANDATORYINVENTLOCATION],
CASE T.c.value('(MandatoryInventSite)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [MANDATORYINVENTSITE],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventItemSalesSetup') AS T(c)
) AS source ([INVENTDIMID], [INVENTDIMIDDEFAULT], [ITEMID], [MANDATORYINVENTLOCATION], [MANDATORYINVENTSITE], [RECID], [DATAAREAID])
ON (target.[ITEMID] = source.[ITEMID] AND target.[INVENTDIMID] = source.[INVENTDIMID] AND target.[DATAAREAID] = source.[DATAAREAID])
WHEN NOT MATCHED THEN
INSERT ([INVENTDIMID], [INVENTDIMIDDEFAULT], [ITEMID], [MANDATORYINVENTLOCATION], [MANDATORYINVENTSITE], [RECID], [DATAAREAID])
VALUES (source.[INVENTDIMID], source.[INVENTDIMIDDEFAULT], source.[ITEMID], source.[MANDATORYINVENTLOCATION], source.[MANDATORYINVENTSITE], source.[RECID], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[INVENTDIMID] = source.[INVENTDIMID], target.[INVENTDIMIDDEFAULT] = source.[INVENTDIMIDDEFAULT], target.[ITEMID] = source.[ITEMID], target.[MANDATORYINVENTLOCATION] = source.[MANDATORYINVENTLOCATION], target.[MANDATORYINVENTSITE] = source.[MANDATORYINVENTSITE], target.[RECID] = source.[RECID], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResTrackingDimensionGroupItem
PRINT 'Upserting into [ax].ECORESTRACKINGDIMENSIONGROUPITEM ..'
MERGE [ax].ECORESTRACKINGDIMENSIONGROUPITEM AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(ItemDataAreaId)[1]', 'NVARCHAR(4)'), '') AS [ITEMDATAAREAID],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(TrackingDimensionGroup)[1]', 'BIGINT'), '0') AS [TRACKINGDIMENSIONGROUP]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResTrackingDimensionGroupItem') AS T(c)
) AS source ([ITEMDATAAREAID], [ITEMID], [RECID], [TRACKINGDIMENSIONGROUP])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([ITEMDATAAREAID], [ITEMID], [RECID], [TRACKINGDIMENSIONGROUP])
VALUES (source.[ITEMDATAAREAID], source.[ITEMID], source.[RECID], source.[TRACKINGDIMENSIONGROUP])
WHEN MATCHED THEN
UPDATE SET target.[ITEMDATAAREAID] = source.[ITEMDATAAREAID], target.[ITEMID] = source.[ITEMID], target.[RECID] = source.[RECID], target.[TRACKINGDIMENSIONGROUP] = source.[TRACKINGDIMENSIONGROUP];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- InventItemGroupItem
PRINT 'Upserting into [ax].INVENTITEMGROUPITEM ..'
MERGE [ax].INVENTITEMGROUPITEM AS target
USING (
SELECT DISTINCT
ISNULL(T.c.value('(ItemDataAreaId)[1]', 'NVARCHAR(4)'), '') AS [ITEMDATAAREAID],
ISNULL(T.c.value('(ItemGroupDataAreaId)[1]', 'NVARCHAR(4)'), '') AS [ITEMGROUPDATAAREAID],
ISNULL(T.c.value('(ItemGroupId)[1]', 'NVARCHAR(10)'), '') AS [ITEMGROUPID],
ISNULL(T.c.value('(ItemId)[1]', 'NVARCHAR(20)'), '') AS [ITEMID],
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/InventItemGroupItem') AS T(c)
) AS source ([ITEMDATAAREAID], [ITEMGROUPDATAAREAID], [ITEMGROUPID], [ITEMID], [RECID])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([ITEMDATAAREAID], [ITEMGROUPDATAAREAID], [ITEMGROUPID], [ITEMID], [RECID])
VALUES (source.[ITEMDATAAREAID], source.[ITEMGROUPDATAAREAID], source.[ITEMGROUPID], source.[ITEMID], source.[RECID])
WHEN MATCHED THEN
UPDATE SET target.[ITEMDATAAREAID] = source.[ITEMDATAAREAID], target.[ITEMGROUPDATAAREAID] = source.[ITEMGROUPDATAAREAID], target.[ITEMGROUPID] = source.[ITEMGROUPID], target.[ITEMID] = source.[ITEMID], target.[RECID] = source.[RECID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailInventAvailability
PRINT 'Upserting into [ax].RETAILINVENTAVAILABILITY ..'
MERGE [ax].RETAILINVENTAVAILABILITY AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(AvailPhysical)[1]', 'NUMERIC(32, 16)'), '0') AS [AVAILPHYSICAL],
ISNULL(T.c.value('(InventDimRecId)[1]', 'BIGINT'), '0') AS [INVENTDIMRECID],
ISNULL(T.c.value('(ItemRecId)[1]', 'BIGINT'), '0') AS [ITEMRECID],
ISNULL(T.c.value('(LastInventTrans)[1]', 'BIGINT'), '0') AS [LASTINVENTTRANS]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/RetailInventAvailability') AS T(c)
) AS source ([RECID], [AVAILPHYSICAL], [INVENTDIMRECID], [ITEMRECID], [LASTINVENTTRANS])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [AVAILPHYSICAL], [INVENTDIMRECID], [ITEMRECID], [LASTINVENTTRANS])
VALUES (source.[RECID], source.[AVAILPHYSICAL], source.[INVENTDIMRECID], source.[ITEMRECID], source.[LASTINVENTTRANS])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[AVAILPHYSICAL] = source.[AVAILPHYSICAL], target.[INVENTDIMRECID] = source.[INVENTDIMRECID], target.[ITEMRECID] = source.[ITEMRECID], target.[LASTINVENTTRANS] = source.[LASTINVENTTRANS];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductMasterColor
PRINT 'Upserting into [ax].ECORESPRODUCTMASTERCOLOR ..'
MERGE [ax].ECORESPRODUCTMASTERCOLOR AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Color)[1]', 'BIGINT'), '0') AS [COLOR],
ISNULL(T.c.value('(ColorProductMaster)[1]', 'BIGINT'), '0') AS [COLORPRODUCTMASTER]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterColor') AS T(c)
) AS source ([RECID], [COLOR], [COLORPRODUCTMASTER])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [COLOR], [COLORPRODUCTMASTER])
VALUES (source.[RECID], source.[COLOR], source.[COLORPRODUCTMASTER])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[COLOR] = source.[COLOR], target.[COLORPRODUCTMASTER] = source.[COLORPRODUCTMASTER];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductMasterDimensionValue
PRINT 'Upserting into [ax].ECORESPRODUCTMASTERDIMENSIONVALUE ..'
MERGE [ax].ECORESPRODUCTMASTERDIMENSIONVALUE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RetailDisplayOrder)[1]', 'NUMERIC(32, 16)'), '0') AS [RETAILDISPLAYORDER],
ISNULL(T.c.value('(RetailWeight)[1]', 'INT'), '0') AS [RETAILWEIGHT],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [INSTANCERELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterColor/EcoResProductMasterDimensionValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RetailDisplayOrder)[1]', 'NUMERIC(32, 16)'), '0') AS [RETAILDISPLAYORDER],
ISNULL(T.c.value('(RetailWeight)[1]', 'INT'), '0') AS [RETAILWEIGHT],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [INSTANCERELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterConfiguration/EcoResProductMasterDimensionValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RetailDisplayOrder)[1]', 'NUMERIC(32, 16)'), '0') AS [RETAILDISPLAYORDER],
ISNULL(T.c.value('(RetailWeight)[1]', 'INT'), '0') AS [RETAILWEIGHT],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [INSTANCERELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterSize/EcoResProductMasterDimensionValue') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(RetailDisplayOrder)[1]', 'NUMERIC(32, 16)'), '0') AS [RETAILDISPLAYORDER],
ISNULL(T.c.value('(RetailWeight)[1]', 'INT'), '0') AS [RETAILWEIGHT],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [RELATIONTYPE],
ISNULL(T.c.value('(RelationType)[1]', 'BIGINT'), 0) AS [INSTANCERELATIONTYPE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterStyle/EcoResProductMasterDimensionValue') AS T(c)
) AS source ([RECID], [RETAILDISPLAYORDER], [RETAILWEIGHT], [RELATIONTYPE], [INSTANCERELATIONTYPE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [RETAILDISPLAYORDER], [RETAILWEIGHT], [RELATIONTYPE], [INSTANCERELATIONTYPE])
VALUES (source.[RECID], source.[RETAILDISPLAYORDER], source.[RETAILWEIGHT], source.[RELATIONTYPE], source.[INSTANCERELATIONTYPE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[RETAILDISPLAYORDER] = source.[RETAILDISPLAYORDER], target.[RETAILWEIGHT] = source.[RETAILWEIGHT], target.[RELATIONTYPE] = source.[RELATIONTYPE], target.[INSTANCERELATIONTYPE] = source.[INSTANCERELATIONTYPE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductMasterDimValueTranslation
PRINT 'Upserting into [ax].ECORESPRODUCTMASTERDIMVALUETRANSLATION ..'
MERGE [ax].ECORESPRODUCTMASTERDIMVALUETRANSLATION AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Description)[1]', 'NVARCHAR(1000)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(60)'), '') AS [NAME],
T.c.value('(../RecId)[1]', 'BIGINT') AS [PRODUCTMASTERDIMENSIONVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterColor/EcoResProductMasterDimensionValue/EcoResProductMasterDimValueTranslation') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Description)[1]', 'NVARCHAR(1000)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(60)'), '') AS [NAME],
T.c.value('(../RecId)[1]', 'BIGINT') AS [PRODUCTMASTERDIMENSIONVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterConfiguration/EcoResProductMasterDimensionValue/EcoResProductMasterDimValueTranslation') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Description)[1]', 'NVARCHAR(1000)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(60)'), '') AS [NAME],
T.c.value('(../RecId)[1]', 'BIGINT') AS [PRODUCTMASTERDIMENSIONVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterSize/EcoResProductMasterDimensionValue/EcoResProductMasterDimValueTranslation') AS T(c)
UNION
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Description)[1]', 'NVARCHAR(1000)'), '') AS [DESCRIPTION],
ISNULL(T.c.value('(LanguageId)[1]', 'NVARCHAR(7)'), '') AS [LANGUAGEID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(60)'), '') AS [NAME],
T.c.value('(../RecId)[1]', 'BIGINT') AS [PRODUCTMASTERDIMENSIONVALUE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterStyle/EcoResProductMasterDimensionValue/EcoResProductMasterDimValueTranslation') AS T(c)
) AS source ([RECID], [DESCRIPTION], [LANGUAGEID], [NAME], [PRODUCTMASTERDIMENSIONVALUE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [DESCRIPTION], [LANGUAGEID], [NAME], [PRODUCTMASTERDIMENSIONVALUE])
VALUES (source.[RECID], source.[DESCRIPTION], source.[LANGUAGEID], source.[NAME], source.[PRODUCTMASTERDIMENSIONVALUE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[DESCRIPTION] = source.[DESCRIPTION], target.[LANGUAGEID] = source.[LANGUAGEID], target.[NAME] = source.[NAME], target.[PRODUCTMASTERDIMENSIONVALUE] = source.[PRODUCTMASTERDIMENSIONVALUE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResColor
PRINT 'Upserting into [ax].ECORESCOLOR ..'
MERGE [ax].ECORESCOLOR AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(10)'), '') AS [NAME]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterColor/EcoResColor') AS T(c)
) AS source ([RECID], [NAME])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [NAME])
VALUES (source.[RECID], source.[NAME])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[NAME] = source.[NAME];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductMasterConfiguration
PRINT 'Upserting into [ax].ECORESPRODUCTMASTERCONFIGURATION ..'
MERGE [ax].ECORESPRODUCTMASTERCONFIGURATION AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(ConfigProductMaster)[1]', 'BIGINT'), '0') AS [CONFIGPRODUCTMASTER],
ISNULL(T.c.value('(Configuration)[1]', 'BIGINT'), '0') AS [CONFIGURATION]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterConfiguration') AS T(c)
) AS source ([RECID], [CONFIGPRODUCTMASTER], [CONFIGURATION])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [CONFIGPRODUCTMASTER], [CONFIGURATION])
VALUES (source.[RECID], source.[CONFIGPRODUCTMASTER], source.[CONFIGURATION])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[CONFIGPRODUCTMASTER] = source.[CONFIGPRODUCTMASTER], target.[CONFIGURATION] = source.[CONFIGURATION];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResConfiguration
PRINT 'Upserting into [ax].ECORESCONFIGURATION ..'
MERGE [ax].ECORESCONFIGURATION AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(10)'), '') AS [NAME]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterConfiguration/EcoResConfiguration') AS T(c)
) AS source ([RECID], [NAME])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [NAME])
VALUES (source.[RECID], source.[NAME])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[NAME] = source.[NAME];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductMasterSize
PRINT 'Upserting into [ax].ECORESPRODUCTMASTERSIZE ..'
MERGE [ax].ECORESPRODUCTMASTERSIZE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Size)[1]', 'BIGINT'), '0') AS [SIZE],
ISNULL(T.c.value('(SizeProductMaster)[1]', 'BIGINT'), '0') AS [SIZEPRODUCTMASTER]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterSize') AS T(c)
) AS source ([RECID], [SIZE], [SIZEPRODUCTMASTER])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [SIZE], [SIZEPRODUCTMASTER])
VALUES (source.[RECID], source.[SIZE], source.[SIZEPRODUCTMASTER])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[SIZE] = source.[SIZE], target.[SIZEPRODUCTMASTER] = source.[SIZEPRODUCTMASTER];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResSize
PRINT 'Upserting into [ax].ECORESSIZE ..'
MERGE [ax].ECORESSIZE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(10)'), '') AS [NAME]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterSize/EcoResSize') AS T(c)
) AS source ([RECID], [NAME])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [NAME])
VALUES (source.[RECID], source.[NAME])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[NAME] = source.[NAME];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResProductMasterStyle
PRINT 'Upserting into [ax].ECORESPRODUCTMASTERSTYLE ..'
MERGE [ax].ECORESPRODUCTMASTERSTYLE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Style)[1]', 'BIGINT'), '0') AS [STYLE],
ISNULL(T.c.value('(StyleProductMaster)[1]', 'BIGINT'), '0') AS [STYLEPRODUCTMASTER]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterStyle') AS T(c)
) AS source ([RECID], [STYLE], [STYLEPRODUCTMASTER])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [STYLE], [STYLEPRODUCTMASTER])
VALUES (source.[RECID], source.[STYLE], source.[STYLEPRODUCTMASTER])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[STYLE] = source.[STYLE], target.[STYLEPRODUCTMASTER] = source.[STYLEPRODUCTMASTER];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EcoResStyle
PRINT 'Upserting into [ax].ECORESSTYLE ..'
MERGE [ax].ECORESSTYLE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Name)[1]', 'NVARCHAR(10)'), '') AS [NAME]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/EcoResProductMasterStyle/EcoResStyle') AS T(c)
) AS source ([RECID], [NAME])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [NAME])
VALUES (source.[RECID], source.[NAME])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[NAME] = source.[NAME];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailKit
PRINT 'Upserting into [ax].RETAILKIT ..'
MERGE [ax].RETAILKIT AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
CASE T.c.value('(DisassemblyAtRegisterAllowed)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [DISASSEMBLYATREGISTERALLOWED],
CASE T.c.value('(DiscontinueKit)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [DISCONTINUEKIT],
ISNULL(T.c.value('(ProductMaster)[1]', 'BIGINT'), '0') AS [PRODUCTMASTER],
CASE T.c.value('(Status)[1]', 'NVARCHAR(4000)')
WHEN 'Draft' THEN 0
WHEN 'Approved' THEN 1
ELSE 0
END AS [STATUS]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/RetailKit') AS T(c)
) AS source ([RECID], [DISASSEMBLYATREGISTERALLOWED], [DISCONTINUEKIT], [PRODUCTMASTER], [STATUS])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [DISASSEMBLYATREGISTERALLOWED], [DISCONTINUEKIT], [PRODUCTMASTER], [STATUS])
VALUES (source.[RECID], source.[DISASSEMBLYATREGISTERALLOWED], source.[DISCONTINUEKIT], source.[PRODUCTMASTER], source.[STATUS])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[DISASSEMBLYATREGISTERALLOWED] = source.[DISASSEMBLYATREGISTERALLOWED], target.[DISCONTINUEKIT] = source.[DISCONTINUEKIT], target.[PRODUCTMASTER] = source.[PRODUCTMASTER], target.[STATUS] = source.[STATUS];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailKitComponent
PRINT 'Upserting into [ax].RETAILKITCOMPONENT ..'
MERGE [ax].RETAILKITCOMPONENT AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(Component)[1]', 'BIGINT'), '0') AS [COMPONENT],
CASE T.c.value('(DoNotShowAtRegister)[1]', 'NVARCHAR(4000)')
WHEN 'No' THEN 0
WHEN 'Yes' THEN 1
ELSE 0
END AS [DONOTSHOWATREGISTER],
ISNULL(T.c.value('(Kit)[1]', 'BIGINT'), '0') AS [KIT],
ISNULL(T.c.value('(Quantity)[1]', 'NUMERIC(32, 16)'), '0') AS [QUANTITY],
ISNULL(T.c.value('(UnitOfMeasure)[1]', 'BIGINT'), '0') AS [UNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/RetailKit/RetailKitComponent') AS T(c)
) AS source ([RECID], [COMPONENT], [DONOTSHOWATREGISTER], [KIT], [QUANTITY], [UNITOFMEASURE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [COMPONENT], [DONOTSHOWATREGISTER], [KIT], [QUANTITY], [UNITOFMEASURE])
VALUES (source.[RECID], source.[COMPONENT], source.[DONOTSHOWATREGISTER], source.[KIT], source.[QUANTITY], source.[UNITOFMEASURE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[COMPONENT] = source.[COMPONENT], target.[DONOTSHOWATREGISTER] = source.[DONOTSHOWATREGISTER], target.[KIT] = source.[KIT], target.[QUANTITY] = source.[QUANTITY], target.[UNITOFMEASURE] = source.[UNITOFMEASURE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailKitComponentSubstitute
PRINT 'Upserting into [ax].RETAILKITCOMPONENTSUBSTITUTE ..'
MERGE [ax].RETAILKITCOMPONENTSUBSTITUTE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(KitComponent)[1]', 'BIGINT'), '0') AS [KITCOMPONENT],
ISNULL(T.c.value('(Quantity)[1]', 'NUMERIC(32, 16)'), '0') AS [QUANTITY],
ISNULL(T.c.value('(SubstituteProduct)[1]', 'BIGINT'), '0') AS [SUBSTITUTEPRODUCT],
ISNULL(T.c.value('(UnitOfMeasure)[1]', 'BIGINT'), '0') AS [UNITOFMEASURE]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/RetailKit/RetailKitComponent/RetailKitComponentSubstitute') AS T(c)
) AS source ([RECID], [KITCOMPONENT], [QUANTITY], [SUBSTITUTEPRODUCT], [UNITOFMEASURE])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [KITCOMPONENT], [QUANTITY], [SUBSTITUTEPRODUCT], [UNITOFMEASURE])
VALUES (source.[RECID], source.[KITCOMPONENT], source.[QUANTITY], source.[SUBSTITUTEPRODUCT], source.[UNITOFMEASURE])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[KITCOMPONENT] = source.[KITCOMPONENT], target.[QUANTITY] = source.[QUANTITY], target.[SUBSTITUTEPRODUCT] = source.[SUBSTITUTEPRODUCT], target.[UNITOFMEASURE] = source.[UNITOFMEASURE];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- RetailKitReleasedSubstituteCharge
PRINT 'Upserting into [ax].RETAILKITRELEASEDSUBSTITUTECHARGE ..'
MERGE [ax].RETAILKITRELEASEDSUBSTITUTECHARGE AS target
USING (
SELECT DISTINCT
T.c.value('(RecId)[1]', 'BIGINT') AS [RECID],
ISNULL(T.c.value('(KitComponentSubstitute)[1]', 'BIGINT'), '0') AS [KITCOMPONENTSUBSTITUTE],
ISNULL(T.c.value('(SubstituteCharge)[1]', 'NUMERIC(32, 16)'), '0') AS [SUBSTITUTECHARGE],
@nvc_DataAreaId AS [DATAAREAID]
FROM @xml_ProductData.nodes('/RetailProductData/InventTable/EcoResProduct/EcoResProductMaster/RetailKit/RetailKitComponent/RetailKitComponentSubstitute/RetailKitReleasedSubstituteCharge') AS T(c)
) AS source ([RECID], [KITCOMPONENTSUBSTITUTE], [SUBSTITUTECHARGE], [DATAAREAID])
ON (target.[RECID] = source.[RECID])
WHEN NOT MATCHED THEN
INSERT ([RECID], [KITCOMPONENTSUBSTITUTE], [SUBSTITUTECHARGE], [DATAAREAID])
VALUES (source.[RECID], source.[KITCOMPONENTSUBSTITUTE], source.[SUBSTITUTECHARGE], source.[DATAAREAID])
WHEN MATCHED THEN
UPDATE SET target.[RECID] = source.[RECID], target.[KITCOMPONENTSUBSTITUTE] = source.[KITCOMPONENTSUBSTITUTE], target.[SUBSTITUTECHARGE] = source.[SUBSTITUTECHARGE], target.[DATAAREAID] = source.[DATAAREAID];

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

    -- Add products to the temporary assortment
    MERGE [crt].TMPASSORTEDPRODUCTS AS target
    USING (
        SELECT
            @bi_ChannelId AS 'CHANNELID',
            T.c.value('(Product)[1]', 'BIGINT') AS 'PRODUCTID',
T.c.value('(ItemId)[1]', 'NVARCHAR(20)') AS 'ITEMID',
            CAST(DATEADD(day, -1, GETUTCDATE()) AS DATE) AS 'VALIDFROM',
            CAST(DATEADD(day, 1, GETUTCDATE()) AS DATE) AS 'VALIDTO'
        FROM @xml_ProductData.nodes('/RetailProductData/InventTable') AS T(c)
    ) AS source ([CHANNELID], [PRODUCTID], [ITEMID], [VALIDFROM], [VALIDTO])
    ON (
        target.[CHANNELID] = source.[CHANNELID] AND
        target.[PRODUCTID] = source.[PRODUCTID] AND
target.[ITEMID] = source.[ITEMID])
    WHEN NOT MATCHED THEN
        INSERT ([CHANNELID], [PRODUCTID], [ITEMID], [VALIDFROM], [VALIDTO])
        VALUES (source.[CHANNELID], source.[PRODUCTID], source.[ITEMID], source.[VALIDFROM], source.[VALIDTO])
    WHEN MATCHED THEN
        UPDATE SET
            target.[VALIDFROM] = source.[VALIDFROM],
            target.[VALIDTO] = source.[VALIDTO];

    SET @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

    PRINT 'Upsert completed successfully.'

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVEPRODUCTDATA]'
GO
-- End creating stored procedure [crt].[SAVEPRODUCTDATA]


GRANT EXECUTE ON [crt].[SAVEPRODUCTDATA] TO [UsersRole];
GO

-- Creating stored procedure [crt].CREATEUPDATECUSTOMERADDRESS
PRINT N'Creating stored procedure [crt].CREATEUPDATECUSTOMERADDRESS';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].CREATEUPDATECUSTOMERADDRESS', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].CREATEUPDATECUSTOMERADDRESS AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].CREATEUPDATECUSTOMERADDRESS.';
END
GO


ALTER PROCEDURE [crt].[CREATEUPDATECUSTOMERADDRESS]
    @nvc_DataAreaId NVARCHAR(10),
    @TVP_CUSTOMERADDRESSTABLETYPE   [crt].CUSTOMERADDRESSTABLETYPE   READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                       INT;
    DECLARE @i_TransactionIsOurs                INT;
    DECLARE @i_Error                            INT;
    DECLARE @i_Rowcount                         INT;
    DECLARE @i_SortOrder                        INT;
    DECLARE @i_AddressCount                     INT;
    DECLARE @dtt_ChangeDate                     DATETIME;
    DECLARE @bi_IdToDelete                      BIGINT;
    DECLARE @i_DeactivateFlag                   INT;
    DECLARE @bi_logisticsPostalAddressRecId     BIGINT;
    DECLARE @bi_dirPartyLocationRecId           BIGINT;
    DECLARE @nvc_TaxGroup                       NVARCHAR(10);
    DECLARE @tvp_CustomerAddressCursor           [crt].CUSTOMERADDRESSTABLETYPE;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SET @i_TransactionIsOurs = 1;

    END

    SET @dtt_ChangeDate = GETUTCDATE();

    SELECT @i_SortOrder = 0;
    SELECT @i_AddressCount = (SELECT COUNT(ADDRESSTYPE) FROM @TVP_CUSTOMERADDRESSTABLETYPE)

    WHILE @i_SortOrder < @i_AddressCount
    BEGIN
        SELECT @i_SortOrder = @i_SortOrder + 1;

        DELETE FROM @tvp_CustomerAddressCursor;
        INSERT @tvp_CustomerAddressCursor 
SELECT
 RECORDID                           
,ADDRESSTYPE                         
,NAME                               
,FULLADDRESS                        
,STREETNUMBER                       
,STREET                             
,POSTBOX                            
,BUILDINGCOMPLIMENT                 
,CITY                               
,COUNTY                             
,DISTRICTNAME                       
,[STATE]                            
,ZIPCODE                            
,THREELETTERISOREGIONNAME           
,ISPRIMARY                          
,ISPRIVATE                          
,DIRPARTYRECORDID                   
,DIRPARTYLOCATIONRECORDID           
,DIRPARTYLOCATIONROLERECORDID       
,LOCATIONDESCRIPTION                
,LOCATOR                            
,LOGISTICSLOCATIONID                
,LOGISTICSLOCATIONRECORDID          
,TAXGROUP                           
,DEACTIVATE                         
,SORTORDER
,EXPIRERECORDID                          
,LOGISTICSLOCATIONROLERECORDID      
,LOGISTICSLOCATIONEXTRECORDID       
FROM @TVP_CUSTOMERADDRESSTABLETYPE WHERE SORTORDER = @i_SortOrder;

        SELECT @i_DeactivateFlag = SOURCE.DEACTIVATE FROM @tvp_CustomerAddressCursor AS SOURCE

        -- WE ARE NOT DEACTIVATING THIS ADDRESS
        IF (@i_DeactivateFlag = 0)
        BEGIN
            -- DELETE THE LOCATIONEXTENSIONS ASSOCIATED WITH THIS LOCATION
            SELECT @bi_IdToDelete = SOURCE.LOGISTICSLOCATIONRECORDID FROM @tvp_CustomerAddressCursor SOURCE;
            DELETE FROM [ax].LOGISTICSLOCATIONEXT WHERE LOCATION = @bi_IdToDelete;

            -- UPSERT INTO LOGISTICSLOCATIONEXT
            SELECT @nvc_TaxGroup = COALESCE(TAXGROUP,'') FROM @tvp_CustomerAddressCursor;

            IF (@nvc_TaxGroup <> '')
            BEGIN
                IF (EXISTS (SELECT RECORDID FROM @tvp_CustomerAddressCursor WHERE LOGISTICSLOCATIONEXTRECORDID > 0))
                BEGIN
                    MERGE INTO [ax].LOGISTICSLOCATIONEXT
                    USING @tvp_CustomerAddressCursor AS SOURCE
                    ON
                        [ax].LOGISTICSLOCATIONEXT.RECID = SOURCE.LOGISTICSLOCATIONEXTRECORDID
                    WHEN MATCHED THEN
                        UPDATE
                        SET
                             LOCATION               = SOURCE.LOGISTICSLOCATIONRECORDID
                            ,TAXGROUP               = SOURCE.TAXGROUP

                    WHEN NOT MATCHED THEN
                        INSERT
                        (
                            RECID
                            ,LOCATION
                            ,TAXGROUP
,DATAAREAID
                        )
                        VALUES
                        (
                            SOURCE.LOGISTICSLOCATIONEXTRECORDID
                            ,SOURCE.LOGISTICSLOCATIONRECORDID
                            ,SOURCE.TAXGROUP
,@nvc_DataAreaId
                        );

                    SELECT @i_Error = @@ERROR;
                    IF @i_Error <> 0
                    BEGIN
                        SET @i_ReturnCode = @i_Error;
                        GOTO exit_label;
                    END;
                END;
            END;

            IF (EXISTS (SELECT RECORDID FROM @tvp_CustomerAddressCursor WHERE LOGISTICSLOCATIONRECORDID > 0))
            BEGIN
                -- UPSERT INTO LOGISTICSLOCATION
                MERGE INTO [ax].LOGISTICSLOCATION
                USING (SELECT DISTINCT LOGISTICSLOCATIONRECORDID, LOGISTICSLOCATIONID, NAME 
FROM @tvp_CustomerAddressCursor
WHERE LOGISTICSLOCATIONRECORDID > 0) AS SOURCE
                ON
                    [ax].LOGISTICSLOCATION.RECID = SOURCE.LOGISTICSLOCATIONRECORDID

                WHEN MATCHED THEN
                    UPDATE
                    SET
                         ISPOSTALADDRESS            = 1
                        ,DESCRIPTION                = SOURCE.NAME
                        ,MODIFIEDDATETIME            = @dtt_ChangeDate

                WHEN NOT MATCHED THEN
                    INSERT
                    (
                        RECID
                        ,LOCATIONID
                        ,DESCRIPTION
                        ,ISPOSTALADDRESS
                        ,MODIFIEDDATETIME
                        ,CREATEDDATETIME
                    )
                    VALUES
                    (
                        SOURCE.LOGISTICSLOCATIONRECORDID
                        ,SOURCE.LOGISTICSLOCATIONID
                        ,SOURCE.NAME
                        ,1
                        ,@dtt_ChangeDate
                        ,@dtt_ChangeDate
                    );

                SELECT @i_Error = @@ERROR;
                IF @i_Error <> 0
                BEGIN
                    SET @i_ReturnCode = @i_Error;
                    GOTO exit_label;
                END;
            END;

            IF (EXISTS (SELECT SOURCE.RECORDID FROM @tvp_CustomerAddressCursor AS SOURCE WHERE SOURCE.RECORDID>0 AND SOURCE.LOGISTICSLOCATIONRECORDID>0))
            BEGIN

                --EXPIRE ANY ADDRESSES THAT GOT UPDATED

                MERGE INTO [ax].LOGISTICSPOSTALADDRESS
                USING @tvp_CustomerAddressCursor AS SOURCE
                ON
                    [ax].LOGISTICSPOSTALADDRESS.RECID = SOURCE.EXPIRERECORDID
                    AND [ax].LOGISTICSPOSTALADDRESS.RECID != SOURCE.RECORDID
                WHEN MATCHED THEN
                UPDATE
                SET
                    MODIFIEDDATETIME    = @dtt_ChangeDate
                    ,VALIDTO            = DATEADD(S, -1, @dtt_ChangeDate);

                --INSERT INTO LOGISTICSPOSTALADDRESS
                MERGE INTO [ax].LOGISTICSPOSTALADDRESS
                USING @tvp_CustomerAddressCursor AS SOURCE
                ON
                    [ax].LOGISTICSPOSTALADDRESS.RECID = SOURCE.RECORDID
                WHEN MATCHED THEN
                UPDATE
                SET
                         ADDRESS = SOURCE.FULLADDRESS
                        ,STREET = SOURCE.STREET
                        ,CITY = SOURCE.CITY
                        ,COUNTY = SOURCE.COUNTY
                        ,[STATE] = SOURCE.[STATE]
                        ,COUNTRYREGIONID = SOURCE.THREELETTERISOREGIONNAME
                        ,ZIPCODE = SOURCE.ZIPCODE
                        ,BUILDINGCOMPLIMENT = SOURCE.BUILDINGCOMPLIMENT
                        ,STREETNUMBER = SOURCE.STREETNUMBER
                        ,DISTRICTNAME = SOURCE.DISTRICTNAME
                        ,POSTBOX = SOURCE.POSTBOX
                        ,ISPRIVATE = SOURCE.ISPRIVATE
                        ,MODIFIEDDATETIME    = @dtt_ChangeDate

                WHEN NOT MATCHED THEN
                    INSERT
                    (
                        RECID
                        ,LOCATION
                        ,ADDRESS
                        ,STREET
                        ,CITY
                        ,COUNTY
                        ,[STATE]
                        ,COUNTRYREGIONID
                        ,ZIPCODE
                        ,BUILDINGCOMPLIMENT
                        ,STREETNUMBER
                        ,DISTRICTNAME
                        ,POSTBOX
                        ,ISPRIVATE
                        ,MODIFIEDDATETIME
                        ,VALIDFROM
                        ,VALIDTO
                    )
                  VALUES
                    (
                        SOURCE.RECORDID
                        ,SOURCE.LOGISTICSLOCATIONRECORDID
                        ,SOURCE.FULLADDRESS
                        ,SOURCE.STREET
                        ,SOURCE.CITY
                        ,SOURCE.COUNTY
                        ,SOURCE.[STATE]
                        ,SOURCE.THREELETTERISOREGIONNAME
                        ,SOURCE.ZIPCODE
                        ,SOURCE.BUILDINGCOMPLIMENT
                        ,SOURCE.STREETNUMBER
                        ,SOURCE.DISTRICTNAME
                        ,SOURCE.POSTBOX
                        ,0
                        ,@dtt_ChangeDate
                        ,@dtt_ChangeDate
                        ,'2154-12-31 23:59:59.000' -- Never expires
                    );

                SELECT @i_Error = @@ERROR;
                IF @i_Error <> 0
                BEGIN
                    SET @i_ReturnCode = @i_Error;
                    GOTO exit_label;
                END;
            END;

            IF (EXISTS (SELECT RECORDID FROM @tvp_CustomerAddressCursor WHERE DIRPARTYLOCATIONRECORDID > 0))
            BEGIN
                -- UPSERT INTO THE DIRPARTYLOCATION
                MERGE INTO [ax].DIRPARTYLOCATION
                USING (SELECT DISTINCT DIRPARTYLOCATIONRECORDID, DIRPARTYRECORDID, LOGISTICSLOCATIONRECORDID, ISPRIMARY 
FROM @tvp_CustomerAddressCursor
WHERE DIRPARTYLOCATIONRECORDID != 0) AS SOURCE
                ON
                    [ax].DIRPARTYLOCATION.RECID = SOURCE.DIRPARTYLOCATIONRECORDID
                WHEN MATCHED THEN
                    UPDATE
                    SET
                         PARTY              = SOURCE.DIRPARTYRECORDID
                        ,LOCATION           = SOURCE.LOGISTICSLOCATIONRECORDID
                        ,ISPOSTALADDRESS    = 1 -- ALWAYS TRUE
                        ,ISPRIMARY          = SOURCE.ISPRIMARY
                WHEN NOT MATCHED THEN
                    INSERT
                    (
                        RECID
                        ,PARTY
                        ,LOCATION
                        ,ISPOSTALADDRESS
                        ,ISPRIMARY
                    )
                    VALUES
                    (
                        SOURCE.DIRPARTYLOCATIONRECORDID
                        ,SOURCE.DIRPARTYRECORDID
                        ,SOURCE.LOGISTICSLOCATIONRECORDID
                        ,1
                        ,SOURCE.ISPRIMARY
                    );

                SELECT @i_Error = @@ERROR;
                IF @i_Error <> 0
                BEGIN
                    SET @i_ReturnCode = @i_Error;
                    GOTO exit_label;
                END;
            END;

            IF (EXISTS (SELECT SOURCE.RECORDID FROM @tvp_CustomerAddressCursor AS SOURCE WHERE SOURCE.DIRPARTYLOCATIONROLERECORDID>0))
            BEGIN
                -- UPSERT INTO THE DIR PARTY LOCATION ROLE
                MERGE INTO [ax].DIRPARTYLOCATIONROLE
                USING @tvp_CustomerAddressCursor AS SOURCE
                ON
                    [ax].DIRPARTYLOCATIONROLE.RECID = SOURCE.DIRPARTYLOCATIONROLERECORDID
                WHEN MATCHED THEN
                    UPDATE
                    SET
                         PARTYLOCATION      = SOURCE.DIRPARTYLOCATIONRECORDID
                        ,LOCATIONROLE       = SOURCE.LOGISTICSLOCATIONROLERECORDID

                WHEN NOT MATCHED THEN
                    INSERT
                    (
                        RECID
                        ,PARTYLOCATION
                        ,LOCATIONROLE
                    )
                    VALUES
                    (
                        SOURCE.DIRPARTYLOCATIONROLERECORDID
                        ,SOURCE.DIRPARTYLOCATIONRECORDID
                        ,SOURCE.LOGISTICSLOCATIONROLERECORDID
                    );

                SELECT @i_Error = @@ERROR;
                IF @i_Error <> 0
                BEGIN
                    SET @i_ReturnCode = @i_Error;
                    GOTO exit_label;
                END;
            END;

        END
        ELSE
        BEGIN
            -- DEACTIVATE THIS ADDRESS IF DEACTIVATE == 1
            SELECT
                @bi_logisticsPostalAddressRecId = SOURCE.RECORDID
                --@bi_dirPartyLocationRecId = SOURCE.DIRPARTYLOCATIONRECORDID
            FROM @tvp_CustomerAddressCursor AS SOURCE

            UPDATE [ax].LOGISTICSPOSTALADDRESS SET VALIDTO=@dtt_ChangeDate WHERE RECID=@bi_logisticsPostalAddressRecId;

            SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;
            IF @i_Error <> 0
            BEGIN
                SET @i_ReturnCode = @i_Error;
                GOTO exit_label;
            END;
            IF @i_Rowcount = 0
            BEGIN
                SET @i_ReturnCode = -1;
                GOTO exit_label;
            END;
        END;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].CREATEUPDATECUSTOMERADDRESS'
GO
-- End creating stored procedure [crt].CREATEUPDATECUSTOMERADDRESS


GRANT EXECUTE ON [crt].[CREATEUPDATECUSTOMERADDRESS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[CREATEUPDATEELECTRONICADDRESS]
PRINT N'Creating stored procedure [crt].[CREATEUPDATEELECTRONICADDRESS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[CREATEUPDATEELECTRONICADDRESS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[CREATEUPDATEELECTRONICADDRESS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[CREATEUPDATEELECTRONICADDRESS].';
END
GO


ALTER PROCEDURE [crt].[CREATEUPDATEELECTRONICADDRESS]
    @TVP_CUSTOMERELECTRONICADDRESSTABLETYPE   [crt].CUSTOMERELECTRONICADDRESSTABLETYPE   READONLY
AS
BEGIN
    --METHODTYPE =
        --None = 0,
        --Phone = 1,
        --Email = 2,
        --URL = 3,
        --Telex = 4,
        --Fax = 5

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                       INT;
    DECLARE @i_TransactionIsOurs                INT;
    DECLARE @i_Error                            INT;
    DECLARE @i_Rowcount                         INT;
    DECLARE @dtt_ChangeDate                     DATETIME;
    DECLARE @tvp_CustomerElectronicAddressCusor [crt].CUSTOMERELECTRONICADDRESSTABLETYPE;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;
        SET @i_TransactionIsOurs = 1;
    END

    SET @dtt_ChangeDate = GETUTCDATE();

    -- UPSERT INTO LOGISTICSLOCATION
    MERGE INTO [ax].LOGISTICSLOCATION
    USING (SELECT DISTINCT LOGISTICSLOCATIONRECORDID, LOGISTICSLOCATIONID, PARENTLOCATION
FROM @TVP_CUSTOMERELECTRONICADDRESSTABLETYPE
WHERE LOGISTICSLOCATIONRECORDID != 0) AS SOURCE
    ON [ax].LOGISTICSLOCATION.RECID = SOURCE.LOGISTICSLOCATIONRECORDID
        AND [ax].LOGISTICSLOCATION.LOCATIONID = SOURCE.LOGISTICSLOCATIONID
    WHEN NOT MATCHED THEN
        INSERT
        (
             RECID
            ,LOCATIONID
,PARENTLOCATION
            ,ISPOSTALADDRESS
            ,MODIFIEDDATETIME
            ,CREATEDDATETIME
        )
        VALUES
        (
             SOURCE.LOGISTICSLOCATIONRECORDID
            ,SOURCE.LOGISTICSLOCATIONID
,SOURCE.PARENTLOCATION
            ,0
            ,@dtt_ChangeDate
            ,@dtt_ChangeDate
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- UPSERT INTO DIRPARTYLOCATION
    MERGE INTO [ax].DIRPARTYLOCATION
    USING (select distinct DIRPARTYLOCATIONRECORDID, DIRPARTYRECORDID, LOGISTICSLOCATIONRECORDID 
from @TVP_CUSTOMERELECTRONICADDRESSTABLETYPE 
where DIRPARTYLOCATIONRECORDID != 0 and PARENTLOCATION = 0) AS SOURCE
    ON [ax].DIRPARTYLOCATION.RECID = SOURCE.DIRPARTYLOCATIONRECORDID
    WHEN NOT MATCHED THEN
        INSERT
        (
             RECID
            ,PARTY
,LOCATION
            ,ISPOSTALADDRESS
        )
        VALUES
        (
             SOURCE.DIRPARTYLOCATIONRECORDID
,SOURCE.DIRPARTYRECORDID
            ,SOURCE.LOGISTICSLOCATIONRECORDID
            ,0
        );

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;


    --UPSERT INTO THE LOGISTICSELECTRONICADDRESS
    MERGE INTO [ax].LOGISTICSELECTRONICADDRESS
    USING @TVP_CUSTOMERELECTRONICADDRESSTABLETYPE AS SOURCE
    ON
        [ax].LOGISTICSELECTRONICADDRESS.RECID = SOURCE.RECORDID
    WHEN MATCHED THEN
        UPDATE
        SET
             LOCATION               = SOURCE.LOGISTICSLOCATIONRECORDID
            ,LOCATOR                = SOURCE.LOCATOR
            ,DESCRIPTION            = SOURCE.LOCATIONDESCRIPTION
            ,COUNTRYREGIONCODE      = ''
            ,TYPE                   = SOURCE.METHODYTPE
            ,ISPRIMARY              = SOURCE.ISPRIMARY
            ,ISPRIVATE              = SOURCE.ISPRIVATE
            ,ISMOBILEPHONE          = SOURCE.ISMOBILEPHONE

    WHEN NOT MATCHED THEN
        INSERT
        (
             RECID
            ,LOCATION
            ,LOCATOR
            ,COUNTRYREGIONCODE
            ,TYPE
            ,ISPRIMARY
            ,ISPRIVATE
            ,ISMOBILEPHONE
            ,DESCRIPTION
        )
        VALUES
        (
             SOURCE.RECORDID
            ,SOURCE.LOGISTICSLOCATIONRECORDID
            ,SOURCE.LOCATOR
            ,''
            ,SOURCE.METHODYTPE
            ,SOURCE.ISPRIMARY
            ,SOURCE.ISPRIVATE
            ,SOURCE.ISMOBILEPHONE
            ,SOURCE.LOCATIONDESCRIPTION
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].CREATEUPDATEELECTRONICADDRESS'
GO
-- End creating stored procedure [crt].CREATEUPDATEELECTRONICADDRESS


GRANT EXECUTE ON [crt].[CREATEUPDATEELECTRONICADDRESS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[CREATEUPDATECUSTOMER]
PRINT N'Creating stored procedure [crt].[CREATEUPDATECUSTOMER]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[CREATEUPDATECUSTOMER]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[CREATEUPDATECUSTOMER] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[CREATEUPDATECUSTOMER].';
END
GO


ALTER PROCEDURE [crt].[CREATEUPDATECUSTOMER]
    @TVP_CUSTOMERTABLETYPE                    [crt].CUSTOMERTABLETYPE   READONLY,
    @TVP_CUSTOMERADDRESSTABLETYPE             [crt].CUSTOMERADDRESSTABLETYPE   READONLY,
    @TVP_CUSTOMERELECTRONICADDRESSTABLETYPE   [crt].CUSTOMERELECTRONICADDRESSTABLETYPE   READONLY,
@TVP_EXTENSIONPROPERTIESTABLETYPE        crt.EXTENSIONPROPERTIESTABLETYPE READONLY,
    @TVP_CUSTOMERAFFILIATIONTABLETYPE         [crt].CUSTOMERAFFILIATIONTABLETYPE READONLY,
    @TVP_ADDRESSBOOKPARTYTABLETYPE            [crt].ADDRESSBOOKPARTYTABLETYPE READONLY,
    @UPDATEADDRESSES                BIT    =1,
@UPDATECUSTOMERAFFILIATION     BIT =1
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;
    DECLARE @dtt_ChangeDate                         DATETIME;
    DECLARE @dtt_MaxAxDate                          DATETIME;
    DECLARE @nvc_DataAreaId                         NVARCHAR(10);
    DECLARE @nvc_PrimaryEmail                       NVARCHAR(10);

DECLARE @nvc_CustomerAccountNumber             NVARCHAR(20);

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    SET @dtt_ChangeDate = GETUTCDATE();
SET @dtt_MaxAxDate = crt.GETMAXAXDATE(); -- Never expires

    -- Resolve the DATAAREAID of the Channel
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID
    FROM [crt].STORAGELOOKUPVIEW slv
    INNER JOIN [ax].RETAILPUBRETAILCHANNELTABLE rct ON rct.ORIGINID = slv.CHANNELID

    -- UPSERT INTO THE DIRPARTYTABLE
    MERGE INTO [ax].DIRPARTYTABLE
    USING @TVP_CUSTOMERTABLETYPE AS SOURCE
    ON
        DIRPARTYTABLE.RECID = SOURCE.DIRPARTYRECORDID
    WHEN MATCHED THEN
        UPDATE
        SET
             NAME                   = SOURCE.NAME
            ,LANGUAGEID             = SOURCE.LANGUAGEID
            ,MODIFIEDDATETIME       = @dtt_ChangeDate

    WHEN NOT MATCHED THEN
        INSERT
        (
            RECID
            ,NAME
            ,PARTYNUMBER
            ,LANGUAGEID
            ,MODIFIEDDATETIME
            ,CREATEDDATETIME
            ,INSTANCERELATIONTYPE
        )
        VALUES
        (
            SOURCE.DIRPARTYRECORDID
            ,SOURCE.NAME
            ,SOURCE.PARTYNUMBER
            ,SOURCE.LANGUAGEID
            ,@dtt_ChangeDate
            ,@dtt_ChangeDate
            ,SOURCE.INSTANCERELATIONTYPE
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- UPSERT INTO THE DIRPERSONNAME
    MERGE INTO [ax].DIRPERSONNAME
    USING @TVP_CUSTOMERTABLETYPE AS SOURCE
    ON
        DIRPERSONNAME.RECID = SOURCE.PERSONNAMEID
    WHEN MATCHED THEN
        UPDATE
        SET
             FIRSTNAME             = SOURCE.FIRSTNAME
            ,MIDDLENAME            = SOURCE.MIDDLENAME
            ,LASTNAME              = SOURCE.LASTNAME
    WHEN NOT MATCHED THEN
        INSERT
        (
             RECID
,PERSON
            ,FIRSTNAME 
            ,MIDDLENAME
            ,LASTNAME
            ,VALIDFROM
            ,VALIDTO
        )
        VALUES
        (
             SOURCE.PERSONNAMEID
,SOURCE.DIRPARTYRECORDID
            ,SOURCE.FIRSTNAME
            ,SOURCE.MIDDLENAME
            ,SOURCE.LASTNAME
            ,@dtt_ChangeDate
            ,@dtt_MaxAxDate
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;


    -- UPSERT INTO THE CUSTTABLE
    MERGE INTO [ax].CUSTTABLE
    USING @TVP_CUSTOMERTABLETYPE AS SOURCE
    ON
        [ax].CUSTTABLE.ACCOUNTNUM = SOURCE.ACCOUNTNUMBER
and [ax].CUSTTABLE.DATAAREAID = @nvc_DataAreaId
    WHEN MATCHED THEN
        UPDATE
        SET
            INVOICEACCOUNT         = SOURCE.INVOICEACCOUNT
            ,CUSTGROUP              = SOURCE.CUSTGROUP
            ,CURRENCY               = SOURCE.CURRENCY
            ,MULTILINEDISC          = SOURCE.MULTILINEDISCOUNTGROUP
            ,ENDDISC                = SOURCE.TOTALDISCOUNTGROUP
            ,LINEDISC               = SOURCE.LINEDISCOUNTGROUP
            ,PRICEGROUP             = SOURCE.PRICEGROUP
            ,TAXGROUP               = SOURCE.TAXGROUP
            ,VATNUM                 = SOURCE.VATNUM
            ,CREDITMAX              = SOURCE.CREDITLIMIT
            ,BLOCKED                = SOURCE.BLOCKED
            ,ORGID                  = SOURCE.ORGID
            ,MODIFIEDDATETIME       = @dtt_ChangeDate
    WHEN NOT MATCHED THEN
        INSERT
        (
            RECID
            ,ACCOUNTNUM
            ,INVOICEACCOUNT
            ,CUSTGROUP
            ,CURRENCY
            ,MULTILINEDISC
            ,ENDDISC
            ,LINEDISC
            ,PRICEGROUP
            ,TAXGROUP
            ,VATNUM
            ,CREDITMAX
            ,BLOCKED
            ,ORGID
            ,PARTY
            ,CREATEDDATETIME
            ,MODIFIEDDATETIME
            ,DATAAREAID
        )
        VALUES
        (
            SOURCE.RECORDID
            ,SOURCE.ACCOUNTNUMBER
            ,SOURCE.INVOICEACCOUNT
            ,SOURCE.CUSTGROUP
            ,SOURCE.CURRENCY
            ,SOURCE.MULTILINEDISCOUNTGROUP
            ,SOURCE.TOTALDISCOUNTGROUP
            ,SOURCE.LINEDISCOUNTGROUP
            ,SOURCE.PRICEGROUP
            ,SOURCE.TAXGROUP
            ,SOURCE.VATNUM
            ,SOURCE.CREDITLIMIT
            ,SOURCE.BLOCKED
            ,SOURCE.ORGID
            ,SOURCE.DIRPARTYRECORDID
            ,@dtt_ChangeDate
            ,@dtt_ChangeDate
            ,@nvc_DataAreaId
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- UPSERT INTO THE RETAILCUSTTABLE BASED ON ACCOUNTNUMBER
    MERGE INTO [ax].RETAILCUSTTABLE
    USING @TVP_CUSTOMERTABLETYPE AS SOURCE
    ON
        [ax].RETAILCUSTTABLE.ACCOUNTNUM = SOURCE.ACCOUNTNUMBER
and [ax].RETAILCUSTTABLE.DATAAREAID = @nvc_DataAreaId
    WHEN MATCHED THEN
        UPDATE
        SET
             RECEIPTEMAIL            = SOURCE.RECEIPTEMAIL
            ,RECEIPTOPTION           = SOURCE.RECEIPTOPTION
            ,MODIFIEDDATETIME        = @dtt_ChangeDate

    WHEN NOT MATCHED THEN
        INSERT
        (
             RECID
            ,ACCOUNTNUM
            ,RECEIPTEMAIL
            ,RECEIPTOPTION
            ,MODIFIEDDATETIME
            ,DATAAREAID
        )
        VALUES
        (
             SOURCE.RETAILCUSTTABLERECORDID
            ,SOURCE.ACCOUNTNUMBER
            ,SOURCE.RECEIPTEMAIL
            ,SOURCE.RECEIPTOPTION
            ,@dtt_ChangeDate
            ,@nvc_DataAreaId
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

/* BEGIN SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this)
MERGE INTO [ax].RETAILCUSTPREFERENCE
USING (SELECT DISTINCT 
tp.PARENTRECID, tp.PROPERTYVALUE as [EMAILOPTIN], ct.ACCOUNTNUM, ct.DATAAREAID 
FROM @TVP_EXTENSIONPROPERTIESTABLETYPE tp
JOIN [ax].CUSTTABLE ct on ct.RECID = tp.PARENTRECID
WHERE tp.PARENTRECID <> 0 and tp.PROPERTYNAME = 'EMAILOPTIN') AS SOURCE
ON [ax].RETAILCUSTPREFERENCE.RECID = SOURCE.PARENTRECID
and [ax].RETAILCUSTPREFERENCE.DATAAREAID = SOURCE.DATAAREAID 
and [ax].RETAILCUSTPREFERENCE.ACCOUNTNUM = SOURCE.ACCOUNTNUM 
WHEN MATCHED THEN 
UPDATE SET [EMAILOPTIN] = source.[EMAILOPTIN]
WHEN NOT MATCHED THEN
INSERT
(
 RECID
,DATAAREAID
,EMAILOPTIN
,ACCOUNTNUM
)
VALUES
(
SOURCE.PARENTRECID
,SOURCE.DATAAREAID
,SOURCE.EMAILOPTIN
,SOURCE.ACCOUNTNUM
);

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;
END SDKSAMPLE_CUSTOMERPREFERENCES (do not remove this) */

   -- UPSERT INTO THE DIRADDRESSBOOKPARTY
    MERGE INTO [ax].DIRADDRESSBOOKPARTY
    USING @TVP_ADDRESSBOOKPARTYTABLETYPE AS SOURCE
    ON
        DIRADDRESSBOOKPARTY.RECID = SOURCE.RECORDID
    WHEN NOT MATCHED THEN
        INSERT
        (
             RECID
            ,ADDRESSBOOK
            ,PARTY
        )
        VALUES
        (
             SOURCE.RECORDID
            ,SOURCE.STOREADDRESSBOOK
            ,SOURCE.PARTY
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

IF (@UPDATEADDRESSES = 1)
BEGIN
-- EXEC THE CUSTOMERADDRESSES SPROC
EXEC @i_Error = [crt].CREATEUPDATECUSTOMERADDRESS @nvc_DataAreaId, @TVP_CUSTOMERADDRESSTABLETYPE;

IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

-- EXEC THE CUSTOMERELECTRONICADDRESSES SPROC
EXEC @i_Error = [crt].[CREATEUPDATEELECTRONICADDRESS] @TVP_CUSTOMERELECTRONICADDRESSTABLETYPE;

IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;
    END;

-- EXEC THE CUSTOMERAFFILIATION SPROC
IF (@UPDATECUSTOMERAFFILIATION = 1)
BEGIN
SELECT TOP 1 @nvc_CustomerAccountNumber = ACCOUNTNUMBER FROM @TVP_CUSTOMERTABLETYPE;
EXEC @i_Error = [crt].[CREATEUPDATECUSTOMERAFFILIATION] @nvc_CustomerAccountNumber, @nvc_DataAreaId, @TVP_CUSTOMERAFFILIATIONTABLETYPE;

IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;
END

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[CREATEUPDATECUSTOMER]'
GO
-- End creating stored procedure [crt].[CREATEUPDATECUSTOMER]


GRANT EXECUTE ON [crt].[CREATEUPDATECUSTOMER] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTCUSTOMERORDERTRANSACTION]
PRINT N'Creating stored procedure [crt].[INSERTCUSTOMERORDERTRANSACTION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTCUSTOMERORDERTRANSACTION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTCUSTOMERORDERTRANSACTION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTCUSTOMERORDERTRANSACTION].';
END
GO


ALTER PROCEDURE [crt].[INSERTCUSTOMERORDERTRANSACTION]
    @bi_channelId           BIGINT,
    @TVP_CUSTOMERORDERTRANS [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE]          READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [crt].CUSTOMERORDERTRANSACTION
    (
[CHANNEL],
[STORE],
[TERMINAL],
[TRANSACTIONID],
[DATAAREAID],
[CANCELLATIONCHARGE],
[DEPOSITOVERRIDE],
[REQUIREDDEPOSIT],
[CALCULATEDDEPOSIT],
[PREPAYMENTPAID],
[PREPAYMENTINVOICED]
    )
    SELECT
@bi_channelId,
[STORE],
[TERMINAL],
[TRANSACTIONID],
[DATAAREAID],
[CANCELLATIONCHARGE],
[DEPOSITOVERRIDE],
[REQUIREDDEPOSIT],
[CALCULATEDDEPOSIT],
[PREPAYMENTPAID],
[PREPAYMENTINVOICED]
    FROM @TVP_CUSTOMERORDERTRANS AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTCUSTOMERORDERTRANSACTION]'
GO
-- End creating stored procedure [crt].[INSERTCUSTOMERORDERTRANSACTION]


GRANT EXECUTE ON [crt].[INSERTCUSTOMERORDERTRANSACTION] TO [UsersRole];
GO

-- Creating stored procedure [crt].[SAVESALESTRANSACTIONS]
PRINT N'Creating stored procedure [crt].[SAVESALESTRANSACTIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVESALESTRANSACTIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVESALESTRANSACTIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVESALESTRANSACTIONS].';
END
GO


ALTER PROCEDURE [crt].[SAVESALESTRANSACTIONS]
    @tvp_SalesTransaction       [crt].[SALESTRANSACTIONTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode           INT;
    DECLARE @i_TransactionIsOurs    INT;
    DECLARE @i_RowIndex             INT;
    DECLARE @i_RowCount             INT;
    DECLARE @i_Error                INT;
    DECLARE @dtt_ChangeDate         DATETIME;

    -- Sales transaction table fields
    DECLARE @nvc_TransactionId      NVARCHAR(44);
    DECLARE @nvc_TerminalId         NVARCHAR(10);
    DECLARE @nvc_CustomerId         NVARCHAR(20);
    DECLARE @nvc_Name               NVARCHAR(128);
    DECLARE @i_ByteLength           INT;
    DECLARE @vb_TransactionData     VARBINARY(MAX);
    DECLARE @rv_RowVersion          ROWVERSION;
    DECLARE @b_IsSuspended          BIT;
    DECLARE @i_Type            INT;
    DECLARE @nvc_Comment            NVARCHAR(60);
DECLARE @bi_ChannelId           BIGINT;
DECLARE @nvc_Staff              NVARCHAR(25);
DECLARE @nu_AmountNUMERIC(32, 16);

    DECLARE @t_SalesTransactionIdTable    TABLE
    (
        i_RowIndex          INT             PRIMARY KEY IDENTITY(0,1)
        ,nvc_TransactionId  NVARCHAR(44)    NOT NULL
    );

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode           = 0;
    SET @i_TransactionIsOurs    = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Sort transactions by ID
    INSERT @t_SalesTransactionIdTable
    (
        nvc_TransactionId
    )
    SELECT
        Source.TRANSACTIONID
    FROM @tvp_SalesTransaction AS Source
    ORDER BY Source.TRANSACTIONID;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    SET @dtt_ChangeDate = GETUTCDATE();
    SET @i_RowIndex     = 0;

    -- Foreach transaction, do the upsert
    WHILE (1 = 1)
    BEGIN
        SELECT
            @nvc_TransactionId      = Source.TRANSACTIONID
            ,@bi_ChannelId          = Source.CHANNELID
            ,@nvc_TerminalId        = Source.TERMINALID
            ,@nvc_CustomerId        = Source.CUSTOMERID
            ,@nvc_Name              = Source.NAME
            ,@i_ByteLength          = Source.BYTELENGTH
            ,@vb_TransactionData    = Source.TRANSACTIONDATA
            ,@rv_RowVersion         = CAST(Source.ROWVERSION AS ROWVERSION)
            ,@b_IsSuspended         = Source.ISSUSPENDED
,@i_Type= Source.TYPE
,@nvc_Comment= Source.COMMENT
,@nvc_Staff= Source.STAFF
,@nu_Amount= Source.AMOUNT
        FROM @tvp_SalesTransaction Source
        INNER JOIN @t_SalesTransactionIdTable Sorted
            ON Source.TRANSACTIONID = Sorted.nvc_TransactionId
        WHERE
            Sorted.i_RowIndex = @i_RowIndex;

        SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        IF @i_Rowcount = 0
        BEGIN
            BREAK;
        END;

        -- Verifies whether the transaction already exists on DB
        SELECT
            @i_Rowcount = COUNT(TRANSACTIONID)
        FROM SALESTRANSACTION Target WITH (NOLOCK)
        WHERE
            Target.TRANSACTIONID = @nvc_TransactionId
            AND Target.DELETEDDATETIME IS NULL;

        -- If it does not exist, this is an insert
        IF (@i_RowCount = 0)
        BEGIN
            INSERT INTO [crt].SALESTRANSACTION
            (
                TRANSACTIONID
                ,CHANNELID
                ,TERMINALID
                ,CUSTOMERID
                ,NAME
                ,BYTELENGTH
                ,TRANSACTIONDATA
                ,CREATEDDATETIME
                ,ISSUSPENDED
,TYPE
,MODIFIEDDATETIME
,COMMENT
,STAFF
,AMOUNT
            )
            VALUES
            (
                @nvc_TransactionId
                ,@bi_ChannelId
                ,@nvc_TerminalId
                ,@nvc_CustomerId
                ,@nvc_Name
                ,@i_ByteLength
                ,@vb_TransactionData
                ,@dtt_ChangeDate
                ,@b_IsSuspended
,@i_Type
,@dtt_ChangeDate
,@nvc_Comment
,@nvc_Staff
,@nu_Amount
            );

            SELECT @i_Error = @@ERROR;
            IF @i_Error <> 0
            BEGIN
                SET @i_ReturnCode = @i_Error;
                GOTO exit_label;
            END;
        END;
        -- This is an update
        ELSE IF (@i_RowCount = 1)
        BEGIN
            UPDATE [crt].SALESTRANSACTION
            SET
                 TRANSACTIONID      = @nvc_TransactionId
                ,CHANNELID          = @bi_ChannelId
                ,TERMINALID         = @nvc_TerminalId
                ,CUSTOMERID         = @nvc_CustomerId
                ,NAME               = @nvc_Name
                ,BYTELENGTH         = @i_ByteLength
                ,TRANSACTIONDATA    = @vb_TransactionData
                ,MODIFIEDDATETIME   = @dtt_ChangeDate
                ,ISSUSPENDED        = @b_IsSuspended
,TYPE= @i_Type
,COMMENT= @nvc_Comment
,STAFF= @nvc_Staff
,AMOUNT    = @nu_Amount
            WHERE
                TRANSACTIONID = @nvc_TransactionId
                AND ROWVERSION = @rv_RowVersion;

            SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                SET @i_ReturnCode = @i_Error;
                GOTO exit_label;
            END;

            -- If no rows were changed, there was a problem updating (mostly because of row version)
            IF (@i_RowCount = 0)
            BEGIN;
                SET @i_ReturnCode = [crt].fn_kErrorVersionMismatchError();
                GOTO exit_label;
            END;
        END;

        SET @i_RowIndex = @i_RowIndex + 1; --so we eventually exit the loop
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVESALESTRANSACTIONS]'
GO
-- End creating stored procedure [crt].[SAVESALESTRANSACTIONS]


GRANT EXECUTE ON [crt].[SAVESALESTRANSACTIONS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETESALESTRANSACTIONS]
PRINT N'Creating stored procedure [crt].[DELETESALESTRANSACTIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETESALESTRANSACTIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETESALESTRANSACTIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETESALESTRANSACTIONS].';
END
GO


ALTER PROCEDURE [crt].[DELETESALESTRANSACTIONS]
    @tvp_SalesTransaction       [crt].[SALESTRANSACTIONTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;
    DECLARE @dtt_ChangeDate             DATETIME;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    SET @dtt_ChangeDate = GETUTCDATE();

    -- ensure that the customer identifier matches the transaction
    IF EXISTS (
        SELECT TOP 1 [Source].TRANSACTIONID, [Target].[CUSTOMERID]
        FROM @tvp_SalesTransaction AS [Source]
INNER JOIN SALESTRANSACTION AS [Target] 
ON [Source].TRANSACTIONID = [Target].TRANSACTIONID
        WHERE
ISNULL([Source].CUSTOMERID, '') != ISNULL([Target].CUSTOMERID, '')
)
    BEGIN
        SET @i_ReturnCode = [crt].fn_kErrorDbAuthorizationError();
        GOTO exit_label;
    END;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- Mark the rows as deleted
    UPDATE SALESTRANSACTION
    SET
        SALESTRANSACTION.DELETEDDATETIME = @dtt_ChangeDate
    FROM @tvp_SalesTransaction AS Source
    INNER JOIN SALESTRANSACTION 
ON Source.TRANSACTIONID = SALESTRANSACTION.TRANSACTIONID

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;


    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETESALESTRANSACTIONS]'
GO
-- End creating stored procedure [crt].[DELETESALESTRANSACTIONS]


GRANT EXECUTE ON [crt].[DELETESALESTRANSACTIONS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETESHIFTSTAGING]
PRINT N'Creating stored procedure [crt].[DELETESHIFTSTAGING]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETESHIFTSTAGING]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETESHIFTSTAGING] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETESHIFTSTAGING].';
END
GO


ALTER PROCEDURE [crt].[DELETESHIFTSTAGING]
    @bi_ChannelId       [BIGINT],
    @nvc_TerminalId     [NVARCHAR](10),
    @bi_ShiftId         [BIGINT],
    @rv_RowVersion      [ROWVERSION]
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode           INT;
    DECLARE @i_TransactionIsOurs    INT;
    DECLARE @i_RowCount             INT;
    DECLARE @i_Error                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    DELETE FROM [crt].RETAILSHIFTSTAGINGTABLE
    WHERE
        CHANNEL = @bi_ChannelId AND
        TERMINALID = @nvc_TerminalId AND
        SHIFTID = @bi_ShiftId AND
        ROWVERSION = @rv_RowVersion

     SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

     IF @i_Error <> 0
     BEGIN
         SET @i_ReturnCode = @i_Error;
         RETURN @i_ReturnCode;
     END;

     -- If no rows were changed, there was a problem updating (mostly because of row version)
     IF (@i_RowCount = 0)
     BEGIN;
         SET @i_ReturnCode = [crt].fn_kErrorVersionMismatchError();
         RETURN @i_ReturnCode;
     END;


    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETESHIFTSTAGING]'
GO
-- End creating stored procedure [crt].[DELETESHIFTSTAGING]


GRANT EXECUTE ON [crt].[DELETESHIFTSTAGING] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTINCOMEEXPENSETRANSACTION]
PRINT N'Creating stored procedure [crt].[INSERTINCOMEEXPENSETRANSACTION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTINCOMEEXPENSETRANSACTION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTINCOMEEXPENSETRANSACTION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTINCOMEEXPENSETRANSACTION].';
END
GO


ALTER PROCEDURE [crt].[INSERTINCOMEEXPENSETRANSACTION]
    @TVP_INCOMEEXPENSETYPE         [crt].[RETAILINCOMEEXPENSETABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

INSERT INTO [ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS]
    (
            [TRANSACTIONID]
,[RECEIPTID]
,[INCOMEEXEPENSEACCOUNT]
,[STORE]
,[TERMINAL]
,[STAFF]
,[TRANSACTIONSTATUS]
,[AMOUNT]
,[ACCOUNTTYPE]
,[TRANSDATE]
,[TRANSTIME]
,[DATAAREAID]
,[CHANNEL]
)
     SELECT
            [TRANSACTIONID]
,[RECEIPTID]
,[INCOMEEXEPENSEACCOUNT]
,[STORE]
,[TERMINAL]
,[STAFF]
,[TRANSACTIONSTATUS]
,[AMOUNT]
,[ACCOUNTTYPE]
,[TRANSDATE]
,[TRANSTIME]
,[DATAAREAID]
,[CHANNEL]
FROM @TVP_INCOMEEXPENSETYPE AS SOURCE;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTINCOMEEXPENSETRANSACTION]'
GO
-- End creating stored procedure [crt].[INSERTINCOMEEXPENSETRANSACTION]


GRANT EXECUTE ON [crt].[INSERTINCOMEEXPENSETRANSACTION] TO [UsersRole];
GO



-- Creating stored procedure [crt].[SAVEWISHLISTS]
PRINT N'Creating stored procedure [crt].[SAVEWISHLISTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVEWISHLISTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVEWISHLISTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVEWISHLISTS].';
END
GO


ALTER PROCEDURE [crt].[SAVEWISHLISTS]
    @tvp_WishList [crt].[WISHLISTTABLETYPE] READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode           INT;
    DECLARE @i_TransactionIsOurs    INT;
    DECLARE @i_RowIndex             INT;
    DECLARE @i_RowCount             INT;
    DECLARE @i_Error                INT;
    DECLARE @dtt_ChangeDate         DATETIME;

    -- Wish List table fields
    DECLARE @nvc_Id      NVARCHAR(44);
    DECLARE @nvc_CustomerId         NVARCHAR(20);
    DECLARE @nvc_Name               NVARCHAR(128);
    DECLARE @vb_WishListData        VARBINARY(max);
    DECLARE @b_Favorite BIT;
    DECLARE @b_Recurring BIT;

    DECLARE @t_WishListIdTable    TABLE
    (
        i_RowIndex          INT             PRIMARY KEY IDENTITY(0,1)
        ,nvc_Id  NVARCHAR(44)    NOT NULL
    );

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode           = 0;
    SET @i_TransactionIsOurs    = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Sort Wish Lists by ID
    INSERT @t_WishListIdTable
    (
        nvc_Id
    )
    SELECT
        Source.ID
    FROM @tvp_WishList AS Source
    ORDER BY Source.ID;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    SET @dtt_ChangeDate = GETUTCDATE();
    SET @i_RowIndex     = 0;

    IF ((SELECT
        Source.FAVORITE
        FROM @tvp_WishList AS Source) = 1)
    BEGIN
        UPDATE [crt].WISHLIST
        SET FAVORITE = 0, MODIFIEDDATETIME = @dtt_ChangeDate
        WHERE FAVORITE = 1;
    END;

    -- Foreach transaction, do the upsert
    WHILE (1 = 1)
    BEGIN
        SELECT
            @nvc_Id             = Source.ID
            ,@nvc_CustomerId    = Source.CUSTOMERID
            ,@nvc_Name          = Source.NAME
            ,@vb_WishListData   = Source.WISHLISTDATA
            ,@b_Favorite        = Source.FAVORITE
            ,@b_Recurring       = Source.RECURRING

        FROM @tvp_WishList Source
        INNER JOIN @t_WishListIdTable Sorted
            ON Source.ID = Sorted.nvc_Id
        WHERE
            Sorted.i_RowIndex = @i_RowIndex;

        SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        IF @i_Rowcount = 0
        BEGIN
            BREAK;
        END;

        -- Verifies whether the wishlist already exists on DB
        SELECT
            @i_Rowcount = COUNT(ID)
        FROM WISHLIST Target WITH (NOLOCK)
        WHERE
            Target.ID = @nvc_Id
            AND Target.DELETEDDATETIME IS NULL;

        -- If it does not exist, this is an insert
        IF (@i_RowCount = 0)
        BEGIN
            INSERT INTO [crt].WISHLIST
            (
                ID
                ,CUSTOMERID
                ,NAME
                ,WISHLISTDATA
                ,CREATEDDATETIME
                ,MODIFIEDDATETIME
                ,FAVORITE
                ,RECURRING
            )
            VALUES
            (
                @nvc_Id
                ,@nvc_CustomerId
                ,@nvc_Name
                ,@vb_WishListData
                ,@dtt_ChangeDate
                ,@dtt_ChangeDate
                ,@b_Favorite
                ,@b_Recurring
            );

            SELECT @i_Error = @@ERROR;
            IF @i_Error <> 0
            BEGIN
                SET @i_ReturnCode = @i_Error;
                GOTO exit_label;
            END;
        END;
        -- This is an update
        ELSE IF (@i_RowCount = 1)
        BEGIN
            UPDATE [crt].WISHLIST
            SET
                 ID                 = @nvc_Id
                ,CUSTOMERID         = @nvc_CustomerId
                ,NAME               = @nvc_Name
                ,WISHLISTDATA       = @vb_WishListData
                ,MODIFIEDDATETIME   = @dtt_ChangeDate
                ,FAVORITE           = @b_Favorite
                ,RECURRING          = @b_Recurring
            WHERE
                ID = @nvc_Id;

            SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                SET @i_ReturnCode = @i_Error;
                GOTO exit_label;
            END;

            -- If no rows were changed, there was a problem updating (mostly because of row version)
            IF (@i_RowCount = 0)
            BEGIN;
                SET @i_ReturnCode = [crt].fn_kErrorVersionMismatchError();
                GOTO exit_label;
            END;
         END;

        SET @i_RowIndex = @i_RowIndex + 1; --so we eventually exit the loop
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;


        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVEWISHLISTS]'
GO
-- End creating stored procedure [crt].[SAVEWISHLISTS]


GRANT EXECUTE ON [crt].[SAVEWISHLISTS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETEWISHLIST]
PRINT N'Creating stored procedure [crt].[DELETEWISHLIST]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETEWISHLIST]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETEWISHLIST] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETEWISHLIST].';
END
GO


ALTER PROCEDURE [crt].[DELETEWISHLIST]
    @tvp_WishList [crt].[WISHLISTTABLETYPE] READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode           INT;
    DECLARE @i_TransactionIsOurs    INT;
    DECLARE @i_RowCount             INT;
    DECLARE @i_Error                INT;


    -- Wish List table fields
    DECLARE @nvc_Id      NVARCHAR(44);

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode           = 0;
    SET @i_TransactionIsOurs    = 0;


IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

        UPDATE [crt].WISHLIST
        SET DELETEDDATETIME = GETUTCDATE(), MODIFIEDDATETIME = GETUTCDATE()
        FROM @tvp_WishList AS Source
        INNER JOIN [crt].WISHLIST Target WITH (NOLOCK) ON Target.ID = Source.ID

        SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        -- If no rows were changed, there was a problem updating (mostly because of row version)
     ELSE IF (@i_RowCount = 0)
        BEGIN;
            SET @i_ReturnCode = [crt].fn_kErrorVersionMismatchError();
            GOTO exit_label;
        END;
     END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;
    RETURN @i_ReturnCode;


GO
PRINT N'Finished creating stored procedure [crt].[DELETEWISHLIST]'
GO
-- End creating stored procedure [crt].[DELETEWISHLIST]


GRANT EXECUTE ON [crt].[DELETEWISHLIST] TO [UsersRole];
GO

-- Creating stored procedure [crt].[RESERVEITEMS]
PRINT N'Creating stored procedure [crt].[RESERVEITEMS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[RESERVEITEMS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[RESERVEITEMS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[RESERVEITEMS].';
END
GO


-- Reserve items for available quantities.
-- Return success and commit the reservations if quantities available, or return error and rollback if out of stock.
ALTER PROCEDURE [crt].[RESERVEITEMS]
    @tvp_ItemReservations   [crt].ITEMRESERVATIONTABLETYPE    READONLY,
    @nvc_DataAreaId    NVARCHAR(4)
AS
BEGIN
    SET NOCOUNT ON;

-- storing current datetime in a variable to be used throughout the procedure.
DECLARE @dt_Today DATETIME = GETUTCDATE();
    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;
    DECLARE @i_RequestedReservations    INT;
    DECLARE @i_GrantedReservations      INT;
    DECLARE @t_GrantedReservationIds    TABLE (RESERVATIONID UNIQUEIDENTIFIER PRIMARY KEY)
    DECLARE @i_RejectedReservations     INT;
    DECLARE @t_RejectedReservationIds   TABLE (RESERVATIONID UNIQUEIDENTIFIER PRIMARY KEY)

    SET @i_ReturnCode           = [crt].fn_kSuccess();
    SET @i_TransactionIsOurs    = 0;

    SELECT @i_RequestedReservations = COUNT(*) FROM @tvp_ItemReservations;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;
        SET @i_TransactionIsOurs = 1;
    END;

    -- Purge released or expired reservations.
    DELETE ITEMRESERVATION WHERE ISRELEASED = 1 OR EXPIREDATETIME < @dt_Today;

    SET @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- Try to insert reservations.
    INSERT ITEMRESERVATION(RESERVATIONID, INVENTAVAILABILITY, QUANTITY, EXPIREDATETIME, ISRELEASED)
        OUTPUT INSERTED.RESERVATIONID
        INTO @t_GrantedReservationIds
        SELECT ir.RESERVATIONID, riav.RECID, ir.QUANTITY, ir.EXPIREDATETIME, 0
        FROM @tvp_ItemReservations ir
        INNER JOIN RETAILINVENTAVAILABILITYVIEW riav ON ir.ITEMID = riav.ITEMID AND ir.INVENTDIMID = riav.INVENTDIMID AND riav.DATAAREAID = @nvc_DataAreaId
        WHERE riav.AVAILPHYSICAL >= ir.QUANTITY;

    SELECT @i_Error = @@ERROR, @i_GrantedReservations = @@ROWCOUNT;

    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_GrantedReservations < @i_RequestedReservations
    BEGIN
        SELECT ir.RESERVATIONID
        FROM @tvp_ItemReservations ir
        LEFT JOIN @t_GrantedReservationIds gri ON gri.RESERVATIONID = ir.RESERVATIONID
        WHERE gri.RESERVATIONID IS NULL;

        SET @i_ReturnCode = [crt].fn_kErrorDbItemOutOfStock();
        GOTO exit_label;
    END

    -- Check if two concurrent requests have overallocated items.
    -- It is possible but less likely both requests may rollback even though one of them could be satisfied.
    -- This is the tradeoff between optimistic concurrency control and pessimistic concurrency control.
    -- The caller is expected to double check item availability and retry if still available.
    INSERT @t_RejectedReservationIds(RESERVATIONID)
        SELECT RESERVATIONID
        FROM @tvp_ItemReservations ir
        JOIN
        (
            SELECT
                it.ITEMID
                ,id.INVENTDIMID
                ,ria.AVAILPHYSICAL - ISNULL(rs.QUANTITY, 0) AS AVAILPHYSICAL
            FROM [ax].RETAILINVENTAVAILABILITY ria
            INNER JOIN [ax].INVENTTABLE it ON it.RECID = ria.ITEMRECID AND it.DATAAREAID = @nvc_DataAreaId
            INNER JOIN [ax].INVENTDIM id on id.RECID = ria.INVENTDIMRECID AND id.DATAAREAID = @nvc_DataAreaId 
            LEFT JOIN
            (
                SELECT
                    INVENTAVAILABILITY
                    ,SUM(QUANTITY) AS QUANTITY
                FROM [crt].ITEMRESERVATION WITH(NOLOCK)   -- Including inserted but not yet committed reservations
                WHERE EXPIREDATETIME >= @dt_Today     -- Including released but not yet committed reservations
                GROUP BY INVENTAVAILABILITY
            ) rs ON rs.INVENTAVAILABILITY = ria.RECID
        ) a ON ir.ITEMID = a.ITEMID AND ir.INVENTDIMID = a.INVENTDIMID
        WHERE a.AVAILPHYSICAL < 0;

    SELECT @i_Error = @@ERROR, @i_RejectedReservations = @@ROWCOUNT;

    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_RejectedReservations > 0
    BEGIN
        SELECT RESERVATIONID FROM @t_RejectedReservationIds;
        SET @i_ReturnCode = [crt].fn_kErrorDbItemOutOfStock();
        GOTO exit_label;
    END

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;
        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[RESERVEITEMS]'
GO
-- End creating stored procedure [crt].[RESERVEITEMS]


GRANT EXECUTE ON [crt].[RESERVEITEMS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[RELEASEITEMS]
PRINT N'Creating stored procedure [crt].[RELEASEITEMS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[RELEASEITEMS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[RELEASEITEMS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[RELEASEITEMS].';
END
GO


-- Release items for available quantities.
ALTER PROCEDURE [crt].RELEASEITEMS
    @tvp_ItemReservationIds [crt].ITEMRESERVATIONIDTABLETYPE READONLY
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    SET @i_ReturnCode           = [crt].fn_kSuccess();
    SET @i_TransactionIsOurs    = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;
        SET @i_TransactionIsOurs = 1;
    END;

    UPDATE ITEMRESERVATION
    SET ISRELEASED = 1
    FROM @tvp_ItemReservationIds iri
    INNER JOIN ITEMRESERVATION ir ON ir.RESERVATIONID = iri.RESERVATIONID;

    SET @i_Error = @@ERROR;

    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;
        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[RELEASEITEMS]'
GO
-- End creating stored procedure [crt].[RELEASEITEMS]


GRANT EXECUTE ON [crt].[RELEASEITEMS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[VALIDATEADDRESS]
PRINT N'Creating stored procedure [crt].[VALIDATEADDRESS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[VALIDATEADDRESS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[VALIDATEADDRESS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[VALIDATEADDRESS].';
END
GO


ALTER PROCEDURE [crt].[VALIDATEADDRESS]
    @COUNTRYREGIONID    NVARCHAR(10),
    @STATEPROVINCEID    NVARCHAR(10) = NULL,
    @COUNTYID           NVARCHAR(10) = NULL,
    @CITY               NVARCHAR(60) = NULL,
    @DISTRICT           NVARCHAR(60) = NULL,
    @ZIPPOSTALCODE      NVARCHAR(10) = NULL
AS
BEGIN
SET NOCOUNT ON

DECLARE @i_ReturnCode               INT;
DECLARE @i_TransactionIsOurs        INT;
DECLARE @i_Error                    INT;

-- CountryId is mandatory according to Ax schema
IF (@COUNTRYREGIONID IS NULL)
BEGIN
    SET @i_ReturnCode           = 1 ; -- invalid countryid
    GOTO exit_label;
END

IF NOT EXISTS
(
    SELECT 1
    FROM [ax].LOGISTICSADDRESSCOUNTRYREGION LCNTRY
    WHERE LCNTRY.COUNTRYREGIONID = @COUNTRYREGIONID
)
BEGIN
    SET @i_ReturnCode           = 1 ; -- invalid country
    GOTO exit_label;
END

-- Validate State, if exists
IF (@STATEPROVINCEID IS NOT NULL)
BEGIN
    IF NOT EXISTS
    (
        SELECT 1
        FROM [ax].LOGISTICSADDRESSSTATE LSTATE
        WHERE
            LSTATE.STATEID = @STATEPROVINCEID AND
            LSTATE.COUNTRYREGIONID = @COUNTRYREGIONID
    )
    BEGIN
        SET @i_ReturnCode           = 2 ; -- invalid stateid
        GOTO exit_label;
    END
END

-- Validate County, if exists
IF (@COUNTYID IS NOT NULL)
BEGIN
    IF NOT EXISTS
    (
        SELECT 1
        FROM [ax].LOGISTICSADDRESSCOUNTY LCNTY
        WHERE
            LCNTY.COUNTYID = @COUNTYID AND
            LCNTY.COUNTRYREGIONID = @COUNTRYREGIONID AND
            (@STATEPROVINCEID IS NULL OR LCNTY.STATEID = @STATEPROVINCEID)
    )
    BEGIN
        SET @i_ReturnCode           = 3 ; -- invalid countyid
        GOTO exit_label;
    END
END

-- Validate City, if exists
IF (@CITY IS NOT NULL)
BEGIN
    IF NOT EXISTS
    (
        SELECT 1
        FROM [ax].LOGISTICSADDRESSSCITY LCITY
        INNER JOIN [ax].LOGISTICSADDRESSCOUNTRYREGION LCNTRY ON LCNTRY.COUNTRYREGIONID = LCITY.COUNTRYREGIONID
        WHERE
            LCITY.NAME = @CITY
            AND LCITY.COUNTRYREGIONID = LCNTRY.COUNTRYREGIONID
            AND (@STATEPROVINCEID IS NULL OR LCITY.STATEID = @STATEPROVINCEID)
            AND (@COUNTYID IS NULL OR LCITY.COUNTYID = '' OR LCITY.COUNTYID = @COUNTYID)
    )
    BEGIN
        SET @i_ReturnCode           = 4 ; -- invalid city
        GOTO exit_label;
    END
END

-- Validate District, if exists
IF (@DISTRICT IS NOT NULL)
BEGIN
    IF NOT EXISTS
    (
        SELECT 1
        FROM [ax].LOGISTICSADDRESSDISTRICT LDIST
        LEFT OUTER JOIN [ax].LOGISTICSADDRESSSCITY LCITY ON LCITY.RECID = LDIST.CITY
        WHERE
            LDIST.NAME = @DISTRICT
            AND (@CITY IS NULL OR LCITY.NAME = @CITY )
            AND (@COUNTYID IS NULL OR LCITY.COUNTYID = '' OR LCITY.COUNTYID = @COUNTYID)
            AND (@STATEPROVINCEID IS NULL OR LCITY.STATEID = @STATEPROVINCEID)
            AND (LCITY.COUNTRYREGIONID = @COUNTRYREGIONID)
    )
    BEGIN
        SET @i_ReturnCode           = 5 ; -- invalid district
        GOTO exit_label;
    END
END

-- Validate ZipCode, if exists
IF (@ZIPPOSTALCODE IS NOT NULL)
BEGIN
    IF NOT EXISTS
    (
        SELECT 1
        FROM [ax].LOGISTICSADDRESSZIPCODE LZIP
        WHERE
            LZIP.ZIPCODE = @ZIPPOSTALCODE
            AND LZIP.COUNTRYREGIONID = @COUNTRYREGIONID
            AND (@STATEPROVINCEID IS NULL OR LZIP.STATE = @STATEPROVINCEID)
            AND (@COUNTYID IS NULL OR LZIP.COUNTY = '' OR LZIP.COUNTY = @COUNTYID)
            AND (@CITY IS NULL OR LZIP.CITY = @CITY)
            AND (@DISTRICT IS NULL OR LZIP.DISTRICTNAME = '' OR LZIP.DISTRICTNAME = @DISTRICT)
    )
    BEGIN
        SET @i_ReturnCode           = 6 ; -- invalid zipcode
        GOTO exit_label;
    END
END

SET @i_ReturnCode = 0;

exit_label:

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[VALIDATEADDRESS]'
GO
-- End creating stored procedure [crt].[VALIDATEADDRESS]


GRANT EXECUTE ON [crt].[VALIDATEADDRESS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETADDRESSFORMATTING]
PRINT N'Creating stored procedure [crt].[GETADDRESSFORMATTING]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETADDRESSFORMATTING]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETADDRESSFORMATTING] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETADDRESSFORMATTING].';
END
GO


-- Returns only active field (INACTIVE == 0) with proper formatting metadata
ALTER PROCEDURE [crt].[GETADDRESSFORMATTING]
    @nvc_CountryRegionId    NVARCHAR(10)
AS
BEGIN

    SET NOCOUNT ON

    SELECT
        LAFL.ELEMENT
       ,CAST(LAFL.LINENUM AS INT) AS LINEINDEX
       ,LAFL.DATAENTRYONLY
    FROM [ax].LOGISTICSADDRESSCOUNTRYREGION LACR
    INNER JOIN [ax].LOGISTICSADDRESSFORMATHEADING LAFH ON LACR.ADDRFORMAT = LAFH.ADDRFORMAT
    INNER JOIN [ax].LOGISTICSADDRESSFORMATLINES LAFL ON LAFH.ADDRFORMAT = LAFL.ADDRFORMAT
    WHERE
        LAFL.INACTIVE = 0
        AND LACR.COUNTRYREGIONID = @nvc_CountryRegionId
    ORDER BY LINEINDEX ASC

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETADDRESSFORMATTING]'
GO
-- End creating stored procedure [crt].[GETADDRESSFORMATTING]


GRANT EXECUTE ON [crt].[GETADDRESSFORMATTING] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS]
PRINT N'Creating stored procedure [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS].';
END
GO


ALTER PROCEDURE [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS]
    @bi_ChannelId             BIGINT,
    @affiliationLoyaltyTiers  [crt].[AFFILIATIONLOYALTYTIERTABLETYPE] READONLY
AS
BEGIN
    SET NOCOUNT ON

    SELECT pdg.GROUPID
        , rapg.PRICEDISCGROUP AS 'PRICEGROUP'
, rapg.RECID
    FROM [ax].PRICEDISCGROUP pdg
    INNER JOIN [ax].RETAILAFFILIATIONPRICEGROUP rapg 
        ON rapg.PRICEDISCGROUP = pdg.RECID
    INNER JOIN @affiliationLoyaltyTiers alt
ON rapg.RETAILAFFILIATION = alt.AFFILIATIONID AND (rapg.RETAILLOYALTYTIER = 0 OR rapg.RETAILLOYALTYTIER = alt.LOYALTYTIERID)
    INNER JOIN [ax].RETAILCHANNELTABLE AS c
        ON c.INVENTLOCATIONDATAAREAID = pdg.DATAAREAID AND c.RECID = @bi_ChannelId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS]'
GO
-- End creating stored procedure [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS]


GRANT EXECUTE ON [crt].[GETAFFILIATIONLOYALTYTIERPRICEGROUPS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GetCustomerLocalPendingDeposit]
PRINT N'Creating stored procedure [crt].[GetCustomerLocalPendingDeposit]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GetCustomerLocalPendingDeposit]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GetCustomerLocalPendingDeposit] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GetCustomerLocalPendingDeposit].';
END
GO


ALTER PROCEDURE [crt].[GetCustomerLocalPendingDeposit] 
@nvc_AccountNumber     NVARCHAR(30),
@nvc_StoreId           NVARCHAR(10),
    @i_LastCounter       INT,
@nvc_DataAreaId        NVARCHAR(4),
@d_amount   DECIMAL(32,16) OUTPUT 
AS
BEGIN
    SET NOCOUNT ON   

set @d_amount = 0.0;

SELECT @d_amount = ISNULL(SUM(rtpt.[AMOUNTMST]), 0.0) 
FROM ax.RETAILTRANSACTIONPAYMENTTRANS rtpt
    INNER JOIN ax.RETAILTRANSACTIONTABLE rtt on rtpt.STORE = rtt.STORE AND rtpt.TERMINAL = rtt.TERMINAL AND rtpt.TRANSACTIONID = rtt.TRANSACTIONID
    WHERE rtpt.STORE = @nvc_StoreId 
AND rtpt.DATAAREAID = @nvc_DataAreaId 
AND rtpt.TRANSACTIONSTATUS in (0) --Normal
AND rtt.ENTRYSTATUS in (0, 2, 3) --Normal, OnHold, Concluded
AND rtt.TYPE = 3 --Payment 
AND rtt.CUSTACCOUNT = @nvc_AccountNumber
AND rtpt.COUNTER> @i_LastCounter;
END;


GO
PRINT N'Finished creating stored procedure [crt].[GetCustomerLocalPendingDeposit]'
GO
-- End creating stored procedure [crt].[GetCustomerLocalPendingDeposit]


GRANT EXECUTE ON [crt].[GetCustomerLocalPendingDeposit] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GetCustomerLocalPendingTenders]
PRINT N'Creating stored procedure [crt].[GetCustomerLocalPendingTenders]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GetCustomerLocalPendingTenders]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GetCustomerLocalPendingTenders] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GetCustomerLocalPendingTenders].';
END
GO


ALTER PROCEDURE [crt].[GetCustomerLocalPendingTenders] 
@nvc_AccountNumber     NVARCHAR(30),
@nvc_StoreId           NVARCHAR(10),
@nvc_TenderTypeId      NVARCHAR(10),
    @i_LastCounter       INT,
@nvc_DataAreaId        NVARCHAR(4),
@d_amount   DECIMAL(32,16) OUTPUT
AS
BEGIN
    SET NOCOUNT ON   

set @d_amount = 0.0;

SELECT @d_amount = ISNULL(SUM(rtpt.[AMOUNTMST]), 0.0)
from ax.RETAILTRANSACTIONPAYMENTTRANS rtpt 
INNER JOIN ax.RETAILTRANSACTIONTABLE rtt ON rtpt.STORE = rtt.STORE AND rtpt.TERMINAL = rtt.TERMINAL AND rtpt.TRANSACTIONID = rtt.TRANSACTIONID
    WHERE rtpt.STORE = @nvc_StoreId 
      AND rtpt.DATAAREAID = @nvc_DataAreaId 
      AND rtpt.CARDORACCOUNT = @nvc_AccountNumber
      AND rtpt.TENDERTYPE = @nvc_TenderTypeId
      AND rtpt.TRANSACTIONSTATUS in (0) --Normal
      AND rtt.ENTRYSTATUS in (0, 2, 3) --Normal, OnHold, Concluded
      AND rtt.TYPE = 2 -- Sales
      AND rtpt.COUNTER > @i_LastCounter 

  return
END;

GO
PRINT N'Finished creating stored procedure [crt].[GetCustomerLocalPendingTenders]'
GO
-- End creating stored procedure [crt].[GetCustomerLocalPendingTenders]


GRANT EXECUTE ON [crt].[GetCustomerLocalPendingTenders] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GetCustomerPendingTransactionsAmount]
PRINT N'Creating stored procedure [crt].[GetCustomerPendingTransactionsAmount]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GetCustomerPendingTransactionsAmount]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GetCustomerPendingTransactionsAmount] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GetCustomerPendingTransactionsAmount].';
END
GO


ALTER PROCEDURE [crt].[GetCustomerPendingTransactionsAmount] 
@nvc_AccountNumber     NVARCHAR(30),
@nvc_StoreId           NVARCHAR(10),
@nvc_TenderTypeId      NVARCHAR(10),
    @i_LastCounter       INT,
@nvc_DataAreaId        NVARCHAR(4),
@d_tenderAmount   DECIMAL OUTPUT,
@d_depositAmount   DECIMAL OUTPUT
AS
BEGIN
    SET NOCOUNT ON   
exec crt.GetCustomerLocalPendingTenders @nvc_AccountNumber, @nvc_StoreId, @nvc_TenderTypeId, @i_LastCounter, @nvc_DataAreaId, @d_tenderAmount OUTPUT
exec crt.GetCustomerLocalPendingDeposit @nvc_AccountNumber, @nvc_StoreId, @i_LastCounter, @nvc_DataAreaId, @d_depositAmount OUTPUT

END;

GO
PRINT N'Finished creating stored procedure [crt].[GetCustomerPendingTransactionsAmount]'
GO
-- End creating stored procedure [crt].[GetCustomerPendingTransactionsAmount]


GRANT EXECUTE ON [crt].[GetCustomerPendingTransactionsAmount] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLOYALTYGROUPSBYLOYALTYCARD]
PRINT N'Creating stored procedure [crt].[GETLOYALTYGROUPSBYLOYALTYCARD]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLOYALTYGROUPSBYLOYALTYCARD]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLOYALTYGROUPSBYLOYALTYCARD] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLOYALTYGROUPSBYLOYALTYCARD].';
END
GO


ALTER PROCEDURE [crt].[GETLOYALTYGROUPSBYLOYALTYCARD]
    @nvc_LoyaltyCardNumberNVARCHAR(30),
@nvc_LocaleNVARCHAR(7) = 'en-us'
AS
BEGIN
    SET NOCOUNT ON

    -- Select all RetailAffiliation which are associated with the loyalty card
select
ra.RECID,
ra.NAME,
rat.DESCRIPTION
from [ax].[RETAILAFFILIATION] ra
left join [ax].[RETAILAFFILIATIONTRANSLATION] rat
on rat.AFFILIATION = ra.RECID
and rat.LANGUAGEID = @nvc_Locale
where ra.RECID in
(
select
rlct.AFFILIATION
from [ax].[RETAILLOYALTYCARD] rlc
inner join [ax].[RETAILLOYALTYCARDTIER] rlct
on rlct.LOYALTYCARD = rlc.RECID
where rlc.CARDNUMBER = @nvc_LoyaltyCardNumber
group by rlct.AFFILIATION
)

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLOYALTYGROUPSBYLOYALTYCARD]'
GO
-- End creating stored procedure [crt].[GETLOYALTYGROUPSBYLOYALTYCARD]


GRANT EXECUTE ON [crt].[GETLOYALTYGROUPSBYLOYALTYCARD] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS]
PRINT N'Creating stored procedure [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETACTIVEORFUTURELOYALTYCARDTIERS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS].';
END
GO


ALTER PROCEDURE [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS]
    @nvc_LoyaltyCardNumberNVARCHAR(30),
@bi_LoyaltyGroupRecordId        BIGINT,
@dt_ChannelLocalDateDATE,
@b_retrieveFutureCardTiersBIT
    
AS
BEGIN
    SET NOCOUNT ON

    -- Declare a table variable to store active or future card tiers.
DECLARE @ActiveOrFutureCardTiers TABLE
(
[RECID] [bigint],
[LOYALTYTIER] [bigint],
[TIERID] [nvarchar](64),
[VALIDFROM] [date],
[VALIDTO] [date]
)

-- Find all active card tiers.
-- If multiple such entries are found for the same card tier, pick the one expires the latest.
insert into @ActiveOrFutureCardTiers
select
ActiveCardTiers.RECID,
ActiveCardTiers.LOYALTYTIER,
ActiveCardTiers.TIERID,
ActiveCardTiers.VALIDFROM,
ActiveCardTiers.VALIDTO
from
(
select
ROW_NUMBER() OVER (PARTITION BY rlt.TIERID ORDER BY rlct.VALIDTO DESC) Ordinal,
rlct.RECID,
rlt.RECID as LOYALTYTIER,
rlt.TIERID,
rlct.VALIDFROM,
rlct.VALIDTO
from [ax].[RETAILLOYALTYCARDTIER] rlct
inner join [ax].[RETAILLOYALTYCARD] rlc
on rlc.RECID = rlct.LOYALTYCARD
inner join [ax].[RETAILLOYALTYTIER] rlt
on rlt.RECID = rlct.LOYALTYTIER
where rlc.CARDNUMBER = @nvc_LoyaltyCardNumber
and rlct.AFFILIATION = @bi_LoyaltyGroupRecordId
and rlct.LOYALTYTIER != 0
and (rlct.VALIDFROM is NULL or rlct.VALIDFROM <= @dt_ChannelLocalDate)
and (rlct.VALIDTO is NULL or rlct.VALIDTO >= @dt_ChannelLocalDate)
) ActiveCardTiers
where ActiveCardTiers.Ordinal = 1

-- find all the card tiers which are not active now but will be in the future.
-- If multiple such entries are found for the same card tier, pick the one takes effect the earliest.
IF (@b_retrieveFutureCardTiers = 1)
BEGIN
insert into @ActiveOrFutureCardTiers
select
FutureCardTiers.RECID,
FutureCardTiers.LOYALTYTIER,
FutureCardTiers.TIERID,
FutureCardTiers.VALIDFROM,
FutureCardTiers.VALIDTO
from
(
select
ROW_NUMBER() OVER (PARTITION BY rlt.TIERID ORDER BY rlct.VALIDFROM ASC) Ordinal,
rlct.RECID,
rlt.RECID as LOYALTYTIER,
rlt.TIERID,
rlct.VALIDFROM,
rlct.VALIDTO
from [ax].[RETAILLOYALTYCARDTIER] rlct
inner join [ax].[RETAILLOYALTYCARD] rlc
on rlc.RECID = rlct.LOYALTYCARD
inner join [ax].[RETAILLOYALTYTIER] rlt
on rlt.RECID = rlct.LOYALTYTIER
where rlc.CARDNUMBER = @nvc_LoyaltyCardNumber
and rlct.AFFILIATION = @bi_LoyaltyGroupRecordId
and rlct.LOYALTYTIER != 0
and rlct.VALIDFROM > @dt_ChannelLocalDate
) FutureCardTiers
where FutureCardTiers.Ordinal = 1
and FutureCardTiers.TIERID not in 
(select TIERID from @ActiveOrFutureCardTiers)
END

select 
        [RECID],
[LOYALTYTIER],
[TIERID],
[VALIDFROM],
[VALIDTO]
    from @ActiveOrFutureCardTiers

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS]'
GO
-- End creating stored procedure [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS]


GRANT EXECUTE ON [crt].[GETACTIVEORFUTURELOYALTYCARDTIERS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLOYALTYCARD]
PRINT N'Creating stored procedure [crt].[GETLOYALTYCARD]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLOYALTYCARD]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLOYALTYCARD] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLOYALTYCARD].';
END
GO


ALTER PROCEDURE [crt].[GETLOYALTYCARD]
    @nvc_LoyaltyCardNumberNVARCHAR(30),
@nvc_CustomerDataAreaIdNVARCHAR(4)
AS
BEGIN
    SET NOCOUNT ON

    -- Select the loyalty card by loyalty card number.
-- If the loyalty card is associated with a party, also try to find the customer number in the given company.
SELECT
        rlc.RECID,
        rlc.CARDNUMBER,
        rlc.CARDTENDERTYPE,
rlc.PARTY,
COALESCE(dpt.PARTYNUMBER, '') AS PARTYNUMBER,
COALESCE(ct.ACCOUNTNUM, '') AS CUSTOMERACCOUNT,
COALESCE(ct.DATAAREAID, '') AS CUSTOMERDATAAREAID
    FROM [ax].[RETAILLOYALTYCARD] rlc
LEFT OUTER JOIN [ax].[DIRPARTYTABLE] dpt
on dpt.RECID = rlc.PARTY
LEFT OUTER JOIN [ax].[CUSTTABLE] ct
on ct.PARTY = rlc.PARTY
    and ct.DATAAREAID = @nvc_CustomerDataAreaId
WHERE rlc.CARDNUMBER = @nvc_LoyaltyCardNumber

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLOYALTYCARD]'
GO
-- End creating stored procedure [crt].[GETLOYALTYCARD]


GRANT EXECUTE ON [crt].[GETLOYALTYCARD] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLOYALTYTIERS]
PRINT N'Creating stored procedure [crt].[GETLOYALTYTIERS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLOYALTYTIERS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLOYALTYTIERS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLOYALTYTIERS].';
END
GO


ALTER PROCEDURE [crt].[GETLOYALTYTIERS]
    @bi_loyaltyGroupRecordId        BIGINT,
@nvc_LocaleNVARCHAR(7) = 'en-us'
AS
BEGIN
    SET NOCOUNT ON

    -- Select all RetailLoyaltyTier of the loyalty program
select
rlt.RECID,
rlt.AFFILIATION as LoyaltyGroupRecordId,
rlt.TIERID,
rlt.TIERLEVEL,
rltt.DESCRIPTION
from [ax].[RETAILLOYALTYTIER] rlt
left join [ax].[RETAILLOYALTYTIERTRANSLATION] rltt
on rltt.LOYALTYTIER = rlt.RECID
and rltt.LANGUAGEID = @nvc_Locale
where rlt.AFFILIATION = @bi_loyaltyGroupRecordId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLOYALTYTIERS]'
GO
-- End creating stored procedure [crt].[GETLOYALTYTIERS]


GRANT EXECUTE ON [crt].[GETLOYALTYTIERS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETCITIES]
PRINT N'Creating stored procedure [crt].[GETCITIES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETCITIES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETCITIES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETCITIES].';
END
GO


ALTER PROCEDURE [crt].[GETCITIES]
    @CountryRegionId    NVARCHAR(10),
    @StateProvinceID    NVARCHAR(10) = NULL,
    @CountyId           NVARCHAR(10) = NULL
AS
BEGIN

    SET NOCOUNT ON

    DECLARE @StateProvinceIDIsNull BIT = CASE WHEN (@StateProvinceID IS NULL OR LEN(LTRIM(RTRIM(@StateProvinceID))) = 0) THEN 1 ELSE 0 END
    DECLARE @CountyIdIsNull BIT = CASE WHEN (@CountyId IS NULL OR LEN(LTRIM(RTRIM(@CountyId))) = 0) THEN 1 ELSE 0 END
    
    SELECT
        LCITY.NAME AS CITYNAME
       ,LCITY.DESCRIPTION
       ,LCITY.COUNTYID
       ,LCITY.COUNTRYREGIONID
       ,LCITY.STATEID
    FROM [ax].LOGISTICSADDRESSSCITY LCITY
    WHERE
        LCITY.COUNTRYREGIONID = @CountryRegionId
        AND (@StateProvinceIDIsNull = 1 OR LCITY.STATEID = @StateProvinceID)
        AND (@CountyIdIsNull = 1 OR LCITY.COUNTYID = @CountyId)

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETCITIES]'
GO
-- End creating stored procedure [crt].[GETCITIES]


GRANT EXECUTE ON [crt].[GETCITIES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETCOUNTIES]
PRINT N'Creating stored procedure [crt].[GETCOUNTIES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETCOUNTIES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETCOUNTIES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETCOUNTIES].';
END
GO


ALTER PROCEDURE [crt].[GETCOUNTIES]
    @CountryRegionId    NVARCHAR(10),
    @StateProvinceID    NVARCHAR(10) = NULL
AS
BEGIN

    SET NOCOUNT ON

DECLARE @StateProvinceIDIsNull BIT = CASE WHEN (@StateProvinceID IS NULL OR LEN(LTRIM(RTRIM(@StateProvinceID))) = 0) THEN 1 ELSE 0 END

    SELECT
        LCNTY.COUNTYID
       ,LCNTY.NAME
       ,LCNTY.COUNTYCODE_SP
       ,LCNTY.COUNTRYREGIONID
       ,LCNTY.STATEID
    FROM [ax].LOGISTICSADDRESSCOUNTY LCNTY
    WHERE
        LCNTY.COUNTRYREGIONID = @CountryRegionId
        AND (@StateProvinceIDIsNull = 1 OR LCNTY.STATEID = @StateProvinceID)

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETCOUNTIES]'
GO
-- End creating stored procedure [crt].[GETCOUNTIES]


GRANT EXECUTE ON [crt].[GETCOUNTIES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETCOUNTRYREGIONS]
PRINT N'Creating stored procedure [crt].[GETCOUNTRYREGIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETCOUNTRYREGIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETCOUNTRYREGIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETCOUNTRYREGIONS].';
END
GO


ALTER PROCEDURE [crt].[GETCOUNTRYREGIONS]
    @nvc_LanguageId     NVARCHAR(10)
AS
BEGIN

    DECLARE @tvp_CountryRegionIds [crt].STRINGIDTABLETYPE;

    SET NOCOUNT ON

    -- Select the countryId matching the criteria.
    INSERT INTO @tvp_CountryRegionIds
    SELECT DISTINCT
        LCNTRY.COUNTRYREGIONID
    FROM [ax].LOGISTICSADDRESSCOUNTRYREGION LCNTRY
    INNER JOIN [ax].LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION LTRANS ON LTRANS.COUNTRYREGIONID = LCNTRY.COUNTRYREGIONID
    WHERE (@nvc_LanguageId IS NULL OR LTRANS.LANGUAGEID = @nvc_LanguageId)

    -- Fetch the details of CountryRegions
    SELECT
        LCNTRY.COUNTRYREGIONID
        ,LCNTRY.ISOCODE
        ,LCNTRY.TIMEZONE
        ,LCNTRY.ADDRFORMAT AS ADDRESSFORMATID
        ,LFORMAT.NAME AS ADDRESSFORMATNAME
        ,LTRANS.SHORTNAME
        ,LTRANS.LONGNAME
        ,LTRANS.LANGUAGEID
    FROM @tvp_CountryRegionIds CRI
    INNER JOIN [ax].LOGISTICSADDRESSCOUNTRYREGION LCNTRY ON LCNTRY.COUNTRYREGIONID = CRI.STRINGID
    INNER JOIN [ax].LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION LTRANS ON LTRANS.COUNTRYREGIONID = LCNTRY.COUNTRYREGIONID
    INNER JOIN [ax].LOGISTICSADDRESSFORMATHEADING LFORMAT ON LFORMAT.ADDRFORMAT = LCNTRY.ADDRFORMAT
    WHERE (LTRANS.LANGUAGEID = @nvc_LanguageId OR @nvc_LanguageId IS NULL)

    -- Fetch the Address formatting information
SELECT
        LACR.COUNTRYREGIONID
       ,LAFL.ELEMENT
       ,CAST(LAFL.LINENUM AS INT) AS LINEINDEX
       ,LAFL.DATAENTRYONLY
    FROM @tvp_CountryRegionIds CRI
    INNER JOIN [ax].LOGISTICSADDRESSCOUNTRYREGION LACR ON LACR.COUNTRYREGIONID = CRI.STRINGID
    INNER JOIN [ax].LOGISTICSADDRESSFORMATHEADING LAFH ON LACR.ADDRFORMAT = LAFH.ADDRFORMAT
    INNER JOIN [ax].LOGISTICSADDRESSFORMATLINES LAFL ON LAFH.ADDRFORMAT = LAFL.ADDRFORMAT
    WHERE
        LAFL.INACTIVE = 0
    ORDER BY LINEINDEX ASC

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETCOUNTRYREGIONS]'
GO
-- End creating stored procedure [crt].[GETCOUNTRYREGIONS]


GRANT EXECUTE ON [crt].[GETCOUNTRYREGIONS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETCOUNTRYREGIONS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETCURRENTSHIFTNONSALETENDERS]
PRINT N'Creating stored procedure [crt].[GETCURRENTSHIFTNONSALETENDERS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETCURRENTSHIFTNONSALETENDERS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETCURRENTSHIFTNONSALETENDERS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETCURRENTSHIFTNONSALETENDERS].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
GETCURRENTSHIFTNONSALETENDERS gets the current shift's non sale tender transactions.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[GETCURRENTSHIFTNONSALETENDERS]
    @nvc_TransactionType    NVARCHAR(10),
@bi_ChannelId    BIGINT,
@nvc_TenderType    NVARCHAR(10),
@nvc_Terminal    NVARCHAR(10),
@bi_BatchId    BIGINT,
@nvc_TransactionId NVARCHAR(44)
AS
BEGIN

    SET NOCOUNT ON

SELECT 
CASE
WHEN RT.TYPE = 4 THEN (-1) * ISNULL(RPT.AMOUNTCUR, 0) -- For tender removal, amount is always negative in the balance, so we negate it
ELSE ISNULL(RPT.AMOUNTCUR, 0)                    -- For float entry and starting amount, amount is positive in the balance
END AS AMOUNT,
RT.TRANSACTIONID AS TRANSACTIONID,
RPT.CURRENCY,
RT.BATCHID AS SHIFTID,
RT.TYPE,
RT.BATCHID,
RT.BATCHTERMINALID,
RT.STAFF,
RT.TERMINAL,
RT.CHANNEL,
RT.DESCRIPTION,
RPT.TENDERTYPE,
RT.STORE
FROM [ax].RETAILTRANSACTIONTABLE RT 
INNER JOIN [ax].RETAILTRANSACTIONPAYMENTTRANS RPT 
ON RT.TRANSACTIONID = RPT.TRANSACTIONID AND RT.TYPE = @nvc_TransactionType 
AND RPT.TENDERTYPE = @nvc_TenderType AND RT.CHANNEL = @bi_ChannelId 
AND RT.TERMINAL= @nvc_Terminal 
AND RT.BATCHID = @bi_BatchId
AND (RT.TRANSACTIONID = @nvc_TransactionId OR (@nvc_TransactionId IS NULL OR @nvc_TransactionId = ''))

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETCURRENTSHIFTNONSALETENDERS]'
GO
-- End creating stored procedure [crt].[GETCURRENTSHIFTNONSALETENDERS]


GRANT EXECUTE ON [crt].[GETCURRENTSHIFTNONSALETENDERS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETDISTRICTS]
PRINT N'Creating stored procedure [crt].[GETDISTRICTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETDISTRICTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETDISTRICTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETDISTRICTS].';
END
GO


ALTER PROCEDURE [crt].[GETDISTRICTS]
    @CountryRegionId        NVARCHAR(10),
    @StateProvinceID        NVARCHAR(10) = NULL,
    @CountyId               NVARCHAR(10) = NULL,
    @City                   NVARCHAR(60) = NULL
AS
BEGIN

    SET NOCOUNT ON

DECLARE @StateProvinceIDIsNull BIT = CASE WHEN (@StateProvinceID IS NULL OR LEN(LTRIM(RTRIM(@StateProvinceID))) = 0) THEN 1 ELSE 0 END
DECLARE @CountyIdIsNull BIT = CASE WHEN (@CountyId IS NULL OR LEN(LTRIM(RTRIM(@CountyId))) = 0) THEN 1 ELSE 0 END
DECLARE @CityIsNull BIT = CASE WHEN (@City IS NULL OR LEN(LTRIM(RTRIM(@City))) = 0) THEN 1 ELSE 0 END

    SELECT
        LDIST.NAME AS DISTRICTNAME
       ,LDIST.DESCRIPTION
       ,LCITY.NAME AS CITYNAME
       ,LCITY.COUNTYID
       ,LCITY.STATEID
       ,LCITY.COUNTRYREGIONID
    FROM [ax].LOGISTICSADDRESSDISTRICT LDIST
    INNER JOIN [ax].LOGISTICSADDRESSSCITY LCITY ON LDIST.CITY = LCITY.RECID
    WHERE
        LCITY.COUNTRYREGIONID = @CountryRegionId
        AND (@StateProvinceIDIsNull = 1 OR LCITY.STATEID = @StateProvinceID)
        AND (@CountyIdIsNull = 1 OR LCITY.COUNTYID = @CountyId)
        AND (@CityIsNull = 1 OR LCITY.NAME = @City)

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETDISTRICTS]'
GO
-- End creating stored procedure [crt].[GETDISTRICTS]


GRANT EXECUTE ON [crt].[GETDISTRICTS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETDOWNLOADINGDATA]
PRINT N'Creating stored procedure [crt].[GETDOWNLOADINGDATA]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETDOWNLOADINGDATA]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETDOWNLOADINGDATA] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETDOWNLOADINGDATA].';
END
GO


ALTER PROCEDURE [crt].[GETDOWNLOADINGDATA]
    @tvp_QueryResultSettings [crt].[QUERYRESULTSETTINGSTYPE] READONLY,
    @bi_ChannelId       BIGINT,
    @vc_dataGroupName   VARCHAR(128)
AS
BEGIN

    SET NOCOUNT ON

    ---
    -- The following code sample demonstrates how to construct downloading dataset based on specified group name.
    --
    -- NOTE: it is always a good practice to get data from view(s) to avoid future migration pain.
    ---

    -- Convert the input parameter to upper case.
    DECLARE @convertedName VARCHAR(128)
    SET @convertedName = UPPER(@vc_dataGroupName)

    -- Return all data in 'PRICING' group
    IF (@convertedName = 'PRICING')
    BEGIN
        SELECT
            [RECID],
            [PRICEGROUP],
            [GROUPID],
            [CHANNELID]
        FROM [crt].PRICEGROUPSVIEW WITH(NOLOCK)

        SELECT
            [RECID],
            [SALESPRICEACCOUNTITEM],
            [SALESPRICEGROUPITEM],
            [SALESPRICEALLITEM],
            [SALESLINEACCOUNTITEM],
            [SALESLINEACCOUNTGROUP],
            [SALESLINEACCOUNTALL],
            [SALESLINEGROUPITEM],
            [SALESLINEGROUPGROUP],
            [SALESLINEGROUPALL],
            [SALESLINEALLITEM],
            [SALESLINEALLGROUP],
            [SALESLINEALLALL],
            [SALESMULTILNACCOUNTGROUP],
            [SALESMULTILNACCOUNTALL],
            [SALESMULTILNGROUPGROUP],
            [SALESMULTILNGROUPALL],
            [SALESMULTILNALLGROUP],
            [SALESMULTILNALLALL],
            [SALESENDACCOUNTALL],
            [SALESENDGROUPALL],
            [SALESENDALLALL]
        FROM [crt].PRICEPARAMETERSVIEW WITH(NOLOCK)

        RETURN
    END

    -- Return all data in 'TAX' group
    IF (@convertedName = 'TAX')
    BEGIN
        SELECT
            [RECID],
            [TAXCODE],
            [TAXFROMDATE],
            [TAXMAX],
            [TAXMIN],
            [TAXTODATE],
            [DATAAREAID],
            [ROWVERSION]
        FROM [ax].TAXCOLLECTLIMIT WITH(NOLOCK)

        SELECT
            [RECID],
            [SALESTAXFORMTYPES_IN],
            [TAXCODE],
            [TAXFROMDATE],
            [TAXLIMITMAX],
            [TAXLIMITMIN],
            [TAXREDUCTIONPCT_BR],
            [TAXTODATE],
            [TAXVALUE],
            [VATEXEMPTPCT],
            [DATAAREAID],
            [ROWVERSION]
        FROM [ax].TAXDATA WITH(NOLOCK)

        SELECT
            [RECID],
            [EXEMPTTAX],
            [TAXATIONCODETABLE_BR],
            [TAXCODE],
            [TAXGROUP],
            [USETAX],
            [DATAAREAID],
            [ROWVERSION]
        FROM [ax].TAXGROUPDATA WITH(NOLOCK)

        SELECT
            [RECID],
            [SEARCHFIELD1],
            [SEARCHFIELD2],
            [TAXGROUP],
            [TAXGROUPNAME],
            [TAXGROUPROUNDING],
            [TAXGROUPSETUP],
            [TAXPRINTDETAIL],
            [TAXREVERSEONCASHDISC],
            [DATAAREAID],
            [ROWVERSION]
        FROM [ax].TAXGROUPHEADING WITH(NOLOCK)

        SELECT
            [RECID],
            [ABATEMENTPERCENT_IN],
            [EXEMPTTAX_BR],
            [TAXATIONCODETABLE_BR],
            [TAXCODE],
            [TAXITEMGROUP],
            [WITHOUTTAXCREDIT_BR],
            [DATAAREAID],
            [ROWVERSION]
        FROM [ax].TAXONITEM WITH(NOLOCK)

        SELECT
            [RECID],
            [CUSTOMSPRACTICE_FI],
            [INCLUDEDTAX_BR],
            [NEGATIVETAX],
            [NOTEUSALESLIST],
            [PAYMENTTAXCODE],
            [PRINTCODE],
            [REPFIELDBASEINCOMING],
            [REPFIELDBASEINCOMINGCREDITNOTE],
            [REPFIELDBASEOUTGOING],
            [REPFIELDBASEOUTGOINGCREDITNOTE],
            [REPFIELDBASEUSETAX],
            [REPFIELDBASEUSETAXCREDITNOTE],
            [REPFIELDBASEUSETAXOFFSET],
            [REPFIELDBASEUSETAXOFFSETCREDITNOTE],
            [REPFIELDTAXFREEBUY],
            [REPFIELDTAXFREEBUYCREDITNOTE],
            [REPFIELDTAXFREESALES],
            [REPFIELDTAXFREESALESCREDITNOTE],
            [REPFIELDTAXINCOMING],
            [REPFIELDTAXINCOMINGCREDITNOTE],
            [REPFIELDTAXOUTGOING],
            [REPFIELDTAXOUTGOINGCREDITNOTE],
            [REPFIELDUSETAX],
            [REPFIELDUSETAXCREDITNOTE],
            [REPFIELDUSETAXOFFSET],
            [REPFIELDUSETAXOFFSETCREDITNOTE],
            [RETAINEDTAX_BR],
            [REVENUECODE_BR],
            [TAXACCOUNTGROUP],
            [TAXATIONCODETABLE_BR],
            [TAXBASE],
            [TAXBORDERNUMREQ_FI],
            [TAXCALCMETHOD],
            [TAXCODE],
            [TAXCOMPONENTTABLE_IN],
            [TAXCOUNTRYREGIONTYPE],
            [TAXCURRENCYCODE],
            [TAXINCLUDEINTAX],
            [TAXJURISDICTIONCODE],
            [TAXLIMITBASE],
            [TAXNAME],
            [TAXONTAX],
            [TAXPACKAGINGSORT],
            [TAXPACKAGINGTAX],
            [TAXPERIOD],
            [TAXPURCHASETAX],
            [TAXROUNDOFF],
            [TAXROUNDOFFTYPE],
            [TAXSUBSTITUTION_BR],
            [TAXTYPE_BR],
            [TAXTYPE_IN],
            [TAXTYPE_SG],
            [TAXUNIT],
            [TAXWRITESELECTION],
            [UNREALIZEDTAX],
            [DATAAREAID],
            [ROWVERSION]
        FROM [ax].TAXTABLE WITH(NOLOCK)

        RETURN
    END
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETDOWNLOADINGDATA]'
GO
-- End creating stored procedure [crt].[GETDOWNLOADINGDATA]


GRANT EXECUTE ON [crt].[GETDOWNLOADINGDATA] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETFROMZIPCODE]
PRINT N'Creating stored procedure [crt].[GETFROMZIPCODE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETFROMZIPCODE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETFROMZIPCODE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETFROMZIPCODE].';
END
GO


ALTER PROCEDURE [crt].[GETFROMZIPCODE]
    @CountryRegionId    NVARCHAR(10),
    @ZipCode            NVARCHAR(10)
AS
BEGIN
    SET NOCOUNT ON

    SELECT
        LZIP.ZIPCODE
       ,LZIP.STREETNAME
       ,LZIP.TIMEZONE
       ,LZIP.CITY AS CITYNAME
       ,LZIP.CITYALIAS
       ,LZIP.COUNTY AS COUNTYID
       ,LZIP.DISTRICTNAME
       ,LZIP.STATE AS STATEID
       ,LZIP.COUNTRYREGIONID
    FROM [ax].LOGISTICSADDRESSZIPCODE LZIP
    WHERE
        LZIP.COUNTRYREGIONID = @CountryRegionId
        AND LZIP.ZIPCODE = @ZipCode

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETFROMZIPCODE]'
GO
-- End creating stored procedure [crt].[GETFROMZIPCODE]


GRANT EXECUTE ON [crt].[GETFROMZIPCODE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPRODUCTCATALOGS]
PRINT N'Creating stored procedure [crt].[GETPRODUCTCATALOGS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTCATALOGS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPRODUCTCATALOGS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPRODUCTCATALOGS].';
END
GO


ALTER PROCEDURE [crt].[GETPRODUCTCATALOGS]
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE]    READONLY
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        rpcp.[PRODUCT],
        rpcp.[CATALOG]
    FROM [ax].RETAILPUBCATALOGPRODUCT rpcp
    INNER JOIN @tvp_ProductIds ids ON rpcp.[PRODUCT] = ids.RECID
    INNER JOIN [crt].GETPUBCATALOGCURRENT(@bi_ChannelId, @dt_ChannelDate) pccv ON pccv.[CATALOG] = rpcp.[CATALOG]

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPRODUCTCATALOGS]'
GO
-- End creating stored procedure [crt].[GETPRODUCTCATALOGS]


GRANT EXECUTE ON [crt].[GETPRODUCTCATALOGS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETPRODUCTCATALOGS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTTOTALAMOUNT]
PRINT N'Creating stored procedure [crt].[GETSHIFTTOTALAMOUNT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTTOTALAMOUNT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTTOTALAMOUNT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTTOTALAMOUNT].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTTOTALAMOUNT]
    @tvp_ShiftTotalAmountTempTable       [crt].[SHIFTTENDERAMOUNTTYPE]    READONLY
AS

BEGIN

-- [20] indicates declare starting amount type
-- [5] indicates float entry amount
-- [4] indicates tender removal amount
-- [7] indicates tender declare amount
-- [17] indicates safe drop amount
-- [16] indicates bank drop amount

WITH SHIFTSTORETOTALAMOUNT(TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, [20],[5],[4],[7],[17],[16])
AS
(
SELECT TENDERTYPEID, 
TENDERTYPENAME, 
CURRENCY, 
COUNTINGREQUIRED,
[20],
[5],
[4],
[7],
[17],
[16]
FROM
(
SELECT TENDERTYPEID, 
TENDERTYPENAME, 
CURRENCY, 
COUNTINGREQUIRED,
TENDEREDAMOUNT,
TRANSACTIONTYPE 
FROM @tvp_ShiftTotalAmountTempTable) AS D
PIVOT (SUM(TENDEREDAMOUNT) FOR D.TRANSACTIONTYPE IN ([20],[5],[4],[17],[16],[7])
) AS PVT
),
SHIFTTENDERTOTALAMOUNT (TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, [20],[5],[4],[7],[17],[16])
AS
(
SELECT TENDERTYPEID, 
TENDERTYPENAME, 
CURRENCY, 
COUNTINGREQUIRED,
[20],
[5],
[4],
[7],
[17],
[16]
FROM
(
SELECT TENDERTYPEID, 
TENDERTYPENAME, 
CURRENCY, 
COUNTINGREQUIRED,
TENDEREDAMOUNTCUR,
TRANSACTIONTYPE 
FROM @tvp_ShiftTotalAmountTempTable) AS D
PIVOT (SUM(TENDEREDAMOUNTCUR) FOR D.TRANSACTIONTYPE IN ([20],[5],[4],[17],[16],[7])
) AS PVT
)

SELECTss.TENDERTYPEID, 
ss.TENDERTYPENAME, 
ss.CURRENCY, 
ss.COUNTINGREQUIRED, 
-- Retrieve the store aggregated amount
ss.[20] AS STARTINGAMOUNT,
ss.[5] AS ADDTOTENDERAMOUNT,
ss.[4] AS REMOVETENDERAMOUNT,
ss.[7] AS DECLARETENDERAMOUNT,
ss.[17] AS SAFEDROPAMOUNT,
ss.[16] AS BANKDROPAMOUNT,
-- Retrieve the tendered currency aggregated amount
st.[20] AS STARTINGAMOUNTCUR,
st.[5] AS ADDTOTENDERAMOUNTCUR,
st.[4] AS REMOVETENDERAMOUNTCUR,
st.[7] AS DECLARETENDERAMOUNTCUR,
st.[17] AS SAFEDROPAMOUNTCUR,
st.[16] AS BANKDROPAMOUNTCUR

FROM SHIFTSTORETOTALAMOUNT AS ss 
JOIN SHIFTTENDERTOTALAMOUNT st 

ONss.TENDERTYPEID = st.TENDERTYPEID 
AND ss.TENDERTYPENAME = st.TENDERTYPENAME
AND ss.CURRENCY = st.CURRENCY
AND ss.COUNTINGREQUIRED = st.COUNTINGREQUIRED
END;



GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTTOTALAMOUNT]'
GO
-- End creating stored procedure [crt].[GETSHIFTTOTALAMOUNT]


GRANT EXECUTE ON [crt].[GETSHIFTTOTALAMOUNT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETACTIVESHIFT]
PRINT N'Creating stored procedure [crt].[GETACTIVESHIFT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETACTIVESHIFT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETACTIVESHIFT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETACTIVESHIFT].';
END
GO


ALTER PROCEDURE [crt].[GETACTIVESHIFT]
    @bi_ChannelId       BIGINT,
    @nvc_CurrentTerminalId     NVARCHAR(10),
    @nvc_UserId         NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;

    -- Select active shift identifier.
    SELECT [SHIFTID],
           [TERMINALID]
    FROM [crt].SHIFTSVIEW SHIFT
    WHERE SHIFT.CHANNEL = @bi_ChannelId AND
  (SHIFT.TERMINALID = @nvc_CurrentTerminalId OR SHIFT.CURRENTTERMINALID = @nvc_CurrentTerminalId) AND
          (SHIFT.STAFFID = @nvc_UserId OR SHIFT.CURRENTSTAFFID = @nvc_UserId) AND
          SHIFT.STATUS = 1 -- 1 means shift is open.

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;


exit_label:

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETACTIVESHIFT]'
GO
-- End creating stored procedure [crt].[GETACTIVESHIFT]


GRANT EXECUTE ON [crt].[GETACTIVESHIFT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLINKEDPRODUCTS]
PRINT N'Creating stored procedure [crt].[GETLINKEDPRODUCTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLINKEDPRODUCTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLINKEDPRODUCTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLINKEDPRODUCTS].';
END
GO


ALTER PROCEDURE [crt].[GETLINKEDPRODUCTS]
    @bi_ChannelId       BIGINT,
    @dt_ChannelDate     DATE,
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE]    READONLY
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @tvp_NormalizedProductIds crt.RECORDIDTABLETYPE
    DECLARE @tvp_LinkedProductIds crt.RECORDIDTABLETYPE

    -- Retrieve the data area for the current channel identifier.
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId

    -- Normalize all input identifiers. That means standalone, product master and variant
    -- identifiers all return the parent product as the lookup identifer.
    INSERT @tvp_NormalizedProductIds (RECID)
    SELECT DISTINCT
        COALESCE(pv2.PRODUCTMASTER, pv.PRODUCTMASTER, ids.RECID) AS 'LOOKUPID'
    FROM @tvp_ProductIds ids
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON [pv].RECID = [ids].RECID
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv2 ON [pv2].PRODUCTMASTER = [ids].RECID

    INSERT @tvp_LinkedProductIds (RECID)
    -- Retrieve incoming product identifiers (left side).
    SELECT RECID
    FROM @tvp_NormalizedProductIds
    UNION
    -- Retrieve linked product identifiers (right side).
    SELECT lit.PRODUCT
    FROM @tvp_NormalizedProductIds ids
    INNER JOIN [ax].INVENTTABLE it ON it.PRODUCT = ids.RECID AND it.DATAAREAID = @nvc_DataAreaId
    INNER JOIN [ax].RETAILINVENTLINKEDITEM rili ON rili.ITEMID = it.ITEMID and rili.DATAAREAID = it.DATAAREAID
    INNER JOIN [ax].INVENTTABLE lit ON lit.ITEMID = rili.LINKEDITEMID AND lit.DATAAREAID = rili.DATAAREAID

    -- Retrieve filtered identifiers by assortment.
    SELECT DISTINCT ap.PRODUCTID AS 'PRODUCT', lit.PRODUCT AS 'LINKEDPRODUCT', rili.QTY
    FROM [crt].GETASSORTEDPRODUCTS(@bi_ChannelId, @dt_ChannelDate, 0/*b_IsForwardLooking*/, 0/*b_SkipVariantExpansion*/, 1/*b_ProductIdsPassed*/, @tvp_LinkedProductIds) ap
    INNER JOIN [ax].RETAILINVENTLINKEDITEM rili ON rili.ITEMID = ap.ITEMID AND rili.DATAAREAID = @nvc_DataAreaId
    INNER JOIN [ax].INVENTTABLE lit ON lit.ITEMID = rili.LINKEDITEMID AND lit.DATAAREAID = rili.DATAAREAID
    WHERE ap.ISREMOTE = 0 -- Exclude remote products

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLINKEDPRODUCTS]'
GO
-- End creating stored procedure [crt].[GETLINKEDPRODUCTS]


GRANT EXECUTE ON [crt].[GETLINKEDPRODUCTS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETLINKEDPRODUCTS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETRETAILINCOMEEXPENSEACCOUNTS]
PRINT N'Creating stored procedure [crt].[GETRETAILINCOMEEXPENSEACCOUNTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETRETAILINCOMEEXPENSEACCOUNTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETRETAILINCOMEEXPENSEACCOUNTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETRETAILINCOMEEXPENSEACCOUNTS].';
END
GO


/**************************************************************************************************************************************
    GETRETAILINCOMEEXPENSEACCOUNTS retrieves the income and expense account numbers for the given storeId, dataareaid and accounttype.
***************************************************************************************************************************************/

ALTER PROCEDURE [crt].[GETRETAILINCOMEEXPENSEACCOUNTS]
    @nvc_StoreIdNVARCHAR(10),
    @nvc_DataAreaIdNVARCHAR(4),
@i_AccountTypeINT
AS
BEGIN

    SET NOCOUNT ON

    SELECT
        RIEA.ACCOUNTNUM AS 'AccountNumber'
   ,RIEA.NAME AS 'AccountName'
   ,RIEA.NAMEALIAS AS 'AccountNameAlias'
   ,RIEA.MESSAGELINE1
   ,RIEA.MESSAGELINE2
   ,RIEA.SLIPTEXT1
   ,RIEA.SLIPTEXT2
   ,RIEA.ACCOUNTTYPE
    FROM [ax].RETAILINCOMEEXPENSEACCOUNTTABLE RIEA
    WHERE
        RIEA.DATAAREAID=@nvc_DataAreaId AND RIEA.STOREID=@nvc_StoreId AND RIEA.ACCOUNTTYPE = @i_AccountType

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETRETAILINCOMEEXPENSEACCOUNTS]'
GO
-- End creating stored procedure [crt].[GETRETAILINCOMEEXPENSEACCOUNTS]


GRANT EXECUTE ON [crt].[GETRETAILINCOMEEXPENSEACCOUNTS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSTATEPROVINCES]
PRINT N'Creating stored procedure [crt].[GETSTATEPROVINCES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSTATEPROVINCES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSTATEPROVINCES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSTATEPROVINCES].';
END
GO


ALTER PROCEDURE [crt].[GETSTATEPROVINCES]
    @CountryRegionId    NVARCHAR(10)
AS
BEGIN

    SET NOCOUNT ON

    SELECT
        LCNTRY.COUNTRYREGIONID
       ,LSTATE.STATEID
       ,LSTATE.NAME AS STATENAME
       ,LSTATE.INTRASTATCODE
    FROM [ax].LOGISTICSADDRESSSTATE LSTATE
    INNER JOIN [ax].LOGISTICSADDRESSCOUNTRYREGION LCNTRY ON LSTATE.COUNTRYREGIONID = LCNTRY.COUNTRYREGIONID
    WHERE LSTATE.COUNTRYREGIONID = @CountryRegionId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSTATEPROVINCES]'
GO
-- End creating stored procedure [crt].[GETSTATEPROVINCES]


GRANT EXECUTE ON [crt].[GETSTATEPROVINCES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFT]
PRINT N'Creating stored procedure [crt].[GETSHIFT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFT].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFT]
    @tvp_QueryResultSettings [crt].[QUERYRESULTSETTINGSTYPE] READONLY,
    @bi_ChannelId       BIGINT,
    @nvc_TerminalId     NVARCHAR(10),
    @bi_ShiftId         BIGINT
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;

    -- Select the Shift record
    SELECT
        [SHIFTID],
        [CASHDRAWER],
        [CHANNEL],
        [CURRENTTERMINALID],
        [CLOSEDATE],
        [CLOSEDATETIMEUTC],
        [CLOSEDATETIMEUTCTZID],
        [CLOSETIME],
        [CUSTOMERSCOUNT],
        [DISCOUNTTOTAL],
        [LOGONSCOUNT],
        [NOSALECOUNT],
        [PAIDTOACCOUNTTOTAL],
        [RETURNSTOTAL],
        [ROUNDEDAMOUNTTOTAL],
        [SALESCOUNT],
        [SALESTOTAL],
        [STAFFID],
[CURRENTSTAFFID],
        [STARTDATE],
        [STARTDATETIMEUTC],
        [STARTDATETIMEUTCTZID],
        [STARTTIME],
        [STATUS],
        [STATUSDATETIMEUTC],
        [STOREID],
        [TAXTOTAL],
        [TERMINALID],
        [TRANSACTIONSCOUNT],
        [VOIDSCOUNT],
        [DATAAREAID],
        [ROWVERSION]
    FROM [crt].SHIFTSVIEW SHIFT
    WHERE SHIFT.CHANNEL = @bi_ChannelId AND
          SHIFT.TERMINALID = @nvc_TerminalId AND
          SHIFT.SHIFTID = @bi_ShiftId

    -- Select the Shift tender line records
    SELECT
        [ADDTOTENDERAMOUNT],
        [ADDTOTENDERAMOUNTCUR],
        [BANKDROPAMOUNT],
        [BANKDROPAMOUNTCUR],
        [CARDTYPEID],
        [CARDTYPENAME],
        [CHANGEAMOUNT],
        [CHANGEAMOUNTCUR],
        [CHANNEL],
        [COUNT],
        [COUNTINGREQUIRED],
        [CURRENCY],
        [DECLARETENDERAMOUNT],
        [DECLARETENDERAMOUNTCUR],
        [REMOVETENDERAMOUNT],
        [REMOVETENDERAMOUNTCUR],
        [SAFEDROPAMOUNT],
        [SAFEDROPAMOUNTCUR],
        [STARTINGAMOUNT],
        [STARTINGAMOUNTCUR],
        [STOREID],
        [SHIFTID],
        [TENDEREDAMOUNT],
        [TENDEREDAMOUNTCUR],
        [TENDERTYPEID],
        [TENDERTYPENAME],
        [TERMINALID],
        [DATAAREAID],
        [ROWVERSION]
    FROM [crt].SHIFTTENDERLINESVIEW SHIFTTENDERLINE
    WHERE SHIFTTENDERLINE.CHANNEL = @bi_ChannelId AND
          SHIFTTENDERLINE.TERMINALID = @nvc_TerminalId AND
          SHIFTTENDERLINE.SHIFTID = @bi_ShiftId

-- Select the income / expense account lines
SELECTINCOMEEXEPENSEACCOUNT,
ACCOUNTTYPE,
AMOUNT

FROM[crt].[SHIFTACCOUNTSVIEW] ACCOUNTLINE
WHERE ACCOUNTLINE.CHANNEL = @bi_ChannelId AND
          ACCOUNTLINE.TERMINALID = @nvc_TerminalId AND
          ACCOUNTLINE.SHIFTID = @bi_ShiftId

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;


exit_label:

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFT]'
GO
-- End creating stored procedure [crt].[GETSHIFT]


GRANT EXECUTE ON [crt].[GETSHIFT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTSALESDATA]
PRINT N'Creating stored procedure [crt].[GETSHIFTSALESDATA]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTSALESDATA]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTSALESDATA] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTSALESDATA].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTSALESDATA]
    @bi_ChannelIdbigint,
@nvc_TerminalIdnvarchar(10),
@bi_ShiftIdbigint,
@i_TaxInclusiveint
AS

BEGIN
SET NOCOUNT ON;

-- Calculate the retail transaction sales amount.
SELECT -1 * (SUM(SALES.SALESAMOUNT) + CASE WHEN @i_TaxInclusive = 1 THEN SUM(SALES.SALESTAXAMOUNT) ELSE 0 END) AS SALESTOTAL,
(SUM(SALES.RETURNAMOUNT) + CASE WHEN @i_TaxInclusive = 1 THEN SUM(SALES.RETURNTAXAMOUNT) ELSE 0 END) AS RETURNSTOTAL,
SUM(SALES.DISCAMOUNT) AS DISCOUNTTOTAL,
SUM(SALES.TAXAMOUNT) AS TAXTOTAL,
COUNT(SALES.TRANSACTIONID) AS SALESCOUNT

FROM[crt].[RETAILTRANSACTIONSALESAMOUNTSVIEW] SALES

WHERESALES.CHANNEL = @bi_ChannelId 
AND SALES.BATCHTERMINALID = @nvc_TerminalId
AND SALES.BATCHID = @bi_ShiftId
-- Filter by 0 normal transaction status (usually sales transactions) (or) customer order with posted status (19 - customer order and 2 - posted transactions ie. invoiced).
AND ((SALES.ENTRYSTATUS = 0) OR (SALES.TYPE = 19 AND SALES.ENTRYSTATUS = 2)) 

-- Select all the Payment done for the current shift.
DECLARE @tvp_ShiftTenderAmountTypeStartingAmount as [crt].[SHIFTTENDERAMOUNTTYPE]
DECLARE @tvp_ShiftTenderAmountTypeFloatEntry as [crt].[SHIFTTENDERAMOUNTTYPE]
DECLARE @tvp_ShiftTenderAmountTypeRemoveTender as [crt].[SHIFTTENDERAMOUNTTYPE]
DECLARE @tvp_ShiftTenderAmountTypeSafeDrop as [crt].[SHIFTTENDERAMOUNTTYPE]
DECLARE @tvp_ShiftTenderAmountTypeBankDrop as [crt].[SHIFTTENDERAMOUNTTYPE]
DECLARE @tvp_ShiftTenderAmountTypeTenderDeclaration as [crt].[SHIFTTENDERAMOUNTTYPE]

/************Transaction Type for different Daily Operations***************/
-- TransactionType = 20 for Declare Start Amount operation
-- TransactionType = 5 for Float Entry operation
-- TransactionType = 4 for Remove Tender operation
-- TransactionType = 17 for Safe drop operation
-- TransactionType = 16 for Bank drop operation
-- TransactionType = 7 for Tender declare operation
/************Transaction Type for different Daily Operations***************/

-- Get Starting shift tender total
INSERT INTO @tvp_ShiftTenderAmountTypeStartingAmount EXEC [crt].[GETSHIFTTENDERPAYMENTTRANS] @bi_ChannelId, @nvc_TerminalId, @bi_ShiftId, 20
-- Get Float entry shift tender total
INSERT INTO @tvp_ShiftTenderAmountTypeFloatEntry EXEC [crt].[GETSHIFTTENDERPAYMENTTRANS] @bi_ChannelId, @nvc_TerminalId, @bi_ShiftId, 5
-- Get tender removal shift tender total
INSERT INTO @tvp_ShiftTenderAmountTypeRemoveTender EXEC [crt].[GETSHIFTTENDERPAYMENTTRANS] @bi_ChannelId, @nvc_TerminalId, @bi_ShiftId, 4
-- Get safe drop shift tender total
INSERT INTO @tvp_ShiftTenderAmountTypeSafeDrop EXEC [crt].[GETSHIFTTENDERSAFEDROPTRANS] @bi_ChannelId, @nvc_TerminalId, @bi_ShiftId, 17
-- Get bank drop shift tender total
INSERT INTO @tvp_ShiftTenderAmountTypeBankDrop EXEC [crt].[GETSHIFTTENDERBANKDROPTRANS] @bi_ChannelId, @nvc_TerminalId, @bi_ShiftId, 16
-- Get tender declaration shift tender total
INSERT INTO @tvp_ShiftTenderAmountTypeTenderDeclaration EXEC [crt].[GETSHIFTTENDERDECLARATIONTRANS] @bi_ChannelId, @nvc_TerminalId, @bi_ShiftId, 7

DECLARE @tvp_ShiftTotalAmountTempTable as [crt].[SHIFTTENDERAMOUNTTYPE]

-- Select the transactions cummulatively.

INSERT INTO @tvp_ShiftTotalAmountTempTable 
SELECT TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, CAST(SUM(TENDEREDAMOUNT) AS DECIMAL(32, 16)) AS TENDEREDAMOUNT, CAST(SUM(TENDEREDAMOUNTCUR) AS DECIMAL(32, 16)) AS TENDEREDAMOUNTCUR, 20 AS TRANSACTIONTYPE FROM @tvp_ShiftTenderAmountTypeStartingAmount
GROUP BY TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED

INSERT INTO @tvp_ShiftTotalAmountTempTable 
SELECT TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, CAST(SUM(TENDEREDAMOUNT) AS DECIMAL(32, 16)) AS TENDEREDAMOUNT, CAST(SUM(TENDEREDAMOUNTCUR) AS DECIMAL(32, 16)) AS TENDEREDAMOUNTCUR, 5 AS TRANSACTIONTYPE FROM @tvp_ShiftTenderAmountTypeFloatEntry
GROUP BY TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED

INSERT INTO @tvp_ShiftTotalAmountTempTable 
SELECT TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, - CAST(SUM(TENDEREDAMOUNT) AS DECIMAL(32, 16)) AS TENDEREDAMOUNT, - CAST(SUM(TENDEREDAMOUNTCUR) AS DECIMAL(32, 16)) AS TENDEREDAMOUNTCUR, 4 AS TRANSACTIONTYPE FROM @tvp_ShiftTenderAmountTypeRemoveTender
GROUP BY TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED

INSERT INTO @tvp_ShiftTotalAmountTempTable 
SELECT TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, CAST(SUM(TENDEREDAMOUNT) AS DECIMAL(32, 16)) AS TENDEREDAMOUNT, CAST(SUM(TENDEREDAMOUNTCUR) AS DECIMAL(32, 16)) AS TENDEREDAMOUNTCUR, 17 AS TRANSACTIONTYPE FROM @tvp_ShiftTenderAmountTypeSafeDrop
GROUP BY TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED

INSERT INTO @tvp_ShiftTotalAmountTempTable 
SELECT TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, CAST(SUM(TENDEREDAMOUNT) AS DECIMAL(32, 16)) AS TENDEREDAMOUNT, CAST(SUM(TENDEREDAMOUNTCUR) AS DECIMAL(32, 16)) AS TENDEREDAMOUNTCUR, 16 AS TRANSACTIONTYPE FROM @tvp_ShiftTenderAmountTypeBankDrop
GROUP BY TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED

INSERT INTO @tvp_ShiftTotalAmountTempTable 
SELECT TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED, CAST(SUM(TENDEREDAMOUNT) AS DECIMAL(32, 16)) AS TENDEREDAMOUNT, CAST(SUM(TENDEREDAMOUNTCUR) AS DECIMAL(32, 16)) AS TENDEREDAMOUNTCUR, 7 AS TRANSACTIONTYPE FROM @tvp_ShiftTenderAmountTypeTenderDeclaration
GROUP BY TENDERTYPEID, TENDERTYPENAME, CURRENCY, COUNTINGREQUIRED

EXEC [crt].[GETSHIFTTOTALAMOUNT] @tvp_ShiftTotalAmountTempTable

-- Select the sum of Income expense account group by Account type and Income Expense Account number.
SELECTL.INCOMEEXEPENSEACCOUNT, 
L.ACCOUNTTYPE, 
SUM(L.AMOUNT) AS AMOUNT 

FROM[ax].[RETAILTRANSACTIONINCOMEEXPENSETRANS] AS L 
INNER JOIN [ax].[RETAILTRANSACTIONTABLE] AS H ON H.TRANSACTIONID = L.TRANSACTIONID 
AND H.CHANNEL = L.CHANNEL
AND H.TERMINAL = L.TERMINAL
AND H.DATAAREAID = L.DATAAREAID 

WHERE   H.CHANNEL = @bi_ChannelId 
AND H.BATCHTERMINALID = @nvc_TerminalId
AND H.BATCHID = @bi_ShiftId 
AND H.ENTRYSTATUS = 0 -- EntryStatus = Normal
AND L.TRANSACTIONSTATUS = 0 -- TransactionStatus = Normal
AND H.[TYPE] = 18 -- TransactionType = Income/ Expense
GROUP BY L.ACCOUNTTYPE, L.INCOMEEXEPENSEACCOUNT
ORDER BY L.INCOMEEXEPENSEACCOUNT

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTSALESDATA]'
GO
-- End creating stored procedure [crt].[GETSHIFTSALESDATA]


GRANT EXECUTE ON [crt].[GETSHIFTSALESDATA] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTTENDERBANKDROPTRANS]
PRINT N'Creating stored procedure [crt].[GETSHIFTTENDERBANKDROPTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTTENDERBANKDROPTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTTENDERBANKDROPTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTTENDERBANKDROPTRANS].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTTENDERBANKDROPTRANS]
    @bi_ChannelIdbigint,
@nvc_TerminalIdnvarchar(10),
@bi_ShiftIdbigint,
@i_TransactionTypeint
AS

BEGIN
SET NOCOUNT ON;

SELECTPAYMENT.TENDERTYPE AS TENDERTYPEID, 
TENDER.NAME AS TENDERTYPENAME,
PAYMENT.CURRENCY, 
TENDER.COUNTINGREQUIRED, 
PAYMENT.AMOUNTTENDERED AS TENDEREDAMOUNT, 
PAYMENT.AMOUNTCUR AS TENDEREDAMOUNTCUR,
TRANS.TYPE AS TRANSACTIONTYPE

FROM[ax].[RETAILTRANSACTIONBANKEDTENDERTRANS] PAYMENT

INNER JOIN[ax].[RETAILTRANSACTIONTABLE] AS TRANS
ON TRANS.TRANSACTIONID = PAYMENT.TRANSACTIONID 
AND TRANS.CHANNEL = PAYMENT.CHANNEL
AND TRANS.TERMINAL = PAYMENT.TERMINAL 
AND TRANS.DATAAREAID = PAYMENT.DATAAREAID 

INNER JOIN[ax].[RETAILSTORETENDERTYPETABLE] AS TENDER 
ON TENDER.TENDERTYPEID = PAYMENT.TENDERTYPE 
AND TENDER.DATAAREAID = PAYMENT.DATAAREAID 
AND TENDER.CHANNEL = PAYMENT.CHANNEL

INNER JOIN[ax].[RETAILSTORETABLE] AS ST 
ON ST.RECID = TENDER.CHANNEL 
AND ST.RECID = PAYMENT.CHANNEL

WHERETRANS.CHANNEL = @bi_ChannelId 
AND TRANS.TYPE = @i_TransactionType
AND TRANS.BATCHTERMINALID = @nvc_TerminalId
AND TRANS.BATCHID = @bi_ShiftId 
AND TRANSACTIONSTATUS = 0-- 0 indicates Transaction status is normal
AND (COUNTINGREQUIRED = 1 OR TAKENTOBANK = 1 OR TAKENTOSAFE = 1)
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTTENDERBANKDROPTRANS]'
GO
-- End creating stored procedure [crt].[GETSHIFTTENDERBANKDROPTRANS]


GRANT EXECUTE ON [crt].[GETSHIFTTENDERBANKDROPTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTTENDERDECLARATIONTRANS]
PRINT N'Creating stored procedure [crt].[GETSHIFTTENDERDECLARATIONTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTTENDERDECLARATIONTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTTENDERDECLARATIONTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTTENDERDECLARATIONTRANS].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTTENDERDECLARATIONTRANS]
    @bi_ChannelIdbigint,
@nvc_TerminalIdnvarchar(10),
@bi_ShiftIdbigint,
@i_TransactionTypeint
AS

BEGIN
SET NOCOUNT ON;

DECLARE @TENDERDECLARATIONCALCTYPE as INT 
SET @TENDERDECLARATIONCALCTYPE = [crt].[GETTENDERDECLARATIONCALCULATIONTYPE](@bi_ChannelId)

IF (@TENDERDECLARATIONCALCTYPE = 0) -- Last
BEGIN
SELECTTENDERDECLARATION.TENDERTYPE AS TENDERTYPEID, 
TENDER.NAME AS TENDERTYPENAME,
TENDERDECLARATION.CURRENCY, 
TENDER.COUNTINGREQUIRED, 
TENDERDECLARATION.AMOUNTTENDERED AS TENDEREDAMOUNT, 
TENDERDECLARATION.AMOUNTCUR AS TENDEREDAMOUNTCUR,
TRANS.TYPE AS TRANSACTIONTYPE

FROM[ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] TENDERDECLARATION

INNER JOIN[ax].[RETAILTRANSACTIONTABLE] AS TRANS
ON TRANS.TRANSACTIONID = TENDERDECLARATION.TRANSACTIONID 
AND TRANS.CHANNEL = TENDERDECLARATION.CHANNEL
AND TRANS.TERMINAL = TENDERDECLARATION.TERMINAL 
AND TRANS.DATAAREAID = TENDERDECLARATION.DATAAREAID 

INNER JOIN[ax].[RETAILSTORETENDERTYPETABLE] AS TENDER 
ON TENDER.TENDERTYPEID = TENDERDECLARATION.TENDERTYPE 
AND TENDER.DATAAREAID = TENDERDECLARATION.DATAAREAID 
AND TENDER.CHANNEL = TENDERDECLARATION.CHANNEL

INNER JOIN[ax].[RETAILSTORETABLE] AS ST 
ON ST.RECID = TENDER.CHANNEL 
AND ST.RECID = TENDERDECLARATION.CHANNEL

WHERETENDERDECLARATION.TRANSACTIONSTATUS = 0
AND (TENDER.COUNTINGREQUIRED = 1 OR TENDER.TAKENTOBANK = 1 OR TENDER.TAKENTOSAFE = 1)
AND TRANS.TRANSACTIONID = (
SELECTTOP 1 TTRANS.TRANSACTIONID
FROM[ax].[RETAILTRANSACTIONTABLE] TTRANS
WHERETTRANS.CHANNEL = @bi_ChannelId
ANDTTRANS.TYPE = @i_TransactionType
ANDTTRANS.BATCHTERMINALID = @nvc_TerminalId
ANDTTRANS.BATCHID = @bi_ShiftId
ORDER BY TTRANS.CREATEDDATETIME DESC)

END
ELSE IF (@TENDERDECLARATIONCALCTYPE = 1) -- Sum
BEGIN
SELECTTENDERDECLARATION.TENDERTYPE AS TENDERTYPEID, 
TENDER.NAME AS TENDERTYPENAME,
TENDERDECLARATION.CURRENCY, 
TENDER.COUNTINGREQUIRED, 
TENDERDECLARATION.AMOUNTTENDERED AS TENDEREDAMOUNT, 
TENDERDECLARATION.AMOUNTCUR AS TENDEREDAMOUNTCUR,
TRANS.TYPE AS TRANSACTIONTYPE

FROM[ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS] TENDERDECLARATION

INNER JOIN[ax].[RETAILTRANSACTIONTABLE] AS TRANS
ON TRANS.TRANSACTIONID = TENDERDECLARATION.TRANSACTIONID 
AND TRANS.CHANNEL = TENDERDECLARATION.CHANNEL
AND TRANS.TERMINAL = TENDERDECLARATION.TERMINAL 
AND TRANS.DATAAREAID = TENDERDECLARATION.DATAAREAID 

INNER JOIN[ax].[RETAILSTORETENDERTYPETABLE] AS TENDER 
ON TENDER.TENDERTYPEID = TENDERDECLARATION.TENDERTYPE 
AND TENDER.DATAAREAID = TENDERDECLARATION.DATAAREAID 
AND TENDER.CHANNEL = TENDERDECLARATION.CHANNEL

INNER JOIN[ax].[RETAILSTORETABLE] AS ST 
ON ST.RECID = TENDER.CHANNEL 
AND ST.RECID = TENDERDECLARATION.CHANNEL

WHERETRANS.CHANNEL = @bi_ChannelId 
AND TRANS.TYPE = @i_TransactionType
AND TRANS.BATCHTERMINALID = @nvc_TerminalId
AND TRANS.BATCHID = @bi_ShiftId 
AND TENDERDECLARATION.TRANSACTIONSTATUS = 0
AND (TENDER.COUNTINGREQUIRED = 1 OR TENDER.TAKENTOBANK = 1 OR TENDER.TAKENTOSAFE = 1)
END
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTTENDERDECLARATIONTRANS]'
GO
-- End creating stored procedure [crt].[GETSHIFTTENDERDECLARATIONTRANS]


GRANT EXECUTE ON [crt].[GETSHIFTTENDERDECLARATIONTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTTENDEREDAMOUNT]
PRINT N'Creating stored procedure [crt].[GETSHIFTTENDEREDAMOUNT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTTENDEREDAMOUNT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTTENDEREDAMOUNT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTTENDEREDAMOUNT].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTTENDEREDAMOUNT]
    @bi_ChannelIdbigint,
@nvc_TerminalIdnvarchar(10),
@bi_ShiftIdbigint
AS

BEGIN
SET NOCOUNT ON;

SELECTPAYMENT.TENDERTYPE AS TENDERTYPEID,
TENDER.NAME AS TENDERTYPENAME,
PAYMENT.CURRENCY AS CURRENCY,
TENDER.COUNTINGREQUIRED,
PAYMENT.CHANGELINE,
SUM(PAYMENT.AMOUNTTENDERED) AS TENDEREDAMOUNT,
SUM(PAYMENT.AMOUNTCUR) AS TENDEREDAMOUNTCUR,
COUNT(*) AS COUNT

FROM[ax].[RETAILTRANSACTIONPAYMENTTRANS] AS PAYMENT

INNER JOIN[ax].[RETAILTRANSACTIONTABLE] AS TRANS
ON TRANS.TRANSACTIONID = PAYMENT.TRANSACTIONID
AND TRANS.CHANNEL = PAYMENT.CHANNEL
AND TRANS.TERMINAL = PAYMENT.TERMINAL
AND TRANS.DATAAREAID = PAYMENT.DATAAREAID

INNER JOIN[ax].[RETAILSTORETENDERTYPETABLE] AS TENDER 
ON TENDER.TENDERTYPEID = PAYMENT.TENDERTYPE 
AND TENDER.DATAAREAID = PAYMENT.DATAAREAID
AND TENDER.CHANNEL = PAYMENT.CHANNEL

INNER JOIN[ax].[RETAILSTORETABLE] AS ST
ON ST.RECID = TENDER.CHANNEL
AND ST.STORENUMBER = PAYMENT.STORE

WHERETRANS.CHANNEL = @bi_ChannelId 
AND TRANS.BATCHTERMINALID = @nvc_TerminalId 
AND TRANS.BATCHID = @bi_ShiftId
AND PAYMENT.TRANSACTIONSTATUS = 0 -- Transaction status is normal
AND (TRANS.TYPE = 2 OR TRANS.TYPE = 3 OR TRANS.TYPE = 15 OR TRANS.TYPE = 14 OR TRANS.TYPE = 19 OR TRANS.TYPE = 18) -- Transaction type Sales, Payment, SalesInvoice, SalesOrder, CustomerOrder, IncomeExpense resp
GROUP BY PAYMENT.TENDERTYPE, TENDER.NAME, PAYMENT.CURRENCY, PAYMENT.CHANGELINE, TENDER.COUNTINGREQUIRED

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTTENDEREDAMOUNT]'
GO
-- End creating stored procedure [crt].[GETSHIFTTENDEREDAMOUNT]


GRANT EXECUTE ON [crt].[GETSHIFTTENDEREDAMOUNT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTTENDERPAYMENTTRANS]
PRINT N'Creating stored procedure [crt].[GETSHIFTTENDERPAYMENTTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTTENDERPAYMENTTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTTENDERPAYMENTTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTTENDERPAYMENTTRANS].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTTENDERPAYMENTTRANS]
    @bi_ChannelIdbigint,
@nvc_TerminalIdnvarchar(10),
@bi_ShiftIdbigint,
@i_TransactionTypeint
AS

BEGIN
SET NOCOUNT ON;

SELECTPAYMENT.TENDERTYPE AS TENDERTYPEID, 
TENDER.NAME AS TENDERTYPENAME,
PAYMENT.CURRENCY, 
TENDER.COUNTINGREQUIRED, 
PAYMENT.AMOUNTTENDERED AS TENDEREDAMOUNT, 
PAYMENT.AMOUNTCUR AS TENDEREDAMOUNTCUR,
TRANS.TYPE AS TRANSACTIONTYPE

FROM[ax].[RETAILTRANSACTIONPAYMENTTRANS] PAYMENT
INNER JOIN[ax].[RETAILTRANSACTIONTABLE] AS TRANS
ON TRANS.TRANSACTIONID = PAYMENT.TRANSACTIONID 
AND TRANS.CHANNEL = PAYMENT.CHANNEL
AND TRANS.TERMINAL = PAYMENT.TERMINAL 
AND TRANS.DATAAREAID = PAYMENT.DATAAREAID 

INNER JOIN[ax].[RETAILSTORETENDERTYPETABLE] AS TENDER 
ON TENDER.TENDERTYPEID = PAYMENT.TENDERTYPE 
AND TENDER.DATAAREAID = PAYMENT.DATAAREAID AND 
TENDER.CHANNEL = PAYMENT.CHANNEL

INNER JOIN[ax].[RETAILSTORETABLE] AS ST 
ON ST.RECID = TENDER.CHANNEL 
AND ST.RECID = PAYMENT.CHANNEL

WHERETRANS.CHANNEL = @bi_ChannelId 
AND TRANS.TYPE = @i_TransactionType
AND TRANS.BATCHTERMINALID = @nvc_TerminalId
AND TRANS.BATCHID = @bi_ShiftId 
AND PAYMENT.TRANSACTIONSTATUS = 0-- Transaction status is normal
AND (TENDER.COUNTINGREQUIRED = 1 OR TENDER.TAKENTOBANK = 1 OR TENDER.TAKENTOSAFE = 1)
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTTENDERPAYMENTTRANS]'
GO
-- End creating stored procedure [crt].[GETSHIFTTENDERPAYMENTTRANS]


GRANT EXECUTE ON [crt].[GETSHIFTTENDERPAYMENTTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTTENDERSAFEDROPTRANS]
PRINT N'Creating stored procedure [crt].[GETSHIFTTENDERSAFEDROPTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTTENDERSAFEDROPTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTTENDERSAFEDROPTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTTENDERSAFEDROPTRANS].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTTENDERSAFEDROPTRANS]
    @bi_ChannelIdbigint,
@nvc_TerminalIdnvarchar(10),
@bi_ShiftIdbigint,
@i_TransactionTypeint
AS

BEGIN
SET NOCOUNT ON;

SELECTPAYMENT.TENDERTYPE AS TENDERTYPEID, 
TENDER.NAME AS TENDERTYPENAME,
PAYMENT.CURRENCY, 
TENDER.COUNTINGREQUIRED, 
PAYMENT.AMOUNTTENDERED AS TENDEREDAMOUNT, 
PAYMENT.AMOUNTCUR AS TENDEREDAMOUNTCUR,
TRANS.TYPE AS TRANSACTIONTYPE

FROM[ax].[RETAILTRANSACTIONSAFETENDERTRANS] PAYMENT
INNER JOIN [ax].[RETAILTRANSACTIONTABLE] AS TRANS
ON TRANS.TRANSACTIONID = PAYMENT.TRANSACTIONID 
AND TRANS.CHANNEL = PAYMENT.CHANNEL
AND TRANS.TERMINAL = PAYMENT.TERMINAL 
AND TRANS.DATAAREAID = PAYMENT.DATAAREAID 

INNER JOIN[ax].[RETAILSTORETENDERTYPETABLE] AS TENDER ON 
TENDER.TENDERTYPEID = PAYMENT.TENDERTYPE 
AND TENDER.DATAAREAID = PAYMENT.DATAAREAID 
AND TENDER.CHANNEL = PAYMENT.CHANNEL

INNER JOIN[ax].[RETAILSTORETABLE] AS ST ON 
ST.RECID = TENDER.CHANNEL 
AND ST.RECID = PAYMENT.CHANNEL

WHERETRANS.CHANNEL = @bi_ChannelId 
AND TRANS.TYPE = @i_TransactionType
AND TRANS.BATCHTERMINALID = @nvc_TerminalId
AND TRANS.BATCHID = @bi_ShiftId 
AND TRANSACTIONSTATUS = 0 -- 0 indicates Transaction status is normal
AND (COUNTINGREQUIRED = 1 OR TAKENTOBANK = 1 OR TAKENTOSAFE = 1)
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTTENDERSAFEDROPTRANS]'
GO
-- End creating stored procedure [crt].[GETSHIFTTENDERSAFEDROPTRANS]


GRANT EXECUTE ON [crt].[GETSHIFTTENDERSAFEDROPTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSHIFTRANSACTIONS]
PRINT N'Creating stored procedure [crt].[GETSHIFTRANSACTIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSHIFTRANSACTIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSHIFTRANSACTIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSHIFTRANSACTIONS].';
END
GO


ALTER PROCEDURE [crt].[GETSHIFTRANSACTIONS]
@bi_ChannelIdbigint,
@nvc_TerminalIdnvarchar(10),
@bi_ShiftIdbigint
AS

BEGIN
SET NOCOUNT ON;

WITH RETAILTRANS (VOIDTRANSACTION, LOGONTRANSACTION, NOSALETRANSACTION, CUSTOMERTRANSACTION, TRANSACTIONS, CREATEDDATETIME, SALESPAYMENTDIFFERENCE, STORE, BATCHID, BATCHTERMINALID)
AS
(
SELECT(CASE WHEN RT.ENTRYSTATUS = 1 THEN TRANSACTIONID ELSE NULL END) AS VOIDTRANSACTION,-- 1 indicates Voided Transaction status
(CASE WHEN RT.TYPE = 1 THEN TRANSACTIONID ELSE NULL END) AS LOGONTRANSACTION,-- 1 indicates LogOn Transaction Type
(CASE WHEN RT.TYPE = 9 THEN TRANSACTIONID ELSE NULL END) AS NOSALETRANSACTION,-- 9 indicates Open Drawer Transaction Type
(CASE WHEN (RT.ENTRYSTATUS = 2 OR (RT.TYPE = 19 AND RT.ENTRYSTATUS = 2)) AND RT.CUSTACCOUNT <> '' THEN TRANSACTIONID ELSE NULL END) AS CUSTOMERTRANSACTION,-- 2 indicates Posted Transaction status, 19 - indicates Customer order type
RT.TRANSACTIONID AS TRANSACTIONS,
RT.CREATEDDATETIME,
RT.SALESPAYMENTDIFFERENCE,
RT.STORE,
RT.BATCHID,
RT.BATCHTERMINALID

FROM[ax].[RETAILTRANSACTIONTABLE] RT 

WHERERT.CHANNEL = @bi_ChannelId
--AND RT.BATCHTERMINALID = @nvc_TerminalId <TFS Bug: 848110>
AND RT.BATCHID = @bi_ShiftId 
)

SELECTCOUNT(VOIDTRANSACTION) AS VOIDSCOUNT, 
COUNT(LOGONTRANSACTION) AS LOGONSCOUNT, 
COUNT(NOSALETRANSACTION) AS NOSALECOUNT, 
COUNT(CUSTOMERTRANSACTION) AS CUSTOMERSCOUNT, 
COUNT(TRANSACTIONS) AS TRANSACTIONSCOUNT, 
MIN(CREATEDDATETIME) AS STARTDATETIMEUTC, 
SUM(SALESPAYMENTDIFFERENCE) AS ROUNDEDAMOUNTTOTAL

FROMRETAILTRANS;

END;

GO
PRINT N'Finished creating stored procedure [crt].[GETSHIFTRANSACTIONS]'
GO
-- End creating stored procedure [crt].[GETSHIFTRANSACTIONS]


GRANT EXECUTE ON [crt].[GETSHIFTRANSACTIONS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSTORESBYEMPLOYEE]
PRINT N'Creating stored procedure [crt].[GETSTORESBYEMPLOYEE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSTORESBYEMPLOYEE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSTORESBYEMPLOYEE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSTORESBYEMPLOYEE].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
 GETSTORESBYEMPLOYEE gets the stores for the given employee personnel number from the Address book.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[GETSTORESBYEMPLOYEE]
@nvc_PersonnelNumberNVARCHAR(25)
AS
BEGIN

SET NOCOUNT ON

SELECT rst.STORENUMBER,
       dpt.NAME AS 'STORENAME',
       pav.LOCATIONNAME,
       pav.ADDRESS AS 'STOREADDRESS'
FROM [ax].[DIRADDRESSBOOKPARTY] dabp
    INNER JOIN [ax].[HCMWORKER] hw ON dabp.PARTY = hw.PERSON
    INNER JOIN [ax].[RETAILSTOREADDRESSBOOK] rsab on dabp.ADDRESSBOOK = rsab.ADDRESSBOOK
    INNER JOIN [ax].[RETAILSTORETABLE] rst ON rsab.STORERECID = rst.RECID
    INNER JOIN [ax].[RETAILCHANNELTABLE] rct ON rst.RECID = rct.RECID
    INNER JOIN [ax].[DIRPARTYTABLE] dpt ON rct.OMOPERATINGUNITID = dpt.RECID
    INNER JOIN [crt].[POSTALADDRESSESVIEW] pav ON rct.OMOPERATINGUNITID = pav.PARTY
WHERE rsab.ADDRESSBOOKTYPE = 1 AND pav.ISPRIMARY = 1 AND hw.PERSONNELNUMBER = @nvc_PersonnelNumber 
ORDER BY rst.STORENUMBER

END


GO
PRINT N'Finished creating stored procedure [crt].[GETSTORESBYEMPLOYEE]'
GO
-- End creating stored procedure [crt].[GETSTORESBYEMPLOYEE]


GRANT EXECUTE ON [crt].[GETSTORESBYEMPLOYEE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETTAXREGIME]
PRINT N'Creating stored procedure [crt].[GETTAXREGIME]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETTAXREGIME]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETTAXREGIME] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETTAXREGIME].';
END
GO


ALTER PROCEDURE [crt].[GETTAXREGIME]
    @nvc_COUNTRYREGIONID        NVARCHAR(10),
    @nvc_STATEID                NVARCHAR(10) = NULL,
    @nvc_COUNTYID               NVARCHAR(10) = NULL,
    @nvc_CITY                   NVARCHAR(60) = NULL,
    @nvc_DISTRICT               NVARCHAR(60) = NULL,
    @nvc_ZIPCODE                 NVARCHAR(10) = NULL
AS
BEGIN
    SET NOCOUNT ON

DECLARE @nvc_COUNTRYREGIONNORMALIZED       NVARCHAR(10)
    SET  @nvc_COUNTRYREGIONNORMALIZED = N''

    -- CountryId is mandatory
    IF (@nvc_COUNTRYREGIONID IS NULL)
    BEGIN
        RAISERROR (N'COUNTRY/REGIONID MANDATORY', 16, 1)
        RETURN;
    END

-- country region Id can be in either format. First need to normalize
IF EXISTS(SELECT  1 FROM [ax].LOGISTICSADDRESSCOUNTRYREGION LCNTRY  WITH(NOLOCK) 
    WHERE COUNTRYREGIONID = @nvc_COUNTRYREGIONID)
    BEGIN
       -- three letter case
   SELECT @nvc_COUNTRYREGIONNORMALIZED = @nvc_COUNTRYREGIONID
    END
    ELSE 
    BEGIN
   -- two letter case
   SELECT  @nvc_COUNTRYREGIONNORMALIZED = LCNTRY.COUNTRYREGIONID 
FROM [ax].LOGISTICSADDRESSCOUNTRYREGION LCNTRY  WHERE ISOCODE = @nvc_COUNTRYREGIONID
    END

    -- For Optional Columns, there is three possible state we can run into
    -- 1) a value is passed in (like @STATEPROVINCEID = 'WA' )--> For this case, only match is possible when @STATEPROVINCEID = STATEPROVINCEID
    -- 2) a value is NOT passed in (like @STATEPROVINCEID = NULL )--> For this case, we do have two sub-cases
    -- 2a) @STATEPROVINCEID = NULL and STATEPROVINCEID is also NULL --> This is a match
    -- 2b) @STATEPROVINCEID = NULL but STATEPROVINCEID != NULL, i.e. has a value in it --> This is no match. The data in the table is more complete than what it is passed
    SELECT
        RDFT.COUNTRYREGIONID,
        RDFT.STATEID,
        RDFT.COUNTYID,
        LCTY.NAME AS CITYNAME,
        LDST.NAME AS DISTRICTNAME,
        LZIP.ZIPCODE AS ZIPCODE,
        RDFT.TAXGROUPHEADING AS 'TAXGROUPNAME'
    FROM [ax].RETAILTAXFILTERS RDFT
    LEFT OUTER JOIN [ax].LOGISTICSADDRESSSCITY LCTY ON RDFT.CITY = LCTY.RECID
    LEFT OUTER JOIN [ax].LOGISTICSADDRESSDISTRICT LDST ON RDFT.DISTRICT = LDST.RECID
    LEFT OUTER JOIN [ax].LOGISTICSADDRESSZIPCODE LZIP ON RDFT.ZIPCODE = LZIP.RECID
    WHERE
        RDFT.COUNTRYREGIONID = @nvc_COUNTRYREGIONNORMALIZED  -- this is mandatory
        AND (RDFT.STATEID = @nvc_STATEID OR (@nvc_STATEID IS NULL AND RDFT.STATEID = ''))
        AND (RDFT.COUNTYID = @nvc_COUNTYID OR (@nvc_COUNTYID IS NULL AND RDFT.COUNTYID = ''))
        AND (LCTY.NAME = @nvc_CITY OR ((@nvc_CITY IS NULL) AND RDFT.CITY = 0))
        AND (LDST.NAME = @nvc_DISTRICT OR ((@nvc_DISTRICT IS NULL)AND RDFT.DISTRICT = 0))
        AND (LZIP.ZIPCODE = @nvc_ZIPCODE  OR ((@nvc_ZIPCODE  IS NULL ) AND RDFT.ZIPCODE = 0))
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETTAXREGIME]'
GO
-- End creating stored procedure [crt].[GETTAXREGIME]


GRANT EXECUTE ON [crt].[GETTAXREGIME] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETUNITOFMEASUREOPTIONS]
PRINT N'Creating stored procedure [crt].[GETUNITOFMEASUREOPTIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETUNITOFMEASUREOPTIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETUNITOFMEASUREOPTIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETUNITOFMEASUREOPTIONS].';
END
GO


-- Gets the unit of measure options for the given product identifiers.
ALTER PROCEDURE [crt].[GETUNITOFMEASUREOPTIONS]
    @bi_ChannelId       BIGINT,
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE]    READONLY
AS
BEGIN
    SET NOCOUNT ON;

    -- Get the data area for the specified channel identifier.
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId;

    -- Retrieves the unit of measure conversions.
    SELECT
        tvppi.RECID             AS PRODUCT,
        it.ITEMID               AS ITEMID,
        uomc.FROMUNITOFMEASURE  AS FROMUNITID,
        uom1.SYMBOL             AS FROMUOMSYMBOL,
        uomc.TOUNITOFMEASURE    AS TOUNITID,
        uom2.SYMBOL             AS TOUOMSYMBOL
    FROM [ax].UNITOFMEASURECONVERSION UOMC
    INNER JOIN [ax].UNITOFMEASURE uom1 ON uom1.RECID = uomc.FROMUNITOFMEASURE
    INNER JOIN [ax].UNITOFMEASURE uom2 ON uom2.RECID = uomc.TOUNITOFMEASURE
    INNER JOIN [ax].INVENTTABLE it ON (it.PRODUCT = uomc.PRODUCT AND it.DATAAREAID = @nvc_DataAreaId) OR uomc.PRODUCT = 0
    INNER JOIN [ax].INVENTTABLEMODULE itm ON (itm.ITEMID = it.ITEMID AND itm.MODULETYPE = 2 AND itm.DATAAREAID = @nvc_DataAreaId)
        AND (uom1.SYMBOL = itm.UNITID OR uom2.SYMBOL = itm.UNITID)
    INNER JOIN @tvp_ProductIds tvppi ON tvppi.RECID = it.PRODUCT

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETUNITOFMEASUREOPTIONS]'
GO
-- End creating stored procedure [crt].[GETUNITOFMEASUREOPTIONS]


GRANT EXECUTE ON [crt].[GETUNITOFMEASUREOPTIONS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETZIPCODES]
PRINT N'Creating stored procedure [crt].[GETZIPCODES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETZIPCODES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETZIPCODES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETZIPCODES].';
END
GO


ALTER PROCEDURE [crt].[GETZIPCODES]
    @CountryRegionId    NVARCHAR(10),
    @StateProvinceID    NVARCHAR(10) = NULL,
    @CountyId           NVARCHAR(10) = NULL,
    @City               NVARCHAR(60) = NULL,
    @District           NVARCHAR(60) = NULL
AS
BEGIN

    SET NOCOUNT ON

    DECLARE @StateProvinceIDIsNull BIT = CASE WHEN (@StateProvinceID IS NULL OR LEN(LTRIM(RTRIM(@StateProvinceID))) = 0) THEN 1 ELSE 0 END
DECLARE @CountyIdIsNull BIT = CASE WHEN (@CountyId IS NULL OR LEN(LTRIM(RTRIM(@CountyId))) = 0) THEN 1 ELSE 0 END
DECLARE @CityIsNull BIT = CASE WHEN (@City IS NULL OR LEN(LTRIM(RTRIM(@City))) = 0) THEN 1 ELSE 0 END
DECLARE @DistrictIsNull BIT = CASE WHEN (@District IS NULL OR LEN(LTRIM(RTRIM(@District))) = 0) THEN 1 ELSE 0 END

    SELECT
        LZIP.ZIPCODE
       ,LZIP.STREETNAME
       ,LZIP.TIMEZONE
       ,LZIP.CITY AS CITYNAME
       ,LZIP.CITYALIAS
       ,LZIP.COUNTY AS COUNTYID
       ,LZIP.DISTRICTNAME
       ,LZIP.STATE AS STATEID
       ,LZIP.COUNTRYREGIONID
    FROM [ax].LOGISTICSADDRESSZIPCODE LZIP
    WHERE
        LZIP.COUNTRYREGIONID = @CountryRegionId
        AND (@StateProvinceIDIsNull = 1 OR LZIP.STATE = @StateProvinceID)
        AND (@CountyIdIsNull = 1 OR LZIP.COUNTY = @CountyId)
        AND (@CityIsNull = 1 OR LZIP.CITY = @City)
        AND (@DistrictIsNull = 1 OR LZIP.DISTRICTNAME = @District)

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETZIPCODES]'
GO
-- End creating stored procedure [crt].[GETZIPCODES]


GRANT EXECUTE ON [crt].[GETZIPCODES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[SAVECHANNELPROPERTY]
PRINT N'Creating stored procedure [crt].[SAVECHANNELPROPERTY]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVECHANNELPROPERTY]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVECHANNELPROPERTY] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVECHANNELPROPERTY].';
END
GO


ALTER PROCEDURE [crt].[SAVECHANNELPROPERTY]
    @bi_ChannelId       BIGINT,
    @nvc_PropertyName   NVARCHAR(128),
    @nvc_PropertyValue  NVARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON

    IF NOT EXISTS
    (
        SELECT CHANNEL, NAME
        FROM [crt].[RETAILCHANNELPROPERTIES]
        WHERE
            CHANNEL = @bi_ChannelId AND
            NAME = @nvc_PropertyName
    )
    BEGIN
        INSERT INTO [crt].[RETAILCHANNELPROPERTIES]
        (CHANNEL, NAME, VALUE)
        VALUES (@bi_ChannelId, @nvc_PropertyName, @nvc_PropertyValue)
    END
    ELSE
    BEGIN
        UPDATE [crt].[RETAILCHANNELPROPERTIES]
        SET VALUE = @nvc_PropertyValue
        WHERE
            CHANNEL = @bi_ChannelId AND
            NAME = @nvc_PropertyName
    END
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVECHANNELPROPERTY]'
GO
-- End creating stored procedure [crt].[SAVECHANNELPROPERTY]


GRANT EXECUTE ON [crt].[SAVECHANNELPROPERTY] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[SAVECHANNELPROPERTY] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[UPDATEONLINECHANNELPUBLISHSTATUS]
PRINT N'Creating stored procedure [crt].[UPDATEONLINECHANNELPUBLISHSTATUS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[UPDATEONLINECHANNELPUBLISHSTATUS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[UPDATEONLINECHANNELPUBLISHSTATUS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[UPDATEONLINECHANNELPUBLISHSTATUS].';
END
GO


ALTER PROCEDURE [crt].[UPDATEONLINECHANNELPUBLISHSTATUS]
    @bi_ChannelId               BIGINT,
    @i_PublishStatus            INT,
    @nvc_PublishStatusMessage   NVARCHAR(max) = NULL
AS
BEGIN
    SET NOCOUNT ON

    UPDATE [ax].[RETAILONLINECHANNELPUBLISHSTATUS]
    SET
        PUBLISHSTATUS = @i_PublishStatus,
        PUBLISHSTATUSMESSAGE = @nvc_PublishStatusMessage
    WHERE
        ONLINECHANNEL = @bi_ChannelId
END;


GO
PRINT N'Finished creating stored procedure [crt].[UPDATEONLINECHANNELPUBLISHSTATUS]'
GO
-- End creating stored procedure [crt].[UPDATEONLINECHANNELPUBLISHSTATUS]


GRANT EXECUTE ON [crt].[UPDATEONLINECHANNELPUBLISHSTATUS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[UPDATEONLINECHANNELPUBLISHSTATUS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[UPDATERETURNQUANTITY]
PRINT N'Creating stored procedure [crt].[UPDATERETURNQUANTITY]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[UPDATERETURNQUANTITY]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[UPDATERETURNQUANTITY] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[UPDATERETURNQUANTITY].';
END
GO


ALTER PROCEDURE [crt].[UPDATERETURNQUANTITY]
    @bi_ChannelId       BIGINT,
    @nvc_StoreNumber    NVARCHAR(10),
    @nvc_TerminalId     NVARCHAR(10),
    @nvc_TransactionId  NVARCHAR(44),
    @nu_LineNumber      NUMERIC(32,16),
    @nu_Quantity        NUMERIC(32,16)
AS
BEGIN
    SET NOCOUNT ON

    UPDATE [ax].[RETAILTRANSACTIONSALESTRANS]
    SET
        RETURNQTY = RETURNQTY + @nu_Quantity
    WHERE
        (CHANNEL = @bi_ChannelId OR STORE = @nvc_StoreNumber)
        AND TERMINALID = @nvc_TerminalId
        AND TRANSACTIONID = @nvc_TransactionId
        AND LINENUM = @nu_LineNumber;
END;


GO
PRINT N'Finished creating stored procedure [crt].[UPDATERETURNQUANTITY]'
GO
-- End creating stored procedure [crt].[UPDATERETURNQUANTITY]


GRANT EXECUTE ON [crt].[UPDATERETURNQUANTITY] TO [UsersRole];
GO

-- Creating stored procedure [crt].[UPDATESHIFTSTAGING]
PRINT N'Creating stored procedure [crt].[UPDATESHIFTSTAGING]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[UPDATESHIFTSTAGING]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[UPDATESHIFTSTAGING] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[UPDATESHIFTSTAGING].';
END
GO


ALTER PROCEDURE [crt].[UPDATESHIFTSTAGING]
    @TVP_SHIFTTABLETYPE     [crt].[SHIFTTABLETYPE] READONLY,
    @RV_ROWVERSION          ROWVERSION OUTPUT

AS
BEGIN
    SET NOCOUNT ON


     DECLARE @i_ReturnCode           INT;
     DECLARE @i_RowCount             INT;
     DECLARE @i_Error                INT;
     DECLARE @tvp_RowVersion         TABLE ([ROWVERSION] BINARY(8));

     -- UPDATE THE RETAILSHIFTSTAGINGTABLE
     UPDATE [crt].RETAILSHIFTSTAGINGTABLE
     SET
        STAFFID                = S.STAFFID,
        CURRENTSTAFFID         = S.CURRENTSTAFFID,
        [STATUS]               = S.[STATUS],
        CURRENTTERMINALID      = S.CURRENTTERMINALID,
        STATUSDATETIMEUTC      = S.STATUSDATETIMEUTC,
        CASHDRAWER             = S.CASHDRAWER
     OUTPUT INSERTED.[ROWVERSION] INTO @tvp_RowVersion
     FROM (SELECT
        [CASHDRAWER],
        [CHANNEL],
        [CLOSEDATE],
        [CLOSEDATETIMEUTC],
        [CLOSEDATETIMEUTCTZID],
        [CLOSETIME],
        [CURRENTTERMINALID],
        [CUSTOMERSCOUNT],
        [DISCOUNTTOTAL],
        [LOGONSCOUNT],
        [NOSALECOUNT],
        [PAIDTOACCOUNTTOTAL],
        [POSTED],
        [RETURNSTOTAL],
        [ROUNDEDAMOUNTTOTAL],
        [SALESCOUNT],
        [SALESTOTAL],
        [SHIFTID],
        [STAFFID],
        [CURRENTSTAFFID],
        [STARTDATE],
        [STARTDATETIMEUTC],
        [STARTDATETIMEUTCTZID],
        [STARTTIME],
        [STATUS],
        [STATUSDATETIMEUTC],
        [STOREID],
        [TAXTOTAL],
        [TERMINALID],
        [TRANSACTIONSCOUNT],
        [VOIDSCOUNT],
        [DATAAREAID]
     FROM @TVP_SHIFTTABLETYPE) AS S
     WHERE
        [crt].RETAILSHIFTSTAGINGTABLE.CHANNEL = ISNULL(S.CHANNEL, 0) AND S.CHANNEL IS NOT NULL AND
        [crt].RETAILSHIFTSTAGINGTABLE.TERMINALID = ISNULL(S.TERMINALID, '') AND S.TERMINALID IS NOT NULL AND
        [crt].RETAILSHIFTSTAGINGTABLE.SHIFTID = ISNULL(S.SHIFTID, 0) AND S.SHIFTID IS NOT NULL AND
        [crt].RETAILSHIFTSTAGINGTABLE.ROWVERSION = @RV_ROWVERSION;

     SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

     IF @i_Error <> 0
     BEGIN
         SET @i_ReturnCode = @i_Error;
         RETURN @i_ReturnCode;
     END;

     SELECT TOP 1 @RV_ROWVERSION = CAST([ROWVERSION] AS ROWVERSION) FROM @tvp_RowVersion;

     -- If no rows were changed, there was a problem updating (mostly because of row version)
     IF (@i_RowCount = 0)
     BEGIN;
         SET @i_ReturnCode = [crt].fn_kErrorVersionMismatchError();
         RETURN @i_ReturnCode;
     END;

END


GO
PRINT N'Finished creating stored procedure [crt].[UPDATESHIFTSTAGING]'
GO
-- End creating stored procedure [crt].[UPDATESHIFTSTAGING]


GRANT EXECUTE ON [crt].[UPDATESHIFTSTAGING] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTADDRESSTRANS]
PRINT N'Creating stored procedure [crt].[INSERTADDRESSTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTADDRESSTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTADDRESSTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTADDRESSTRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTADDRESSTRANS]
    @bi_ChannelId           BIGINT,
    @TVP_AddressTrans       [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONADDRESSTRANS
    (
        [DATAAREAID],
        [STORE],
        [TERMINAL],
        [TRANSACTIONID],
        [SALELINENUM],
        [DELIVERYNAME],
        [SALESNAME],
        [ZIPCODE],
        [COUNTRYREGIONID],
        [STATE],
        [CITY],
        [COUNTY],
        [STREET],
        [EMAIL],
[EMAILCONTENT],
        [PHONE],
        [STREETNUMBER],
        [DISTRICTNAME],
        [CHANNEL]
    )
    SELECT
        [DATAAREAID],
        [STORE],
        [TERMINAL],
        [TRANSACTIONID],
        [SALELINENUM],
        [DELIVERYNAME],
        [SALESNAME],
        [ZIPCODE],
        [COUNTRYREGIONID],
        [STATE],
        [CITY],
        [COUNTY],
        [STREET],
        [EMAIL],
[EMAILCONTENT],
        [PHONE],
        [STREETNUMBER],
        [DISTRICTNAME],
        @bi_ChannelId
    FROM @TVP_AddressTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTADDRESSTRANS]'
GO
-- End creating stored procedure [crt].[INSERTADDRESSTRANS]


GRANT EXECUTE ON [crt].[INSERTADDRESSTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTATTRIBUTETRANS]
PRINT N'Creating stored procedure [crt].[INSERTATTRIBUTETRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTATTRIBUTETRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTATTRIBUTETRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTATTRIBUTETRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTATTRIBUTETRANS]
    @bi_channelId           BIGINT,
    @TVP_AttributeTrans     [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONATTRIBUTETRANS
    (
        [DATAAREAID],
        [STORE],
        [TERMINAL],
        [TRANSACTIONID],
        [TEXTVALUE],
        [NAME],
        [CHANNEL]
    )
    SELECT
        [DATAAREAID],
        [STORE],
        [TERMINAL],
        [TRANSACTIONID],
        [TEXTVALUE],
        [NAME],
        @bi_channelId
    FROM @TVP_AttributeTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTATTRIBUTETRANS]'
GO
-- End creating stored procedure [crt].[INSERTATTRIBUTETRANS]


GRANT EXECUTE ON [crt].[INSERTATTRIBUTETRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTBANKEDTENDERTRANS]
PRINT N'Creating stored procedure [crt].[INSERTBANKEDTENDERTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTBANKEDTENDERTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTBANKEDTENDERTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTBANKEDTENDERTRANS].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
INSERTBANKEDTENDERTRANS inserts tender transactions into AX.[RETAILTRANSACTIONBANKEDTENDERTRANS].
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[INSERTBANKEDTENDERTRANS]
    @bi_channelIdBIGINT,
    @TVP_TenderDropTransTable       [crt].[TENDERDROPTRANSTYPE]    READONLY    
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
INSERT INTO [ax].[RETAILTRANSACTIONBANKEDTENDERTRANS]
           (
[AMOUNTCUR]
           ,[AMOUNTCURPOS]
           ,[AMOUNTMST]
           ,[AMOUNTMSTPOS]
           ,[AMOUNTTENDERED]
           ,[AMOUNTTENDEREDPOS]
           ,[BANKBAGNO]
           ,[CARDORACCOUNT]
           ,[CARDTYPEID]
           ,[CHANNEL]
           ,[CURRENCY]
           ,[EXCHRATE]
           ,[EXCHRATEMST]
           ,[LINENUM]
           ,[QTY]
           ,[REPLICATED]
           ,[SHIFT]
           ,[SHIFTDATE]
           ,[STAFF]
           ,[STATEMENTCODE]
           ,[STATUSTYPE]
           ,[STORE]
           ,[TENDERTYPE]
           ,[TERMINAL]
           ,[TRANSACTIONID]
           ,[TRANSACTIONSTATUS]
           ,[TRANSDATE]
           ,[TRANSTIME]
           ,[DATAAREAID])
     SELECT
           [AMOUNTCUR]
           ,[AMOUNTCURPOS]
           ,[AMOUNTMST]
           ,[AMOUNTMSTPOS]
           ,[AMOUNTTENDERED]
           ,[AMOUNTTENDEREDPOS]
           ,[BANKBAGNO]
           ,[CARDORACCOUNT]
           ,[CARDTYPEID]
           ,@bi_channelId
           ,[CURRENCY]
           ,[EXCHRATE]
           ,[EXCHRATEMST]
           ,[LINENUM]
           ,[QTY]
           ,[REPLICATED]
           ,[SHIFT]
           ,[SHIFTDATE]
           ,[STAFF]
           ,[STATEMENTCODE]
           ,[STATUSTYPE]
           ,[STORE]
           ,[TENDERTYPE]
           ,[TERMINAL]
           ,[TRANSACTIONID]
           ,[TRANSACTIONSTATUS]
           ,[TRANSDATE]
           ,[TRANSTIME]
           ,[DATAAREAID]
   FROM @TVP_TenderDropTransTable AS Source

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;
        
        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTBANKEDTENDERTRANS]'
GO
-- End creating stored procedure [crt].[INSERTBANKEDTENDERTRANS]

GRANT EXECUTE ON [crt].[INSERTBANKEDTENDERTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTNONSALETENDER]
PRINT N'Creating stored procedure [crt].[INSERTNONSALETENDER]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTNONSALETENDER]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTNONSALETENDER] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTNONSALETENDER].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
[crt].[INSERTNONSALETENDER] calls the corresponding stored procedures to insert into:
Header record into RetailTransactionTable 
Transaction lines into INSERTPAYMENTTRANS.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[INSERTNONSALETENDER]
    @bi_ChannelId           BIGINT,
    @TVP_TRANSACTION        [crt].[RETAILTRANSACTIONTABLETYPE]                  READONLY,
    @TVP_PAYMENTTRANS       [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]      READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    --
    -- Insert RetailTransactionTable
    --
    EXEC [crt].[INSERTTRANSACTION] @bi_ChannelId, @TVP_TRANSACTION;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionPaymentTrans
    --
    EXEC [crt].[INSERTPAYMENTTRANS] @bi_ChannelId, @TVP_PAYMENTTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTNONSALETENDER]'
GO
-- End creating stored procedure [crt].[INSERTNONSALETENDER]


GRANT EXECUTE ON [crt].[INSERTNONSALETENDER] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTSAFETENDERTRANS]
PRINT N'Creating stored procedure [crt].[INSERTSAFETENDERTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSAFETENDERTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSAFETENDERTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSAFETENDERTRANS].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
[INSERTSAFETENDERTRANS] inserts tender transactions into AX.[RETAILTRANSACTIONSAFETENDERTRANS].
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[INSERTSAFETENDERTRANS]
    @bi_channelIdBIGINT,
    @TVP_TenderDropTransTable       [crt].[TENDERDROPTRANSTYPE]    READONLY    
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
INSERT INTO [ax].[RETAILTRANSACTIONSAFETENDERTRANS]
           (
[AMOUNTCUR]
           ,[AMOUNTCURPOS]
           ,[AMOUNTMST]
           ,[AMOUNTMSTPOS]
           ,[AMOUNTTENDERED]
           ,[AMOUNTTENDEREDPOS]
           ,[CARDORACCOUNT]
           ,[CARDTYPEID]
           ,[CHANNEL]
           ,[CURRENCY]
           ,[EXCHRATE]
           ,[EXCHRATEMST]
           ,[LINENUM]
           ,[QTY]
           ,[REPLICATED]
           ,[SHIFT]
           ,[SHIFTDATE]
           ,[STAFF]
           ,[STATEMENTCODE]
           ,[STATUSTYPE]
           ,[STORE]
           ,[TENDERTYPE]
           ,[TERMINAL]
           ,[TRANSACTIONID]
           ,[TRANSACTIONSTATUS]
           ,[TRANSDATE]
           ,[TRANSTIME]
           ,[DATAAREAID])
     SELECT
           [AMOUNTCUR]
           ,[AMOUNTCURPOS]
           ,[AMOUNTMST]
           ,[AMOUNTMSTPOS]
           ,[AMOUNTTENDERED]
           ,[AMOUNTTENDEREDPOS]
           ,[CARDORACCOUNT]
           ,[CARDTYPEID]
           ,@bi_channelId
           ,[CURRENCY]
           ,[EXCHRATE]
           ,[EXCHRATEMST]
           ,[LINENUM]
           ,[QTY]
           ,[REPLICATED]
           ,[SHIFT]
           ,[SHIFTDATE]
           ,[STAFF]
           ,[STATEMENTCODE]
           ,[STATUSTYPE]
           ,[STORE]
           ,[TENDERTYPE]
           ,[TERMINAL]
           ,[TRANSACTIONID]
           ,[TRANSACTIONSTATUS]
           ,[TRANSDATE]
           ,[TRANSTIME]
           ,[DATAAREAID]
   FROM @TVP_TenderDropTransTable AS Source

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;
        
        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSAFETENDERTRANS]'
GO
-- End creating stored procedure [crt].[INSERTSAFETENDERTRANS]

GRANT EXECUTE ON [crt].[INSERTSAFETENDERTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTTENDERDECLARATION]
PRINT N'Creating stored procedure [crt].[INSERTTENDERDECLARATION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTTENDERDECLARATION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTTENDERDECLARATION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTTENDERDECLARATION].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
[INSERTTENDERDECLARATION] inserts tender transactions into AX.[RETAILTRANSACTIONTENDERDECLARATIONTRANS].
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[INSERTTENDERDECLARATION]
    @bi_channelId               BIGINT,
    @TVP_TenderDeclareTrans       [crt].[TENDERDECLARATIONTRANSTYPE]    READONLY    
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].[RETAILTRANSACTIONTENDERDECLARATIONTRANS]
    (
      [AMOUNTCUR]
      ,[AMOUNTMST]
      ,[AMOUNTTENDERED]
      ,[CARDID]
      ,[CHANNEL]
      ,[CURRENCY]
      ,[EXCHRATE]
      ,[EXCHRATEMST]
      ,[LINENUM]
      ,[POSCURRENCY]
      ,[QTY]
      ,[RECEIPTID]
      ,[REPLICATED]      
      ,[SHIFT]
      ,[SHIFTDATE]
      ,[STAFF]
      ,[STATEMENTCODE]
      ,[STORE]
      ,[TENDERTYPE]
      ,[TERMINAL]
      ,[TRANSACTIONID]
      ,[TRANSACTIONSTATUS]
      ,[TRANSDATE]
      ,[TRANSTIME]
      ,[DATAAREAID]      
    )
    SELECT
      [AMOUNTCUR]
      ,[AMOUNTMST]
      ,[AMOUNTTENDERED]
      ,[CARDID]
      ,@bi_channelId
      ,[CURRENCY]
      ,[EXCHRATE]
      ,[EXCHRATEMST]
      ,[LINENUM]
      ,[POSCURRENCY]
      ,[QTY]
      ,[RECEIPTID]
      ,[REPLICATED]      
      ,[SHIFT]
      ,[SHIFTDATE]
      ,[STAFF]
      ,[STATEMENTCODE]
      ,[STORE]
      ,[TENDERTYPE]
      ,[TERMINAL]
      ,[TRANSACTIONID]
      ,[TRANSACTIONSTATUS]
      ,[TRANSDATE]
      ,[TRANSTIME]
      ,[DATAAREAID]      
    FROM @TVP_TenderDeclareTrans AS Source;


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;
        
        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTTENDERDECLARATION]'
GO
-- End creating stored procedure [crt].[INSERTTENDERDECLARATION]

GRANT EXECUTE ON [crt].[INSERTTENDERDECLARATION] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTTENDERDROPANDDECLARE]
PRINT N'Creating stored procedure [crt].[INSERTTENDERDROPANDDECLARE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTTENDERDROPANDDECLARE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTTENDERDROPANDDECLARE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTTENDERDROPANDDECLARE].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
[crt].[INSERTTENDERDROPANDDECLARE] calls the corresponding stored procedures to insert into:
Header record into RetailTransactionTable 
Transaction lines into RETAILTRANSACTIONTENDERDECLARATIONTRANS, RETAILTRANSACTIONBANKEDTENDERTRANS and RETAILTRANSACTIONSAFETENDERTRANS.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[INSERTTENDERDROPANDDECLARE]
    @bi_ChannelIdBIGINT,
    @tvp_Transaction[crt].[RETAILTRANSACTIONTABLETYPE]      READONLY,
@tvp_TenderDeclareTrans[crt].[TENDERDECLARATIONTRANSTYPE]      READONLY,
@tvp_TenderDropTrans[crt].[TENDERDROPTRANSTYPE]      READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;
DECLARE @tvp_BankDropTrans[crt].[TENDERDROPTRANSTYPE];
DECLARE @tvp_SafeDropTrans[crt].[TENDERDROPTRANSTYPE];

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    --
    -- Insert RetailTransactionTable
    --
    EXEC [crt].[INSERTTRANSACTION] @bi_ChannelId, @tvp_Transaction;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RETAILTRANSACTIONTENDERDECLARATIONTRANS
    --
    EXEC [crt].[INSERTTENDERDECLARATION] @bi_ChannelId, @tvp_TenderDeclareTrans;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RETAILTRANSACTIONBANKEDTENDERTRANS
    --

    -- Insert into table value by filtering type for BankDrop (16)

INSERT INTO @tvp_BankDropTrans 
SELECT[TENDERTRANS].[AMOUNTCUR], 
[TENDERTRANS].[AMOUNTCURPOS], 
[TENDERTRANS].[AMOUNTMST], 
[TENDERTRANS].[AMOUNTMSTPOS], 
[TENDERTRANS].[AMOUNTTENDERED], 
[TENDERTRANS].[AMOUNTTENDEREDPOS],
ISNULL([TENDERTRANS].[TYPE],0), 
[TENDERTRANS].[BANKBAGNO], 
[TENDERTRANS].[CARDORACCOUNT], 
[TENDERTRANS].[CARDTYPEID], 
[TENDERTRANS].[CURRENCY], 
[TENDERTRANS].[EXCHRATE], 
[TENDERTRANS].[EXCHRATEMST], 
[TENDERTRANS].[LINENUM], 
[TENDERTRANS].[QTY],
[TENDERTRANS].[REPLICATED], 
[TENDERTRANS].[SHIFT], 
[TENDERTRANS].[SHIFTDATE], 
[TENDERTRANS].[STAFF], 
[TENDERTRANS].[STATEMENTCODE], 
[TENDERTRANS].[STATUSTYPE],
[TENDERTRANS].[STORE], 
[TENDERTRANS].[TENDERTYPE], 
[TENDERTRANS].[TERMINAL], 
[TENDERTRANS].[TRANSACTIONID], 
[TENDERTRANS].[TRANSACTIONSTATUS], 
[TENDERTRANS].[TRANSDATE], 
[TENDERTRANS].[TRANSTIME],
[TENDERTRANS].[DATAAREAID]
FROM @tvp_TenderDropTrans AS TENDERTRANS WHERE ISNULL([TENDERTRANS].[TYPE],0) = 16

    EXEC [crt].[INSERTBANKEDTENDERTRANS] @bi_ChannelId, @tvp_BankDropTrans;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RETAILTRANSACTIONSAFETENDERTRANS
    --

    -- Insert into table value by filtering type for SafeDrop (17)

INSERT INTO @tvp_SafeDropTrans 
SELECT [TENDERTRANS].[AMOUNTCUR], 
[TENDERTRANS].[AMOUNTCURPOS], 
[TENDERTRANS].[AMOUNTMST], 
[TENDERTRANS].[AMOUNTMSTPOS], 
[TENDERTRANS].[AMOUNTTENDERED], 
[TENDERTRANS].[AMOUNTTENDEREDPOS],
ISNULL([TENDERTRANS].[TYPE],0), 
[TENDERTRANS].[BANKBAGNO], 
[TENDERTRANS].[CARDORACCOUNT], 
[TENDERTRANS].[CARDTYPEID], 
[TENDERTRANS].[CURRENCY], 
[TENDERTRANS].[EXCHRATE], 
[TENDERTRANS].[EXCHRATEMST], 
[TENDERTRANS].[LINENUM], 
[TENDERTRANS].[QTY],
[TENDERTRANS].[REPLICATED], 
[TENDERTRANS].[SHIFT], 
[TENDERTRANS].[SHIFTDATE], 
[TENDERTRANS].[STAFF], 
[TENDERTRANS].[STATEMENTCODE], 
[TENDERTRANS].[STATUSTYPE],
[TENDERTRANS].[STORE], 
[TENDERTRANS].[TENDERTYPE], 
[TENDERTRANS].[TERMINAL], 
[TENDERTRANS].[TRANSACTIONID], 
[TENDERTRANS].[TRANSACTIONSTATUS], 
[TENDERTRANS].[TRANSDATE], 
[TENDERTRANS].[TRANSTIME],
[TENDERTRANS].[DATAAREAID]
FROM @tvp_TenderDropTrans AS TENDERTRANS WHERE ISNULL([TENDERTRANS].[TYPE],0) = 17

EXEC [crt].[INSERTSAFETENDERTRANS] @bi_ChannelId, @tvp_SafeDropTrans;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTTENDERDROPANDDECLARE]'
GO
-- End creating stored procedure [crt].[INSERTTENDERDROPANDDECLARE]


GRANT EXECUTE ON [crt].[INSERTTENDERDROPANDDECLARE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTINFOCODETRANS]
PRINT N'Creating stored procedure [crt].[INSERTINFOCODETRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTINFOCODETRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTINFOCODETRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTINFOCODETRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTINFOCODETRANS]
    @bi_ChannelId           BIGINT,
    @TVP_InfoCodeTrans      [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONINFOCODETRANS
    (
        [TRANSACTIONID],
        [LINENUM],
        [DATAAREAID],
        [TYPE],
        [INFOCODEID],
        [INFORMATION],
        [INFOAMOUNT],
        [TRANSDATE],
        [TRANSTIME],
        [STORE],
        [TERMINAL],
        [STAFF],
        [ITEMTENDER],
        [AMOUNT],
        [INPUTTYPE],
        [SUBINFOCODEID],
        [STATEMENTCODE],
        [SOURCECODE],
        [SOURCECODE2],
        [SOURCECODE3],
        [PARENTLINENUM],
        [CHANNEL]
    )
    SELECT
        [TRANSACTIONID],
        [LINENUM],
        [DATAAREAID],
        [TYPE],
        [INFOCODEID],
        [INFORMATION],
        [INFOAMOUNT],
        CAST([TRANSDATE] AS DATE),
        [TRANSTIME],
        [STORE],
        [TERMINAL],
        [STAFF],
        [ITEMTENDER],
        [AMOUNT],
        [INPUTTYPE],
        [SUBINFOCODEID],
        [STATEMENTCODE],
        [SOURCECODE],
        [SOURCECODE2],
        [SOURCECODE3],
        [PARENTLINENUM],
        @bi_ChannelId
    FROM @TVP_InfoCodeTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTINFOCODETRANS]'
GO
-- End creating stored procedure [crt].[INSERTINFOCODETRANS]


GRANT EXECUTE ON [crt].[INSERTINFOCODETRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTMARKUPTRANS]
PRINT N'Creating stored procedure [crt].[INSERTMARKUPTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTMARKUPTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTMARKUPTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTMARKUPTRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTMARKUPTRANS]
    @bi_channelId           BIGINT,
    @TVP_MarkupTrans        [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONMARKUPTRANS
    (
        [CURRENCYCODE],
        [DATAAREAID],
        [MARKUPCODE],
        [MARKUPLINENUM],
        [SALELINENUM],
        [STORE],
        [TAXGROUP],
        [TAXITEMGROUP],
        [TERMINALID],
        [TRANSACTIONID],
        [VALUE],
        [CALCULATEDAMOUNT],
        [METHOD],
[TAXAMOUNT],
[TAXAMOUNTINCLUSIVE],
[TAXAMOUNTEXCLUSIVE],
        [CHANNEL]
    )
    SELECT
        [CURRENCYCODE],
        [DATAAREAID],
        [MARKUPCODE],
        [MARKUPLINENUM],
        [SALELINENUM],
        [STORE],
        [TAXGROUP],
        [TAXITEMGROUP],
        [TERMINALID],
        [TRANSACTIONID],
        [VALUE],
        [CALCULATEDAMOUNT],
        [METHOD],
[TAXAMOUNT],
[TAXAMOUNTINCLUSIVE],
[TAXAMOUNTEXCLUSIVE],
        @bi_channelId
    FROM @TVP_MarkupTrans AS Source;


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTMARKUPTRANS]'
GO
-- End creating stored procedure [crt].[INSERTMARKUPTRANS]


GRANT EXECUTE ON [crt].[INSERTMARKUPTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTPAYMENTTRANS]
PRINT N'Creating stored procedure [crt].[INSERTPAYMENTTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTPAYMENTTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTPAYMENTTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTPAYMENTTRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTPAYMENTTRANS]
@bi_channelId           BIGINT,
@TVP_PaymentTrans       [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]    READONLY
AS
BEGIN

SET NOCOUNT ON;

DECLARE @i_ReturnCode               INT;
DECLARE @i_TransactionIsOurs        INT;
DECLARE @i_Error                    INT;

-- initializes the return code and assume the transaction is not ours by default
SET @i_ReturnCode = 0;
SET @i_TransactionIsOurs = 0;

IF @@TRANCOUNT = 0
BEGIN
BEGIN TRANSACTION;

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

SET @i_TransactionIsOurs = 1;
END;

-- Perform Insert
INSERT INTO [ax].RETAILTRANSACTIONPAYMENTTRANS
(
[AMOUNTCUR],
[CURRENCY],
[EXCHRATE],
[AMOUNTTENDERED],
[EXCHRATEMST],
[AMOUNTMST],
[DATAAREAID],
[LINENUM],
[PAYMENTAUTHORIZATION],
[STORE],
[TENDERTYPE],
[TERMINAL],
[STAFF],
[TRANSACTIONID],
[CHANGELINE],
[SIGCAPDATA],
[TRANSACTIONSTATUS],
[RECEIPTID],
[GIFTCARDID],
[LOYALTYCARDID],
[CARDORACCOUNT],
[CARDTYPEID],
[CREDITVOUCHERID],
[TRANSDATE],
[TRANSTIME],
[QTY],
[CHANNEL]
)
SELECT
[AMOUNTCUR],
[CURRENCY],
[EXCHRATE] * 100.00, -- ePOS behavior
[AMOUNTTENDERED],
[EXCHRATEMST] * 100.00, -- ePOS behavior
[AMOUNTMST],
[DATAAREAID],
[LINENUM],
[PAYMENTAUTHORIZATION],
[STORE],
[TENDERTYPE],
[TERMINAL],
[STAFF],
[TRANSACTIONID],
[CHANGELINE],
[SIGCAPDATA],
[TRANSACTIONSTATUS],
[RECEIPTID],
[GIFTCARDID],
[LOYALTYCARDID],
[CARDORACCOUNT],
[CARDTYPEID],
[CREDITVOUCHERID],
CAST([TRANSDATE] AS DATE),
[TRANSTIME],
1.0,
@bi_channelId
FROM @TVP_PaymentTrans AS Source;


SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

IF @i_TransactionIsOurs = 1
BEGIN
COMMIT TRANSACTION;

SET @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @i_ReturnCode = @i_Error;
GOTO exit_label;
END;

SET @i_TransactionIsOurs = 0;
END;

exit_label:

IF @i_TransactionIsOurs = 1
BEGIN
ROLLBACK TRANSACTION;
END;

RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTPAYMENTTRANS]'
GO
-- End creating stored procedure [crt].[INSERTPAYMENTTRANS]


GRANT EXECUTE ON [crt].[INSERTPAYMENTTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTLOYALTYREWARDPOINTTRANS]
PRINT N'Creating stored procedure [crt].[INSERTLOYALTYREWARDPOINTTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTLOYALTYREWARDPOINTTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTLOYALTYREWARDPOINTTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTLOYALTYREWARDPOINTTRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTLOYALTYREWARDPOINTTRANS]
    @bi_ChannelId           BIGINT,
@TVP_RewardPointTrans   [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE] READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS]
    (
[AFFILIATION],
[CARDNUMBER],
[CHANNEL],
[CUSTACCOUNT],
[ENTRYDATE],
[ENTRYTIME],
[ENTRYTYPE],
[EXPIRATIONDATE],
[LINENUM],
[LOYALTYTIER],
[RECEIPTID],
[REWARDPOINT],
[REWARDPOINTAMOUNTQTY],
[STAFFID],
[STOREID],
[TERMINALID],
[TRANSACTIONID],
[DATAAREAID]
    )
    SELECT
        [AFFILIATION],
[CARDNUMBER],
@bi_ChannelId,
[CUSTACCOUNT],
[ENTRYDATE],
[ENTRYTIME],
[ENTRYTYPE],
[EXPIRATIONDATE],
[LINENUM],
[LOYALTYTIER],
[RECEIPTID],
[REWARDPOINT],
[REWARDPOINTAMOUNTQTY],
[STAFFID],
[STOREID],
[TERMINALID],
[TRANSACTIONID],
[DATAAREAID]
    FROM @TVP_RewardPointTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTLOYALTYREWARDPOINTTRANS]'
GO
-- End creating stored procedure [crt].[INSERTLOYALTYREWARDPOINTTRANS]


GRANT EXECUTE ON [crt].[INSERTLOYALTYREWARDPOINTTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE]
PRINT N'Creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE].';
END
GO


ALTER PROCEDURE [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE]
    @bi_ChannelId               BIGINT,
    @tvp_ShipmentPublishStatus  [crt].[RETAILSHIPMENTPUBLISHINGSTATUSTABLETYPE] READONLY
AS
BEGIN
    SET NOCOUNT ON

    MERGE [crt].RETAILSHIPMENTPUBLISHINGSTATUS AS TARGET
    USING @tvp_ShipmentPublishStatus AS SOURCE
    ON
        TARGET.CHANNELID = @bi_ChannelId
        AND TARGET.SALESID = SOURCE.SALESID
        AND TARGET.PACKINGSLIPID = SOURCE.PACKINGSLIPID
    WHEN MATCHED THEN
        UPDATE
        SET PUBLISHSTATUS = SOURCE.PUBLISHSTATUS,
            CHANNELBATCHID = SOURCE.CHANNELBATCHID,
            CHANNELREFID = SOURCE.CHANNELREFID,
            PUBLISHMESSAGE = SOURCE.PUBLISHMESSAGE
    WHEN NOT MATCHED THEN
        INSERT
        (
            [CHANNELID],
            [SALESID],
            [PACKINGSLIPID],
            [PUBLISHSTATUS],
            [CHANNELBATCHID],
            [CHANNELREFID],
            [PUBLISHMESSAGE]
        )
        VALUES
        (
            @bi_ChannelId,
            SOURCE.[SALESID],
            SOURCE.[PACKINGSLIPID],
            SOURCE.[PUBLISHSTATUS],
            SOURCE.[CHANNELBATCHID],
            SOURCE.[CHANNELREFID],
            SOURCE.[PUBLISHMESSAGE]
        );
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE]'
GO
-- End creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE]


GRANT EXECUTE ON [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[INSERTPUBLISHSTATUSFORCURRENTSHIPMENTPAGE] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[INSERTSALESTRANS]
PRINT N'Creating stored procedure [crt].[INSERTSALESTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSALESTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSALESTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSALESTRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTSALESTRANS]
    @bi_ChannelId           BIGINT,
    @TVP_SALESTRANS         [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONSALESTRANS
    (
        [CUSTACCOUNT],
        [CREATEDDATETIME],
        [DATAAREAID],
        [DISCAMOUNT],
        [TOTALDISCAMOUNT],
        [TOTALDISCPCT],
        [LINEDSCAMOUNT],
        [PERIODICDISCAMOUNT],
        [PERIODICPERCENTAGEDISCOUNT],
        [LINEMANUALDISCOUNTAMOUNT],
        [LINEMANUALDISCOUNTPERCENTAGE],
        [DLVMODE],
        [INVENTDIMID],
        [INVENTLOCATIONID],
        [INVENTSERIALID],
        [INVENTSITEID],
        [ITEMID],
[BARCODE],
        [LINENUM],
        [LISTINGID],
        [LOGISTICSPOSTALADDRESS],
        [NETAMOUNT],
        [NETAMOUNTINCLTAX],
        [PRICE],
        [QTY],
        [RECEIPTDATEREQUESTED],
        [SHIPPINGDATEREQUESTED],
        [STORE],
        [TAXAMOUNT],
        [TAXGROUP],
        [TAXITEMGROUP],
        [TERMINALID],
        [STAFFID],
        [TRANSACTIONID],
        [UNIT],
        [VARIANTID],
        [RETURNNOSALE],
        [RETURNTRANSACTIONID],
        [RETURNLINENUM],
        [RETURNSTORE],
        [RETURNTERMINALID],
        [RECEIPTID],
        [TRANSDATE],
        [TRANSTIME],
        [TRANSACTIONSTATUS],
        [CHANNEL],
        [COMMENT],
        [GIFTCARD],
[CATALOG],
[ELECTRONICDELIVERYEMAIL],
[ELECTRONICDELIVERYEMAILCONTENT]
    )
    SELECT
        [CUSTACCOUNT],
        [CREATEDDATETIME],
        [DATAAREAID],
        [DISCAMOUNT],
        [TOTALDISCAMOUNT],
        [TOTALDISCPCT],
        [LINEDSCAMOUNT],
        [PERIODICDISCAMOUNT],
        [PERIODICPERCENTAGEDISCOUNT],
        [LINEMANUALDISCOUNTAMOUNT],
        [LINEMANUALDISCOUNTPERCENTAGE],
        [DLVMODE],
        [INVENTDIMID],
        [INVENTLOCATIONID],
        [INVENTSERIALID],
        [INVENTSITEID],
        [ITEMID],
[BARCODE],
        [LINENUM],
        [LISTINGID],
        [LOGISTICSPOSTALADDRESS],
        [NETAMOUNT],
        [NETAMOUNTINCLTAX],
        [PRICE],
        [QTY],
        CAST([RECEIPTDATEREQUESTED] AS DATE),
        CAST([SHIPPINGDATEREQUESTED] AS DATE),
        [STORE],
        [TAXAMOUNT],
        [TAXGROUP],
        [TAXITEMGROUP],
        [TERMINALID],
        [STAFFID],
        [TRANSACTIONID],
        [UNIT],
        [VARIANTID],
        [RETURNNOSALE],
        [RETURNTRANSACTIONID],
        [RETURNLINENUM],
        [RETURNSTORE],
        [RETURNTERMINALID],
        [RECEIPTID],
        CAST([TRANSDATE] AS DATE),
        [TRANSTIME],
        [TRANSACTIONSTATUS],
        @bi_ChannelId,
        [COMMENT],
        [GIFTCARD],
[CATALOG],
[ELECTRONICDELIVERYEMAIL],
[ELECTRONICDELIVERYEMAILCONTENT]
    FROM @TVP_SALESTRANS AS Source;


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSALESTRANS]'
GO
-- End creating stored procedure [crt].[INSERTSALESTRANS]


GRANT EXECUTE ON [crt].[INSERTSALESTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTSHIFTTENDERLINE]
PRINT N'Creating stored procedure [crt].[INSERTSHIFTTENDERLINE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSHIFTTENDERLINE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSHIFTTENDERLINE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSHIFTTENDERLINE].';
END
GO


ALTER PROCEDURE [crt].[INSERTSHIFTTENDERLINE]
    @TVP_SHIFTTENDERLINETABLETYPE       [crt].[SHIFTTENDERLINETABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILPOSBATCHTENDERTRANS
    (
        [ADDTOTENDERAMOUNT],
        [ADDTOTENDERAMOUNTCUR],
        [BANKDROPAMOUNT],
        [BANKDROPAMOUNTCUR],
        [BATCHID],
        [CARDTYPEID],
        [CHANGEAMOUNT],
        [CHANGEAMOUNTCUR],
        [CHANNEL],
        [COUNT],
        [COUNTINGREQUIRED],
        [CURRENCY],
        [DECLARETENDERAMOUNT],
        [DECLARETENDERAMOUNTCUR],
        [REMOVETENDERAMOUNT],
        [REMOVETENDERAMOUNTCUR],
        [SAFEDROPAMOUNT],
        [SAFEDROPAMOUNTCUR],
        [STARTINGAMOUNT],
        [STARTINGAMOUNTCUR],
        [STOREID],
        [TENDEREDAMOUNT],
        [TENDEREDAMOUNTCUR],
        [TENDERTYPEID],
        [TERMINALID],
        [DATAAREAID]
    )
    SELECT
        [ADDTOTENDERAMOUNT],
        [ADDTOTENDERAMOUNTCUR],
        [BANKDROPAMOUNT],
        [BANKDROPAMOUNTCUR],
        [SHIFTID],
        [CARDTYPEID],
        [CHANGEAMOUNT],
        [CHANGEAMOUNTCUR],
        [CHANNEL],
        [COUNT],
        [COUNTINGREQUIRED],
        [CURRENCY],
        [DECLARETENDERAMOUNT],
        [DECLARETENDERAMOUNTCUR],
        [REMOVETENDERAMOUNT],
        [REMOVETENDERAMOUNTCUR],
        [SAFEDROPAMOUNT],
        [SAFEDROPAMOUNTCUR],
        [STARTINGAMOUNT],
        [STARTINGAMOUNTCUR],
        [STOREID],
        [TENDEREDAMOUNT],
        [TENDEREDAMOUNTCUR],
        [TENDERTYPEID],
        [TERMINALID],
        [DATAAREAID]
    FROM @TVP_SHIFTTENDERLINETABLETYPE;


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSHIFTTENDERLINE]'
GO
-- End creating stored procedure [crt].[INSERTSHIFTTENDERLINE]


GRANT EXECUTE ON [crt].[INSERTSHIFTTENDERLINE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTSHIFTSTAGING]
PRINT N'Creating stored procedure [crt].[INSERTSHIFTSTAGING]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSHIFTSTAGING]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSHIFTSTAGING] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSHIFTSTAGING].';
END
GO


ALTER PROCEDURE [crt].[INSERTSHIFTSTAGING]
    @TVP_SHIFTTABLETYPE [crt].[SHIFTTABLETYPE] READONLY,
    @RV_ROWVERSION      ROWVERSION             OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_ReturnCode           INT;
    DECLARE @i_Error                INT;
    DECLARE @tvp_RowVersion         TABLE ([ROWVERSION] BINARY(8));

    INSERT INTO [crt].RETAILSHIFTSTAGINGTABLE
    (
        CHANNEL
        ,STOREID
        ,TERMINALID
        ,SHIFTID
        ,STAFFID
,CURRENTSTAFFID
        ,[STATUS]
        ,CURRENTTERMINALID
        ,STARTDATETIMEUTC
        ,STATUSDATETIMEUTC
        ,DATAAREAID
        ,CASHDRAWER
    )
    OUTPUT INSERTED.[ROWVERSION] INTO @tvp_RowVersion
    SELECT
        SOURCE.CHANNEL
        ,SOURCE.STOREID
        ,SOURCE.TERMINALID
        ,SOURCE.SHIFTID
        ,SOURCE.STAFFID
,SOURCE.CURRENTSTAFFID
        ,SOURCE.[STATUS]
        ,SOURCE.CURRENTTERMINALID
        ,SOURCE.STARTDATETIMEUTC
        ,SOURCE.STATUSDATETIMEUTC
        ,SOURCE.DATAAREAID
        ,SOURCE.CASHDRAWER
    FROM @TVP_SHIFTTABLETYPE AS SOURCE

    SELECT @i_Error = @@ERROR;

    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        RETURN @i_ReturnCode;
    END;

    SELECT TOP 1 @RV_ROWVERSION = CAST([ROWVERSION] AS ROWVERSION) FROM @tvp_RowVersion;
END;

GO


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSHIFTSTAGING]'
GO
-- End creating stored procedure [crt].[INSERTSHIFTSTAGING]


GRANT EXECUTE ON [crt].[INSERTSHIFTSTAGING] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTSHIFT]
PRINT N'Creating stored procedure [crt].[INSERTSHIFT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSHIFT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSHIFT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSHIFT].';
END
GO


ALTER PROCEDURE [crt].[INSERTSHIFT]
    @TVP_SHIFTTABLETYPE              [crt].[SHIFTTABLETYPE]                  READONLY,
    @TVP_SHIFTTENDERLINETABLETYPE    [crt].[SHIFTTENDERLINETABLETYPE]        READONLY,
@TVP_SHIFTACCOUNTLINETABLETYPE    [crt].[SHIFTACCOUNTLINETYPE]     READONLY,
    @RV_ROWVERSION                   ROWVERSION                              OUTPUT
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;
    DECLARE @tvp_RowVersion             TABLE ([ROWVERSION] BINARY(8));

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    --
    -- Insert Shift
    --

    -- Perform Insert
    INSERT INTO [ax].RETAILPOSBATCHTABLE
    (
        [BATCHID],
        [CHANNEL],
        [CLOSEDATE],
        [CLOSEDATETIMEUTC],
        [CLOSEDATETIMEUTCTZID],
        [CLOSETIME],
        [CUSTOMERSCOUNT],
        [DISCOUNTTOTAL],
        [LOGONSCOUNT],
        [NOSALECOUNT],
        [PAIDTOACCOUNTTOTAL],
        [POSTED],
        [RETURNSTOTAL],
        [ROUNDEDAMOUNTTOTAL],
        [SALESCOUNT],
        [SALESTOTAL],
        [STAFFID],
        [STARTDATE],
        [STARTDATETIMEUTC],
        [STARTDATETIMEUTCTZID],
        [STARTTIME],
        [STATUS],
        [STOREID],
        [TAXTOTAL],
        [TERMINALID],
        [TRANSACTIONSCOUNT],
        [VOIDSCOUNT],
        [DATAAREAID]
    )
    OUTPUT INSERTED.[ROWVERSION] INTO @tvp_RowVersion
    SELECT
        [SHIFTID],
        [CHANNEL],
        [CLOSEDATE],
        [CLOSEDATETIMEUTC],
        [CLOSEDATETIMEUTCTZID],
        [CLOSETIME],
        [CUSTOMERSCOUNT],
        [DISCOUNTTOTAL],
        [LOGONSCOUNT],
        [NOSALECOUNT],
        [PAIDTOACCOUNTTOTAL],
        [POSTED],
        [RETURNSTOTAL],
        [ROUNDEDAMOUNTTOTAL],
        [SALESCOUNT],
        [SALESTOTAL],
        [STAFFID],
        [STARTDATE],
        [STARTDATETIMEUTC],
        [STARTDATETIMEUTCTZID],
        [STARTTIME],
        [STATUS],
        [STOREID],
        [TAXTOTAL],
        [TERMINALID],
        [TRANSACTIONSCOUNT],
        [VOIDSCOUNT],
        [DATAAREAID]
    FROM @TVP_SHIFTTABLETYPE;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    SELECT TOP 1 @RV_ROWVERSION = CAST([ROWVERSION] AS ROWVERSION) FROM @tvp_RowVersion;

    -- Insert ShiftTenderLine
    EXEC @i_Error = [crt].[INSERTSHIFTTENDERLINE] @TVP_SHIFTTENDERLINETABLETYPE;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

-- Insert ShiftTenderLine
    EXEC @i_Error = [crt].[INSERTSHIFTACCOUNTLINE] @TVP_SHIFTACCOUNTLINETABLETYPE;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSHIFT]'
GO
-- End creating stored procedure [crt].[INSERTSHIFT]


GRANT EXECUTE ON [crt].[INSERTSHIFT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTSHIFTACCOUNTLINE]
PRINT N'Creating stored procedure [crt].[INSERTSHIFTACCOUNTLINE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSHIFTACCOUNTLINE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSHIFTACCOUNTLINE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSHIFTACCOUNTLINE].';
END
GO


ALTER PROCEDURE [crt].[INSERTSHIFTACCOUNTLINE]
    @TVP_SHIFTACCOUNTLINETABLETYPE       [crt].[SHIFTACCOUNTLINETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].[RETAILPOSBATCHACCOUNTTRANS]
    (
        [BATCHID],
        [CHANNEL],
        [STOREID],
        [TERMINALID],
[ACCOUNTNUM],
[ACCOUNTTYPE],
[AMOUNT]
    )
    SELECT
        [SHIFTID],
        [CHANNEL],
        [STOREID],
        [TERMINALID],
[INCOMEEXEPENSEACCOUNT],
[ACCOUNTTYPE],
[AMOUNT]
    FROM @TVP_SHIFTACCOUNTLINETABLETYPE;


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSHIFTACCOUNTLINE]'
GO
-- End creating stored procedure [crt].[INSERTSHIFTACCOUNTLINE]


GRANT EXECUTE ON [crt].[INSERTSHIFTACCOUNTLINE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTDISCOUNTTRANS]
PRINT N'Creating stored procedure [crt].[INSERTDISCOUNTTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTDISCOUNTTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTDISCOUNTTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTDISCOUNTTRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTDISCOUNTTRANS]
    @bi_channelId           BIGINT,
    @TVP_DiscountTrans      [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONDISCOUNTTRANS
    (
        [AMOUNT],        
        [DATAAREAID],
        [DEALPRICE],
        [DISCOUNTAMOUNT],
        [DISCOUNTCODE],
        [LINENUM],         
        [PERCENTAGE],
        [PERIODICDISCOUNTOFFERID],
        [SALELINENUM],
        [STOREID],
        [TERMINALID],
        [TRANSACTIONID],
        [CHANNEL],
        [DISCOUNTORIGINTYPE],
        [MANUALDISCOUNTTYPE],
        [CUSTOMERDISCOUNTTYPE] 
    )
    SELECT
        [AMOUNT],
        [DATAAREAID],
        [DEALPRICE],
        [DISCOUNTAMOUNT],
        [DISCOUNTCODE],
        [LINENUM],
        [PERCENTAGE],
        [PERIODICDISCOUNTOFFERID],
        [SALELINENUM],
        [STOREID],
        [TERMINALID],
        [TRANSACTIONID],
        @bi_channelId,
        [DISCOUNTORIGINTYPE],
        [MANUALDISCOUNTTYPE],
        [CUSTOMERDISCOUNTTYPE]   
    FROM @TVP_DiscountTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTDISCOUNTTRANS]'
GO
-- End creating stored procedure [crt].[INSERTDISCOUNTTRANS]


GRANT EXECUTE ON [crt].[INSERTDISCOUNTTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTTAXTRANS]
PRINT N'Creating stored procedure [crt].[INSERTTAXTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTTAXTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTTAXTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTTAXTRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTTAXTRANS]
    @bi_ChannelId           BIGINT,
    @TVP_TaxTrans           [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONTAXTRANS
    (
        [AMOUNT],
        [DATAAREAID],
        [ISINCLUDEDINPRICE],
        [SALELINENUM],
        [STOREID],
        [TAXCODE],
        [TERMINALID],
        [TRANSACTIONID],
        [CHANNEL]
    )
    SELECT
        [AMOUNT],
        [DATAAREAID],
        [ISINCLUDEDINPRICE],
        [SALELINENUM],
        [STOREID],
        [TAXCODE],
        [TERMINALID],
        [TRANSACTIONID],
        @bi_ChannelId
    FROM @TVP_TaxTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTTAXTRANS]'
GO
-- End creating stored procedure [crt].[INSERTTAXTRANS]


GRANT EXECUTE ON [crt].[INSERTTAXTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTTRANSACTION]
PRINT N'Creating stored procedure [crt].[INSERTTRANSACTION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTTRANSACTION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTTRANSACTION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTTRANSACTION].';
END
GO


ALTER PROCEDURE [crt].[INSERTTRANSACTION]
    @bi_ChannelId               BIGINT,
    @TVP_TransactionTable       [crt].[RETAILTRANSACTIONTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONTABLE
    (
        [CHANNELREFERENCEID],
        [CREATEDDATETIME],
        [MODIFIEDDATETIME],
        [TRANSDATE],
        [TRANSTIME],
        [BUSINESSDATE],
        [CURRENCY],
        [EXCHRATE],
        [ENTRYSTATUS],
        [CUSTACCOUNT],
        [DATAAREAID],
        [DLVMODE],
        [GROSSAMOUNT],
        [INVENTLOCATIONID],
        [INVENTSITEID],
        [INCOMEEXPENSEAMOUNT],
        [LOGISTICSPOSTALADDRESS],
        [NETAMOUNT],
        [PAYMENTAMOUNT],
        [RECEIPTDATEREQUESTED],
        [SHIPPINGDATEREQUESTED],
        [STORE],
        [TERMINAL],
        [CREATEDONPOSTERMINAL],
        [STAFF],
        [TRANSACTIONID],
        [TYPE],
        [CHANNEL],
        [LOYALTYCARDID],
        [RECEIPTEMAIL],
        [RECEIPTID],
        [NUMBEROFITEMS],
        [NUMBEROFITEMLINES],
        [NUMBEROFPAYMENTLINES],
        [TIMEWHENTRANSCLOSED],
        [SALEISRETURNSALE],
        [DISCAMOUNT],
        [TOTALDISCAMOUNT],
        [CUSTDISCAMOUNT],
        [TOTALMANUALDISCOUNTAMOUNT],
        [TOTALMANUALDISCOUNTPERCENTAGE],
        [BATCHID],
        [BATCHTERMINALID],
        [COMMENT],
        [SALESORDERID],
        [DESCRIPTION],
[STATEMENTCODE],
        [FISCALDOCUMENTID],
        [FISCALSERIALID]
    )
    SELECT
        [CHANNELREFERENCEID],
        [CREATEDDATETIME],
        [CREATEDDATETIME],          -- For inserts, we set MODIFIEDDATETIME = CREATEDDATETIME.
        CAST([TRANSDATE] AS DATE),
        [TRANSTIME],
        CAST([BUSINESSDATE] AS DATE),
        [CURRENCY],
        [EXCHRATE],
        [ENTRYSTATUS],
        [CUSTOMERID],
        [DATAAREAID],
        [DELIVERYMODE],
        [GROSSAMOUNT],
        [INVENTLOCATIONID],
        [INVENTSITEID],
        [INCOMEEXPENSEAMOUNT],
        [LOGISTICSPOSTALADDRESS],
        [NETAMOUNT],
        [PAYMENTAMOUNT],
        CAST([RECEIPTDATEREQUESTED] AS DATE),
        CAST([SHIPPINGDATEREQUESTED] AS DATE),
        [STORE],
        [TERMINAL],
        [TERMINAL], -- using same value for CREATEDONPOSTERMINAL
        [STAFF],
        [TRANSACTIONID],
        [TYPE],
        @bi_ChannelId,
        [LOYALTYCARDID],
        [RECEIPTEMAIL],
        [RECEIPTID],
        [NUMBEROFITEMS],
        [NUMBEROFITEMLINES],
        [NUMBEROFPAYMENTLINES],
        [TIMEWHENTRANSCLOSED],
        [SALEISRETURNSALE],
        [DISCAMOUNT],
        [TOTALDISCAMOUNT],
        [CUSTDISCAMOUNT],
        [TOTALMANUALDISCOUNTAMOUNT],
        [TOTALMANUALDISCOUNTPERCENTAGE],
        [BATCHID],
        [BATCHTERMINALID],
        [COMMENT],
        [SALESORDERID],
        [DESCRIPTION],
[STATEMENTCODE],
        '', --[FISCALDOCUMENTID],
        '' --[FISCALSERIALID]
    FROM @TVP_TransactionTable AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTTRANSACTION]'
GO
-- End creating stored procedure [crt].[INSERTTRANSACTION]


GRANT EXECUTE ON [crt].[INSERTTRANSACTION] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTSALESPROPERTIES]
PRINT N'Creating stored procedure [crt].[INSERTSALESPROPERTIES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSALESPROPERTIES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSALESPROPERTIES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSALESPROPERTIES].';
END
GO


ALTER PROCEDURE [crt].[INSERTSALESPROPERTIES]
    @bi_channelId           BIGINT,
    @TVP_SALESPROPERTIES    [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [crt].[RETAILTRANSACTIONPROPERTIES]
    (
        [DATAAREAID],
        [CHANNEL],
        [STOREID],
        [TERMINALID],
        [TRANSACTIONID],
        [SALELINENUM],
        [NAME],
        [VALUE]
    )
    SELECT
        [DATAAREAID],
        @bi_channelId,
        [STOREID],
        [TERMINALID],
        [TRANSACTIONID],
        [SALELINENUM],
        [NAME],
        [VALUE]
    FROM @TVP_SALESPROPERTIES;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSALESPROPERTIES]'
GO
-- End creating stored procedure [crt].[INSERTSALESPROPERTIES]


GRANT EXECUTE ON [crt].[INSERTSALESPROPERTIES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTSALESORDER]
PRINT N'Creating stored procedure [crt].[INSERTSALESORDER]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTSALESORDER]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTSALESORDER] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTSALESORDER].';
END
GO


ALTER PROCEDURE [crt].[INSERTSALESORDER]
    @bi_ChannelId           BIGINT,
    @TVP_TRANSACTION        [crt].[RETAILTRANSACTIONTABLETYPE]                  READONLY,
    @TVP_SALESTRANS         [crt].[RETAILTRANSACTIONSALESTRANSTABLETYPE]        READONLY,
    @TVP_INCOMEEXPENSE      [crt].[RETAILINCOMEEXPENSETABLETYPE]                READONLY,
    @TVP_MARKUPTRANS        [crt].[RETAILTRANSACTIONMARKUPTRANSTABLETYPE]       READONLY,
    @TVP_PAYMENTTRANS       [crt].[RETAILTRANSACTIONPAYMENTTRANSTABLETYPE]      READONLY,
    @TVP_TAXTRANS           [crt].[RETAILTRANSACTIONTAXTRANSTABLETYPE]          READONLY,
    @TVP_ATTRIBUTETRANS     [crt].[RETAILTRANSACTIONATTRIBUTETRANSTABLETYPE]    READONLY,
    @TVP_ADDRESSTRANS       [crt].[RETAILTRANSACTIONADDRESSTRANSTABLETYPE]      READONLY,
    @TVP_DISCOUNTTRANS      [crt].[RETAILTRANSACTIONDISCOUNTTRANSTABLETYPE]     READONLY,
    @TVP_INFOCODETRANS      [crt].[RETAILTRANSACTIONINFOCODETRANSTABLETYPE]     READONLY,
    @TVP_SALESPROPERTIES    [crt].[RETAILTRANSACTIONPROPERTIESTABLETYPE]        READONLY,
    @TVP_REWARDPOINTTRANS   [crt].[RETAILTRANSACTIONLOYALTYREWARDPOINTTRANSTABLETYPE] READONLY,
    @TVP_AFFILIATIONTRANS   [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE]        READONLY,
    @TVP_CUSTOMERORDERTRANS [crt].[CUSTOMERORDERTRANSACTIONTABLETYPE]           READONLY,
    @TVP_INVOICETRANS       [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE] READONLY

AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    --
    -- Insert RetailTransactionTable
    --
    EXEC [crt].[INSERTTRANSACTION] @bi_ChannelId, @TVP_TRANSACTION;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionSalesTrans
    --
    EXEC [crt].[INSERTSALESTRANS] @bi_ChannelId, @TVP_SALESTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- Insert RetailIncomeExpenseAccountTable 
    EXEC [crt].[INSERTINCOMEEXPENSETRANSACTION] @TVP_INCOMEEXPENSE;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionMarkupTrans
    --
    EXEC [crt].[INSERTMARKUPTRANS] @bi_ChannelId, @TVP_MARKUPTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionTaxTrans
    --
    EXEC [crt].[INSERTTAXTRANS] @bi_ChannelId, @TVP_TAXTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionPaymentTrans
    --
    EXEC [crt].[INSERTPAYMENTTRANS] @bi_ChannelId, @TVP_PAYMENTTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionAttributeTrans
    --
    EXEC [crt].[INSERTATTRIBUTETRANS] @bi_ChannelId, @TVP_ATTRIBUTETRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionAddressTrans
    --
    EXEC [crt].[INSERTADDRESSTRANS] @bi_ChannelId, @TVP_ADDRESSTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionDiscountTrans
    --
    EXEC [crt].[INSERTDISCOUNTTRANS] @bi_ChannelId, @TVP_DISCOUNTTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionInfocodeTrans
    --
    EXEC [crt].[INSERTINFOCODETRANS] @bi_ChannelId, @TVP_INFOCODETRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionProperties
    --
    EXEC [crt].[INSERTSALESPROPERTIES] @bi_ChannelId, @TVP_SALESPROPERTIES;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionLoyaltyRewardPointTrans
    --
    EXEC [crt].[INSERTLOYALTYREWARDPOINTTRANS] @bi_ChannelId, @TVP_REWARDPOINTTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionAffiliations
    --
    EXEC [crt].[INSERTAFFILIATIONTRANS] @bi_ChannelId, @TVP_AFFILIATIONTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert CustomerOrderTransaction
    --
    EXEC [crt].[INSERTCUSTOMERORDERTRANSACTION] @bi_ChannelId, @TVP_CUSTOMERORDERTRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionOrderInvoiceTrans
    --
    EXEC [crt].[INSERTINVOICETRANS] @bi_ChannelId, @TVP_INVOICETRANS;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Final error handling
    --
    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTSALESORDER]'
GO
-- End creating stored procedure [crt].[INSERTSALESORDER]


GRANT EXECUTE ON [crt].[INSERTSALESORDER] TO [UsersRole];
GO

-- Creating stored procedure [crt].[ISPRODUCTINCATEGORY]
PRINT N'Creating stored procedure [crt].[ISPRODUCTINCATEGORY]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[ISPRODUCTINCATEGORY]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[ISPRODUCTINCATEGORY] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[ISPRODUCTINCATEGORY].';
END
GO


ALTER PROCEDURE [crt].[ISPRODUCTINCATEGORY]
    @PRODUCTRECIDBIGINT,
    @CATEGORYRECIDBIGINT
AS
BEGIN
SET NOCOUNT ON

DECLARE @i_ReturnCode INT;
SET @i_ReturnCode = 0;

IF EXISTS
(
SELECT PRODUCT, CATEGORY 
FROM [crt].[RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW]
WHERE PRODUCT = @PRODUCTRECID AND CATEGORY = @CATEGORYRECID
)
BEGIN
    SET @i_ReturnCode = 1 ;
END

RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[ISPRODUCTINCATEGORY]'
GO
-- End creating stored procedure [crt].[ISPRODUCTINCATEGORY]


GRANT EXECUTE ON [crt].[ISPRODUCTINCATEGORY] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT]
PRINT N'Creating stored procedure [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETESHIFTSTAGINGANDINSERTSHIFT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT].';
END
GO


ALTER PROCEDURE [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT]
    @TVP_SHIFTTABLETYPE             [crt].[SHIFTTABLETYPE]                  READONLY,
    @TVP_SHIFTTENDERLINETABLETYPE   [crt].[SHIFTTENDERLINETABLETYPE]        READONLY,
    @RV_ROWVERSION                  ROWVERSION                              OUTPUT
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    --
    -- DELETE ShiftStaging
    --
    DECLARE @bi_ChannelId           [BIGINT];
    DECLARE @nvc_TerminalId         [NVARCHAR](10);
    DECLARE @bi_ShiftId             [BIGINT];

    SELECT @bi_ChannelId = CHANNEL, @nvc_TerminalId = TERMINALID, @bi_ShiftId = SHIFTID
    FROM @TVP_SHIFTTABLETYPE

    EXEC @i_Error = [crt].[DELETESHIFTSTAGING] @bi_ChannelId, @nvc_TerminalId, @bi_ShiftId, @RV_ROWVERSION;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- INSERT SHIFT
    --
    DECLARE @RV_NEWROWVERSION       ROWVERSION;

    EXEC @i_Error = [crt].[INSERTSHIFT] @TVP_SHIFTTABLETYPE, @TVP_SHIFTTENDERLINETABLETYPE, @RV_ROWVERSION = @RV_NEWROWVERSION OUTPUT;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- RETURNS NEW ROWVERSION FROM SHIFT TABLE
    SELECT @RV_ROWVERSION = @RV_NEWROWVERSION


    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT]'
GO
-- End creating stored procedure [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT]


GRANT EXECUTE ON [crt].[DELETESHIFTSTAGINGANDINSERTSHIFT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETTAXCODEINTERVALS]
PRINT N'Creating stored procedure [crt].[GETTAXCODEINTERVALS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETTAXCODEINTERVALS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETTAXCODEINTERVALS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETTAXCODEINTERVALS].';
END
GO


ALTER PROCEDURE [crt].[GETTAXCODEINTERVALS]
    @bi_ChannelId       BIGINT,
    @nvc_SalesTaxGroup  NVARCHAR(10),
    @nvc_ItemTaxGroup   NVARCHAR(10),
    @dt_TransactionDate DATE
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_ReturnCode       INT;
    DECLARE @i_Error            INT;
    DECLARE @dt_NoDateBoundary  DATE;
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = INVENTLOCATIONDATAAREAID from [ax].RETAILCHANNELTABLE where RECID = @bi_ChannelId

    SET @dt_NoDateBoundary = CAST('1900-01-01' as DATE)

    SELECT DISTINCT
        toi.TAXITEMGROUP,
        toi.TAXCODE,
        ISNULL(td.TAXVALUE, 0.0) AS TAXVALUE,
        ISNULL(td.TAXLIMITMIN, 0.0) AS TAXLIMITMIN,
        ISNULL(td.TAXLIMITMAX, 0.0) AS TAXLIMITMAX,
        tgd.EXEMPTTAX,
        tgh.TAXGROUPROUNDING,
        tt.TAXCURRENCYCODE,
        tt.TAXBASE,
        tt.TAXLIMITBASE,
        tt.TAXCALCMETHOD,
        tt.TAXONTAX,
        tt.TAXUNIT,
        ISNULL(tcl.TAXMAX,0) AS TAXMAX,
        ISNULL(tcl.TAXMIN,0) AS TAXMIN
    FROM [ax].TAXGROUPHEADING tgh
    INNER JOIN [ax].TAXGROUPDATA tgd ON tgh.TAXGROUP = tgd.TAXGROUP AND tgh.DATAAREAID = tgd.DATAAREAID
    INNER JOIN [ax].TAXONITEM toi ON tgd.TAXCODE = toi.TAXCODE AND tgd.DATAAREAID = toi.DATAAREAID
    INNER JOIN [ax].TAXDATA td ON toi.TAXCODE = td.TAXCODE AND toi.DATAAREAID = td.DATAAREAID
    INNER JOIN [ax].TAXTABLE tt ON tt.TAXCODE = td.TAXCODE AND tt.DATAAREAID = td.DATAAREAID
    LEFT JOIN [ax].TAXCOLLECTLIMIT tcl ON
        tcl.TAXCODE = td.TAXCODE
        AND (tcl.TAXFROMDATE IS NULL
            OR @dt_TransactionDate >= tcl.TAXFROMDATE
            OR tcl.TAXFROMDATE = @dt_NoDateBoundary)
        AND (tcl.TAXTODATE IS NULL
            OR @dt_TransactionDate < DATEADD(d, 1, tcl.TAXTODATE)
            OR tcl.TAXTODATE = @dt_NoDateBoundary)
    WHERE
        tgh.DATAAREAID = @nvc_DataAreaId
        AND toi.TAXITEMGROUP = @nvc_ItemTaxGroup
        AND tgh.TAXGROUP = @nvc_SalesTaxGroup
        AND ((@dt_TransactionDate >= td.TAXFROMDATE OR td.TAXFROMDATE = @dt_NoDateBoundary)
        AND (@dt_TransactionDate < DATEADD(d, 1, td.TAXTODATE) OR td.TAXTODATE = @dt_NoDateBoundary))

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

exit_label:

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETTAXCODEINTERVALS]'
GO
-- End creating stored procedure [crt].[GETTAXCODEINTERVALS]


GRANT EXECUTE ON [crt].[GETTAXCODEINTERVALS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY]
PRINT N'Creating stored procedure [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY].';
END
GO


ALTER PROCEDURE [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY]
    @bi_ChannelId BIGINT,
    @OfferId    NVARCHAR(40),
    @Quantity   NUMERIC(32,16)
AS
BEGIN
    SET NOCOUNT ON

    SELECT TOP 1
        MBL.MULTIBUYID,
        MBL.QTYLOWEST,
        MBL.PRICEDISCPCT,
        MBL.RECID
    FROM [ax].RETAILMULTIBUYDISCOUNTLINE AS MBL
INNER JOIN [ax].RETAILCHANNELTABLE AS C
ON C.INVENTLOCATIONDATAAREAID = MBL.DATAAREAID AND C.RECID = @bi_ChannelId
    WHERE
        MULTIBUYID = @OfferId
        AND QTYLOWEST <= @Quantity
    ORDER BY MULTIBUYID, QTYLOWEST DESC

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY]'
GO
-- End creating stored procedure [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY]


GRANT EXECUTE ON [crt].[GETMULTIBUYLINEDISCOUNTBYQUANTITY] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETACTIVEEXCHANGERATE]
PRINT N'Creating stored procedure [crt].[GETACTIVEEXCHANGERATE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETACTIVEEXCHANGERATE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETACTIVEEXCHANGERATE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETACTIVEEXCHANGERATE].';
END
GO


ALTER PROCEDURE [crt].[GETACTIVEEXCHANGERATE]
    @nvc_FromCurrency   NVARCHAR(3),
    @nvc_ToCurrency     NVARCHAR(3),
@bi_ChannelId    BIGINT,
    @dt_ActiveDate      DATETIME
AS
BEGIN
    SET NOCOUNT ON

    SELECT
er.CHANNELID,
        er.EXCHANGERATE,
        er.FROMCURRENCYCODE,
        er.TOCURRENCYCODE,
        er.RECID
    FROM [crt].[EXCHANGERATEVIEW] AS er
    WHERE
        er.VALIDFROM <= @dt_ActiveDate
        AND er.VALIDTO >= @dt_ActiveDate
AND er.CHANNELID = @bi_ChannelId
        AND ((er.FROMCURRENCYCODE = @nvc_FromCurrency AND er.TOCURRENCYCODE = @nvc_ToCurrency) OR
            (er.FROMCURRENCYCODE = @nvc_ToCurrency AND er.TOCURRENCYCODE = @nvc_FromCurrency))

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETACTIVEEXCHANGERATE]'
GO
-- End creating stored procedure [crt].[GETACTIVEEXCHANGERATE]


GRANT EXECUTE ON [crt].[GETACTIVEEXCHANGERATE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPRICEADJUSTMENTS]
PRINT N'Creating stored procedure [crt].[GETPRICEADJUSTMENTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPRICEADJUSTMENTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPRICEADJUSTMENTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPRICEADJUSTMENTS].';
END
GO


ALTER PROCEDURE [crt].[GETPRICEADJUSTMENTS]
    @bi_ChannelId                   BIGINT,
    @bi_ProductId                   BIGINT,
    @bi_DistinctProductVariantId    BIGINT,
    @tvp_StorePriceGroups           [crt].[RECORDIDTABLETYPE] READONLY,
    @nvc_UnitId                     NVARCHAR(10),
    @nvc_CurrencyCode               NVARCHAR(3),
    @dt_ActiveDate                  DATE
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @NoDate DATE = CAST([crt].[PRICE_NODATE]() AS DATE);

    SELECT DISTINCT
        promo.OFFERID,
        promo.VALIDFROM,
        promo.VALIDTO,
        promo.CONCURRENCYMODE,
        promo.DATEVALIDATIONTYPE,
        promo.VALIDATIONPERIODID,
        promoOffer.DISCOUNTMETHOD,
        promoOffer.OFFERPRICE,
        promoOffer.OFFERPRICEINCLTAX,
        promoOffer.DISCPCT,
        promoOffer.DISCAMOUNT,
        promoOffer.RECID
    FROM [ax].RETAILPERIODICDISCOUNT promo
INNER JOIN [ax].RETAILCHANNELTABLE AS c
ON c.INVENTLOCATIONDATAAREAID = promo.DATAAREAID AND c.RECID = @bi_ChannelId
    INNER JOIN [ax].RETAILPERIODICDISCOUNTLINE promoLine ON promoLine.OFFERID = promo.OFFERID AND promoLine.DATAAREAID = promo.DATAAREAID
    INNER JOIN [ax].RETAILDISCOUNTLINEOFFER promoOffer ON promoOffer.RECID = promoLine.RECID
    LEFT JOIN [ax].UNITOFMEASURE uom ON uom.RECID = promoLine.UNITOFMEASURE
    INNER JOIN [ax].RETAILGROUPMEMBERLINE rgl ON rgl.RECID = promoLine.RETAILGROUPMEMBERLINE
    LEFT JOIN [crt].RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW rpca ON rgl.CATEGORY = rpca.CATEGORY
    INNER JOIN @tvp_StorePriceGroups spg ON promo.PRICEDISCGROUP = spg.RECID
    WHERE
        promo.STATUS = 1
        AND promo.PERIODICDISCOUNTTYPE = 3 -- get only price adjustments
        AND (promo.CURRENCYCODE = '' OR  promo.CURRENCYCODE = @nvc_CurrencyCode)
        AND (promoLine.UNITOFMEASURE = 0 OR uom.SYMBOL = '' OR uom.SYMBOL = @nvc_UnitId)
        AND ((rgl.VARIANT != 0 AND rgl.VARIANT = @bi_DistinctProductVariantId) OR
           (rgl.VARIANT = 0 AND rgl.PRODUCT != 0 AND rgl.PRODUCT = @bi_ProductId) OR
           (rgl.VARIANT = 0 AND rgl.PRODUCT = 0 AND
            (rpca.PRODUCT = @bi_ProductId OR rpca.PRODUCT = @bi_DistinctProductVariantId)))
        AND ((promo.VALIDFROM <= @dt_ActiveDate OR promo.VALIDFROM <= @NoDate)
            AND (promo.VALIDTO >= @dt_ActiveDate OR promo.VALIDTO <= @NoDate))

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPRICEADJUSTMENTS]'
GO
-- End creating stored procedure [crt].[GETPRICEADJUSTMENTS]


GRANT EXECUTE ON [crt].[GETPRICEADJUSTMENTS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS]
PRINT N'Creating stored procedure [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS].';
END
GO


ALTER PROCEDURE [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS]
    @bi_ChannelId       BIGINT,
    @COUNT              INT,
    @LASTSYNCVERSION    BIGINT = 0,
    @PUBLISHSTATUS      INT
AS
BEGIN
    SET NOCOUNT ON

    IF (@COUNT IS NULL)
    BEGIN
        RAISERROR (N'NUMBER OF RECORDS TO RETRIEVE IS MANDATORY', 16, 1)
        RETURN;
    END

    IF (@LASTSYNCVERSION IS NULL)
    BEGIN
        RAISERROR (N'VERSION OF LAST SYNCHRONIZATION IS MANDATORY', 16, 1)
        RETURN;
    END

    SELECT TOP(@COUNT)
        RSPS.SALESID,
        RSPS.PACKINGSLIPID,
        RSPS.PUBLISHSTATUS,
        RSPS.CHANNELBATCHID,
        RSPS.CHANNELREFID,
        RSPS.LASTMODIFIEDDATETIME,
        RSPS.PUBLISHMESSAGE,
        CAST(RSPS.ROWVERSION as BIGINT) as SEQUENCE
    FROM [crt].RETAILSHIPMENTPUBLISHINGSTATUS RSPS
    WHERE
        RSPS.CHANNELID = @bi_ChannelId
        AND RSPS.ROWVERSION > @LASTSYNCVERSION
        AND RSPS.PUBLISHSTATUS <> 0
        AND @PUBLISHSTATUS <> 0
    ORDER BY RSPS.ROWVERSION ASC

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS]'
GO
-- End creating stored procedure [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS]


GRANT EXECUTE ON [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETFORINCREMENTALSYNC_RETAILSHIPMENTPUBLISHINGSTATUS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETTRADEAGREEMENTS]
PRINT N'Creating stored procedure [crt].[GETTRADEAGREEMENTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETTRADEAGREEMENTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETTRADEAGREEMENTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETTRADEAGREEMENTS].';
END
GO


ALTER PROCEDURE [crt].[GETTRADEAGREEMENTS]
    @bi_ChannelId           BIGINT,
    @Relation               INT,
    @ItemCode               INT,
    @ItemRelation           NVARCHAR(20),
    @AccountCode            INT,
    @AccountRelations       [crt].[PRICEACCOUNTRELATIONSTABLETYPE] READONLY,
    @UnitId                 NVARCHAR(10),
    @CurrencyCode           NVARCHAR(3),
    @Quantity               NUMERIC(32,16),
    @ColorId                NVARCHAR(10),
    @SizeId                 NVARCHAR(10),
    @StyleId                NVARCHAR(10),
    @ConfigId               NVARCHAR(10),
    @ActiveDate             DATE
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @NoDate DATE = CAST([crt].[PRICE_NODATE]() AS DATE);
    DECLARE @ABSQuantity NUMERIC(32,16) = abs(@Quantity);

    SELECT
        ta.RECID,
        ta.ITEMCODE,
        ta.ACCOUNTCODE,
        ta.ITEMRELATION,
        ta.ACCOUNTRELATION,
        ta.QUANTITYAMOUNTFROM,
        ta.QUANTITYAMOUNTTO,
        ta.FROMDATE,
        ta.TODATE,
        ta.AMOUNT,
        ta.CURRENCY,
        ta.PERCENT1,
        ta.PERCENT2,
        ta.SEARCHAGAIN,
        ta.PRICEUNIT,
        ta.RELATION,
        ta.UNITID,
        ta.MARKUP,
        ta.ALLOCATEMARKUP,
        ta.INVENTDIMID,
ta.MAXIMUMRETAILPRICE_IN AS MAXIMUMRETAILPRICEINDIA
    FROM [ax].PRICEDISCTABLE ta
INNER JOIN [ax].RETAILCHANNELTABLE AS c
ON c.INVENTLOCATIONDATAAREAID = ta.DATAAREAID AND c.RECID = @bi_ChannelId
    LEFT JOIN [ax].INVENTDIM invdim ON ta.INVENTDIMID = invdim.INVENTDIMID AND ta.DATAAREAID = c.INVENTLOCATIONDATAAREAID
    WHERE
        ta.RELATION = @Relation
        AND ta.ITEMCODE = @ItemCode
        AND ta.ITEMRELATION = @ItemRelation
        AND ta.ACCOUNTCODE = @AccountCode

        -- USES Tvp: CREATE TYPE FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE AS TABLE(ACCOUNTRELATION nvarchar(20) NOT NULL);
        AND (ta.ACCOUNTRELATION) IN (SELECT ar.ACCOUNTRELATION FROM @AccountRelations ar)

        AND ta.CURRENCY = @CurrencyCode
        AND ((@UnitId = '') OR (ta.UNITID = @UnitId))
        AND ta.QUANTITYAMOUNTFROM <= @ABSQuantity
        AND (ta.QUANTITYAMOUNTTO >= @ABSQuantity OR ta.QUANTITYAMOUNTTO = 0.0)
        AND ((ta.FROMDATE <= @ActiveDate OR ta.FROMDATE <= @NoDate)
                AND (ta.TODATE >= @ActiveDate OR ta.TODATE <= @NoDate))
        AND (invdim.INVENTCOLORID = @ColorId OR invdim.INVENTCOLORID = '')
        AND (invdim.INVENTSIZEID = @SizeId OR invdim.INVENTSIZEID = '')
        AND (invdim.INVENTSTYLEID = @StyleId OR invdim.INVENTSTYLEID = '')
        AND (invdim.CONFIGID = @ConfigId OR invdim.INVENTSTYLEID = '')

        -- ORDERBY CLAUSE MUST MATCH THAT IN AX TO ENSURE COMPATIBLE PRICING BEHAVIOR.
        -- SEE THE CLASS PRICEDISC.FINDPRICEAGREEMENT() AND TABLE PRICEDISCTABLE.PRICEDISCIDX
        ORDER BY ta.QUANTITYAMOUNTFROM, ta.RECID, ta.FROMDATE

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETTRADEAGREEMENTS]'
GO
-- End creating stored procedure [crt].[GETTRADEAGREEMENTS]


GRANT EXECUTE ON [crt].[GETTRADEAGREEMENTS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETTRADEAGREEMENTS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETSALESLINEDELIVERYOPTIONS]
PRINT N'Creating stored procedure [crt].[GETSALESLINEDELIVERYOPTIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSALESLINEDELIVERYOPTIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSALESLINEDELIVERYOPTIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSALESLINEDELIVERYOPTIONS].';
END
GO


ALTER PROCEDURE [crt].[GETSALESLINEDELIVERYOPTIONS]
    @bi_ChannelId                   BIGINT,
    @tvp_salesLineDeliveryOptions   [crt].[SALESLINEDELIVERYOPTIONSTABLETYPE]   READONLY
AS
BEGIN

    SET NOCOUNT ON

    SELECT DISTINCT SALESLINEID, RECID, CODE, TXT, MARKUPGROUP
    FROM @tvp_salesLineDeliveryOptions SDO
    INNER JOIN [crt].DELIVERYMODESEXPLODEDVIEW DV ON DV.CHANNELID = @bi_ChannelId
        AND DV.COUNTRYREGION = SDO.COUNTRYREGIONID
        AND DV.STATE = SDO.STATEID
        AND DV.ITEMID = SDO.ITEMID
        AND (DV.INVENTDIM = '' OR DV.INVENTDIM = ISNULL(NULLIF(SDO.VARIANTINVENTDIMID,''),DV.INVENTDIM))

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETSALESLINEDELIVERYOPTIONS]'
GO
-- End creating stored procedure [crt].[GETSALESLINEDELIVERYOPTIONS]


GRANT EXECUTE ON [crt].[GETSALESLINEDELIVERYOPTIONS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPERIODICDISCOUNTS]
PRINT N'Creating stored procedure [crt].[GETPERIODICDISCOUNTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPERIODICDISCOUNTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPERIODICDISCOUNTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPERIODICDISCOUNTS].';
END
GO


ALTER PROCEDURE [crt].[GETPERIODICDISCOUNTS]
    @bi_ChannelId                   BIGINT,
    @bi_ProductId                   BIGINT,
    @bi_DistinctProductVariantId    BIGINT,
    @tvp_StorePriceGroups           [crt].[RECORDIDTABLETYPE] READONLY,
    @nvc_CurrencyCode               NVARCHAR(3),
    @dt_ActiveDate                  DATETIME
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @NoDate date = CAST('1900-1-1' as date);

    SELECT
        pd.OFFERID,
        pd.NAME,
        pd.PERIODICDISCOUNTTYPE,
        pd.CONCURRENCYMODE,
        pd.ISDISCOUNTCODEREQUIRED,
        pd.VALIDATIONPERIODID,
        pd.DATEVALIDATIONTYPE,
        pd.VALIDFROM,
        pd.VALIDTO,
        pd.DISCOUNTTYPE,
        pd.DEALPRICEVALUE,
        pd.DISCOUNTPERCENTVALUE,
        pd.DISCOUNTAMOUNTVALUE,
        pd.NOOFLEASTEXPENSIVELINES,
        pd.NUMBEROFTIMESAPPLICABLE,
        pd.LINENUM,
        pd.DISCOUNTPERCENTORVALUE,

        ISNULL(mmol.LINEGROUP,'') AS LINEGROUP,
        ISNULL(mmol.DISCOUNTTYPE,'') AS MIXANDMATCHLINEDISCOUNTTYPE,
        ISNULL(mmol.NUMBEROFITEMSNEEDED,'') AS NUMBEROFITEMSNEEDED,

        ISNULL(dol.DISCOUNTMETHOD,0) AS DISCOUNTMETHOD,
        ISNULL(dol.DISCAMOUNT,0) AS DISCAMOUNT,
        ISNULL(dol.DISCPCT, 0) AS DISCPCT,
        ISNULL(dol.OFFERPRICE, 0) AS OFFERPRICE,
        ISNULL(dol.OFFERPRICEINCLTAX, 0) AS OFFERPRICEINCLTAX,

        ISNULL(uom.SYMBOL,'') AS SYMBOL,

        ISNULL(pd.COUNTNONDISCOUNTITEMS, 0) AS COUNTNONDISCOUNTITEMS
    FROM [crt].RETAILPERIODICDISCOUNTSFLATTENEDVIEW pd
INNER JOIN [ax].RETAILCHANNELTABLE AS c
ON c.INVENTLOCATIONDATAAREAID = pd.DATAAREAID AND c.RECID = @bi_ChannelId
    LEFT JOIN [ax].UNITOFMEASURE uom ON uom.RECID = pd.UNITOFMEASURE
    INNER JOIN [ax].RETAILGROUPMEMBERLINE rgl ON pd.RETAILGROUPMEMBERLINE = rgl.RECID
    LEFT JOIN [crt].RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW rpca ON rgl.CATEGORY = rpca.CATEGORY
    LEFT JOIN [ax].RETAILDISCOUNTLINEMIXANDMATCH mmol ON pd.DISCOUNTLINEID = mmol.RECID
    LEFT JOIN [ax].RETAILDISCOUNTLINEOFFER dol ON pd.DISCOUNTLINEID = dol.RECID
    INNER JOIN @tvp_StorePriceGroups spg ON pd.PRICEDISCGROUP = spg.RECID
    WHERE
      ((rgl.VARIANT != 0 AND rgl.VARIANT = @bi_DistinctProductVariantId) OR
       (rgl.VARIANT = 0 AND rgl.PRODUCT != 0 AND rgl.PRODUCT = @bi_ProductId) OR
       (rgl.VARIANT = 0 AND rgl.PRODUCT = 0 AND (rpca.PRODUCT = @bi_ProductId OR rpca.PRODUCT = @bi_DistinctProductVariantId)))

        AND (pd.STATUS = 1)
        AND (pd.PERIODICDISCOUNTTYPE != 3) -- Don't fetch promotions
        AND (pd.CURRENCYCODE = @nvc_CurrencyCode OR pd.CURRENCYCODE = '')

        AND ((pd.VALIDFROM <= @dt_ActiveDate OR pd.VALIDFROM <= @NoDate) AND (pd.VALIDTO >= @dt_ActiveDate OR pd.VALIDTO <= @NoDate))

    ORDER BY pd.OFFERID, pd.LINENUM

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPERIODICDISCOUNTS]'
GO
-- End creating stored procedure [crt].[GETPERIODICDISCOUNTS]


GRANT EXECUTE ON [crt].[GETPERIODICDISCOUNTS] TO [UsersRole];
GO
/**********************************************************************************
 *    FILE:         PurgeSales.sql
 *    DESCRIPTION:  Deletes rows from SalesTransaction table
 *    OWNER:        mperkins
 *    Copyright 2012 Microsoft Corporation. All Rights Reserved.
 **********************************************************************************/


-- Creating stored procedure [crt].[PURGESALES]
PRINT N'Creating stored procedure [crt].[PURGESALES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[PURGESALES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[PURGESALES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[PURGESALES].';
END
GO


ALTER PROCEDURE [crt].PURGESALES
    @f_PurgeOrder       BIT     = 1
   ,@i_RetentionDays    INT     = 1        --must be >= 1
   ,@i_BatchSize        INT     = 10000     --must be >= 1 and <= 10000
   ,@i_WaitSeconds      INT     = 2         --must be >= 1 and < 60
   ,@i_WaitRows         INT     = 10000     --must be > batch size
AS BEGIN
    SET NOCOUNT ON;

    --capture datetimes: 
    DECLARE @dt_CurrentDatetime         DATETIME;
    DECLARE @dt_RetentionDatetime       DATETIME;
    DECLARE @vc_ErrorHeader             VARCHAR(40);
    DECLARE @vc_Error                   VARCHAR(1000);
    DECLARE @vc_Success                 VARCHAR(1000);
    DECLARE @i_Error                    INT;
    DECLARE @i_Rowcount                 INT;
    DECLARE @i_ReturnCode               INT;
    DECLARE @bi_TableRowcount           BIGINT;
    DECLARE @bi_WaitTrigger             BIGINT;
    DECLARE @vc_WaitTime                VARCHAR(10);
    DECLARE @f_ExitLoop                 BIT;
    DECLARE @vc_TableName               VARCHAR(64);
    DECLARE @i_RowId                    INT;
    DECLARE @f_ExitInnerLoop            BIT;
    DECLARE @vc_InnerTableName          VARCHAR(64);
    DECLARE @i_InnerRowcount            INT;
    DECLARE @bi_InnerTableRowcount      BIGINT;
    DECLARE @bi_InnerWaitTrigger        BIGINT;
    DECLARE @t_TransactionList          TABLE
    (
        nvc_TransactionId   NVARCHAR(44) NOT NULL
    );


    SET @vc_ErrorHeader             = 'PurgeSales Hard Delete Handler: ';
    SET @bi_TableRowcount           = 0;
    SET @bi_WaitTrigger             = 0;
    SET @vc_Success                 = ''; --will be used for reporting the number of rows deleted.

    --protect against null being explicitly passed for the args
    SET @i_RetentionDays    = ISNULL(@i_RetentionDays, 1);
    SET @i_BatchSize        = ISNULL(@i_BatchSize, 500);
    SET @i_WaitSeconds      = ISNULL(@i_WaitSeconds, 2);
    SET @i_WaitRows         = ISNULL(@i_WaitRows, 2000);

    IF  @i_RetentionDays < 1 OR
        @i_BatchSize < 1 OR
        @i_BatchSize > 10000 OR
        @i_WaitSeconds < 1 OR 
        @i_WaitSeconds > 59 OR
        @i_WaitRows < 1 OR
        @i_WaitRows < @i_BatchSize
    BEGIN
        SET @vc_Error = @vc_ErrorHeader + 'Invalid parameters passed, cannot execute.';
        GOTO exit_label;
    END;    
    IF @@TRANCOUNT > 0
    BEGIN
        SET @vc_Error = @vc_ErrorHeader + 'Cannot call within a transaction!';
        GOTO exit_label;
    END;
    
    --set execution parameters
    SET @dt_CurrentDatetime         = GETUTCDATE();
    SET @dt_RetentionDatetime = DATEADD(DAY, -1 * @i_RetentionDays, @dt_CurrentDatetime);
    --handle single and double digit wait times:
    SET @vc_WaitTime = '00:00:' + RIGHT('0' + CONVERT(VARCHAR, @i_WaitSeconds), 2);

    SET @bi_TableRowcount = 0;
    SET @bi_WaitTrigger   = 0;
    SET @f_ExitLoop       = 0;
    
    --run deletes on this table
    WHILE (@f_ExitLoop = 0)
    BEGIN
        BEGIN TRANSACTION;
        
        DELETE FROM @t_TransactionList;

        IF (@f_PurgeOrder = 1)
        BEGIN
            SET @vc_TableName = 'SalesTransaction';

            WITH Limited (id)             
            AS
            (
                SELECT TOP (@i_BatchSize) TRANSACTIONID
                FROM [crt].SALESTRANSACTION WITH (ROWLOCK, UPDLOCK, READPAST)
                WHERE 
                    MODIFIEDDATETIME < @dt_RetentionDatetime
            )
            DELETE [crt].SALESTRANSACTION
            OUTPUT DELETED.TRANSACTIONID INTO @t_TransactionList
            FROM [crt].SALESTRANSACTION el
            INNER JOIN Limited l on l.id = el.TRANSACTIONID
            OPTION (MAXDOP 1);
        END
        ELSE
        BEGIN
            SET @vc_TableName = 'RETAILTRANSACTIONTABLE';
            INSERT INTO @t_TransactionList 
                SELECT TOP (@i_BatchSize) TRANSACTIONID
                FROM [ax].RETAILTRANSACTIONTABLE WITH (ROWLOCK, UPDLOCK, READPAST)
                WHERE 
                    MODIFIEDDATETIME < @dt_RetentionDatetime
        END
        SELECT @i_Error = @@ERROR, @i_Rowcount = @@ROWCOUNT;

        IF @i_Error <> 0
        BEGIN
            ROLLBACK;
            SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_TableName +
                '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
            GOTO exit_label;
        END;


        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RETAILTRANSACTIONTABLE';
        -- PK TRANSACTIONID
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONTABLE
            FROM [ax].RETAILTRANSACTIONTABLE el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;

        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RETAILTRANSACTIONSALESTRANS';
        -- PK TRANSACTIONID
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONTABLE
            FROM [ax].RETAILTRANSACTIONTABLE el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;
        
        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RetailTransactionMarkupTrans';
        -- PK DATAAREAID,SALELINENUM,TRANSACTIONID,TERMINALID,STORE,MARKUPLINENUM,CHANNEL
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONMARKUPTRANS
            FROM [ax].RETAILTRANSACTIONMARKUPTRANS el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;
        
        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RetailTransactionTaxTrans';
        -- PK DATAAREAID,TERMINALID,STOREID,TRANSACTIONID,SALELINENUM,TAXCODE,CHANNEL
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONTAXTRANS
            FROM [ax].RETAILTRANSACTIONTAXTRANS el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;
        
        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RetailTransactionPaymentTrans';
        -- PK DATAAREAID,STORE,TERMINAL,TRANSACTIONID,LINENUM,CHANNEL
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONPAYMENTTRANS
            FROM [ax].RETAILTRANSACTIONPAYMENTTRANS el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;
        
        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RetailTransactionAttributeTrans';
        -- PK DATAAREAID,NAME,TRANSACTIONID,TERMINAL,STORE,CHANNEL
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONATTRIBUTETRANS
            FROM [ax].RETAILTRANSACTIONATTRIBUTETRANS el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;
        
        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RETAILTRANSACTIONADDRESSTRANS';
        -- PK DATAAREAID,TRANSACTIONID,TERMINAL,STORE,SALELINENUM,CHANNEL
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONADDRESSTRANS
            FROM [ax].RETAILTRANSACTIONADDRESSTRANS el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;
        
        SET @bi_InnerTableRowcount = 0;
        SET @bi_InnerWaitTrigger   = 0;
        SET @f_ExitInnerLoop = 0;
        SET @vc_InnerTableName = 'RETAILTRANSACTIONDISCOUNTTRANS';
        -- PK DATAAREAID,STOREID,TERMINALID,TRANSACTIONID,SALELINENUM,PERIODICDISCOUNTOFFERID,CHANNEL
        WHILE (@f_ExitInnerLoop = 0)
        BEGIN

            DELETE [ax].RETAILTRANSACTIONDISCOUNTTRANS
            FROM [ax].RETAILTRANSACTIONDISCOUNTTRANS el
            INNER JOIN @t_TransactionList l on l.nvc_TransactionId = el.TRANSACTIONID
            OPTION (MAXDOP 1);

            SELECT @i_Error = @@ERROR, @i_InnerRowcount = @@ROWCOUNT;

            IF @i_Error <> 0
            BEGIN
                ROLLBACK;
                SET @vc_Error = @vc_ErrorHeader + 'Error deleting from table ' + @vc_InnerTableName +
                    '. @@ERROR value was ' + CONVERT(VARCHAR, @i_Error);
                GOTO exit_label;
            END;

            IF @i_InnerRowcount < @i_BatchSize
            BEGIN
                SET @f_ExitInnerLoop = 1;
            END;
            ELSE
            BEGIN
                IF @bi_InnerWaitTrigger <> @bi_InnerTableRowcount/@i_WaitRows
                BEGIN
                    WAITFOR DELAY @vc_WaitTime;
                END;
                SET @bi_InnerWaitTrigger = @bi_InnerTableRowcount/@i_WaitRows;
            END;
        END;

        COMMIT;
        --keep track of how many rows we've deleted from this table.
        SET @bi_TableRowcount = @bi_TableRowcount + @i_Rowcount;
        IF @i_Rowcount < @i_BatchSize
        BEGIN
            SET @f_ExitLoop = 1;
            SET @vc_Success = 
                ' Job started deleting from ' + @vc_TableName + 
                ' at ' + CONVERT(VARCHAR, @dt_CurrentDatetime, 109) + 
                ' and ended at ' + CONVERT(VARCHAR, GETUTCDATE(), 109) + 
                '. Deleted ' + convert(varchar, @bi_TableRowcount) + ' rows. ';
        END;
        ELSE
        BEGIN
            IF @bi_WaitTrigger <> @bi_TableRowcount/@i_WaitRows
            BEGIN
                WAITFOR DELAY @vc_WaitTime;
            END;
            SET @bi_WaitTrigger = @bi_TableRowcount/@i_WaitRows;
        END;
    END;
    
exit_label:
    IF @vc_Error IS NOT NULL
    BEGIN
        RAISERROR(@vc_Error, 16, 1) WITH LOG;
    END;
    ELSE
    BEGIN
        RAISERROR(@vc_Success, 10, 1) WITH LOG;
    END;
END;
GO


GO
PRINT N'Finished creating stored procedure [crt].[PURGESALES]'
GO
-- End creating stored procedure [crt].[PURGESALES]


GRANT EXECUTE ON [crt].[PURGESALES] TO [UsersRole]
GO

-- Creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE]
PRINT N'Creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE].';
END
GO


ALTER PROCEDURE [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE]
    @tvp_ListingPublishStatus[crt].[LISTINGPUBLISHSTATUSTABLETYPE] READONLY
AS
BEGIN
    SET NOCOUNT ON

    MERGE [ax].RETAILLISTINGSTATUSLOG AS TARGET
    USING @tvp_ListingPublishStatus AS SOURCE
    ON
TARGET.PRODUCT = SOURCE.PRODUCT
AND TARGET.CATALOG = SOURCE.CATALOG
AND TARGET.CHANNEL = SOURCE.CHANNEL
        AND TARGET.LISTINGMODIFIEDDATETIME = SOURCE.LISTINGMODIFIEDDATETIME
    WHEN MATCHED THEN
        UPDATE
        SET ACTIONSTATUS = SOURCE.ACTIONSTATUS,
            CHANNELLISTINGID = SOURCE.CHANNELLISTINGID,
            STATUSDATETIME = SOURCE.STATUSDATETIME,
            STATUSMESSAGE = SOURCE.STATUSMESSAGE,
            CHANNELBATCHID = SOURCE.CHANNELBATCHID,
            CHANNELSTATE = SOURCE.CHANNELSTATE
    WHEN NOT MATCHED THEN
        INSERT
        (
            [ACTIONSTATUS],
            [APPLIEDACTION],
[CATALOG],
            [CHANNEL],
            [CHANNELLISTINGID],
            [LISTINGMODIFIEDDATETIME],
            [LISTINGMODIFIEDDATETIMETZID],
[PRODUCT],
            [PROCESSED],
            [STATUSDATETIME],
            [STATUSDATETIMETZID],
            [STATUSMESSAGE],
            [CHANNELBATCHID],
            [CHANNELSTATE]
        )
        VALUES
        (
            SOURCE.[ACTIONSTATUS],
            SOURCE.[APPLIEDACTION],
SOURCE.[CATALOG],
            SOURCE.[CHANNEL],
            SOURCE.[CHANNELLISTINGID],
            SOURCE.[LISTINGMODIFIEDDATETIME],
            SOURCE.[LISTINGMODIFIEDDATETIMETZID],
SOURCE.[PRODUCT],
            SOURCE.[PROCESSED],
            SOURCE.[STATUSDATETIME],
            SOURCE.[STATUSDATETIMETZID],
            SOURCE.[STATUSMESSAGE],
            SOURCE.[CHANNELBATCHID],
            SOURCE.[CHANNELSTATE]
        );
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE]'
GO
-- End creating stored procedure [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE]


GRANT EXECUTE ON [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[INSERTPUBLISHSTATUSFORCURRENTLISTINGPAGE] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETALLPRICETRADEAGREEMENTS]
PRINT N'Creating stored procedure [crt].[GETALLPRICETRADEAGREEMENTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETALLPRICETRADEAGREEMENTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETALLPRICETRADEAGREEMENTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETALLPRICETRADEAGREEMENTS].';
END
GO


ALTER PROCEDURE [crt].[GETALLPRICETRADEAGREEMENTS]
    @bi_ChannelId       BIGINT,
    @ItemIds            [crt].[STRINGIDTABLETYPE] READONLY,
    @PriceGroups        [crt].[PRICEACCOUNTRELATIONSTABLETYPE] READONLY,
    @Customer           nvarchar(20),
    @MinDate            DATE,
    @MaxDate            DATE,
@nvc_CurrencyCode   NVARCHAR(3)
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @NoDate DATE = CAST([crt].[PRICE_NODATE]() AS DATE);

    SELECT
        ta.RECID,
        ta.ITEMCODE,
        ta.ACCOUNTCODE,
        ta.ITEMRELATION,
        ta.ACCOUNTRELATION,
        ta.QUANTITYAMOUNTFROM,
        ta.QUANTITYAMOUNTTO,
        ta.FROMDATE,
        ta.TODATE,
        ta.AMOUNT,
        ta.CURRENCY,
        ta.PERCENT1,
        ta.PERCENT2,
        ta.SEARCHAGAIN,
        ta.PRICEUNIT,
        ta.RELATION,
        ta.UNITID,
        ta.MARKUP,
        ta.ALLOCATEMARKUP,
        ta.INVENTDIMID,
ta.MAXIMUMRETAILPRICE_IN AS MAXIMUMRETAILPRICEINDIA,
        invdim.CONFIGID,
        invdim.INVENTCOLORID,
        invdim.INVENTSIZEID,
        invdim.INVENTSTYLEID
    FROM [ax].PRICEDISCTABLE ta
INNER JOIN [ax].RETAILCHANNELTABLE AS c
ON c.INVENTLOCATIONDATAAREAID = ta.DATAAREAID AND c.RECID = @bi_ChannelId
    LEFT JOIN [ax].INVENTDIM invdim ON ta.INVENTDIMID = invdim.INVENTDIMID AND invdim.DATAAREAID = c.INVENTLOCATIONDATAAREAID
    WHERE
        -- agreement is of price sales
        ta.RELATION = 4
AND ta.CURRENCY = @nvc_CurrencyCode 

        -- and currently active
        AND ((ta.FROMDATE <= @MinDate OR ta.FROMDATE <= @NoDate)
                AND (ta.TODATE >= @MaxDate OR ta.TODATE <= @NoDate))

        -- and customer/group relation matches
        AND
        (
         -- account code is group and relation is in the price groups
         ((ta.ACCOUNTCODE = 1) AND
            (ta.ACCOUNTRELATION IN (SELECT ar.ACCOUNTRELATION FROM @PriceGroups ar)))
         OR
         -- or account code is customer and customer is on the agreement
         ((ta.ACCOUNTCODE = 0) AND (ta.ACCOUNTRELATION = @Customer))
         OR
         -- or account code is ALL customers
         ((ta.ACCOUNTCODE = 2))
        )

        -- and item/group relation matches
        AND
        (
         -- item code is one of the items passed in
         ((ta.ITEMCODE = 0) AND (ta.ITEMRELATION in (SELECT i.STRINGID FROM @ItemIds i)))
        )

  -- and warehouse is either for all or for current channel
  AND
  (
   invdim.INVENTLOCATIONID = '' OR (invdim.INVENTLOCATIONID = c.INVENTLOCATION)
  )

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETALLPRICETRADEAGREEMENTS]'
GO
-- End creating stored procedure [crt].[GETALLPRICETRADEAGREEMENTS]


GRANT EXECUTE ON [crt].[GETALLPRICETRADEAGREEMENTS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETALLPRICETRADEAGREEMENTS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETPRICEADJUSTMENTSFORITEMS]
PRINT N'Creating stored procedure [crt].[GETPRICEADJUSTMENTSFORITEMS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPRICEADJUSTMENTSFORITEMS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPRICEADJUSTMENTSFORITEMS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPRICEADJUSTMENTSFORITEMS].';
END
GO


ALTER PROCEDURE [crt].[GETPRICEADJUSTMENTSFORITEMS]
    @bi_ChannelId       BIGINT,
    @items              [crt].[ITEMVARIANTINVENTDIMTABLETYPE] READONLY,
    @priceGroups        [crt].[PRICEGROUPTABLETYPE] READONLY,
    @fromDate           DATE,
    @toDate             DATE
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @NoDate DATE = CAST([crt].[PRICE_NODATE]() AS DATE);
    DECLARE @Never DATE = CAST('2154-12-31' AS DATE);
DECLARE @nvc_DataAreaId NVARCHAR(4);
SELECT @nvc_DataAreaId = INVENTLOCATIONDATAAREAID from [ax].RETAILCHANNELTABLE where RECID = @bi_ChannelId

    -- fetch price group record ids or lookup if missing
    DECLARE @priceGroupRecIds TABLE (PRICEGROUP BIGINT);
    INSERT INTO @priceGroupRecIds (PRICEGROUP)
    SELECT (CASE(pa.PRICEGROUP)
        WHEN 0
        THEN pg.RECID
        ELSE pa.PRICEGROUP
        END)
    FROM @priceGroups AS pa
    INNER JOIN [ax].PRICEDISCGROUP pg ON pg.GROUPID = pa.GROUPID AND DATAAREAID = @nvc_DataAreaId

    -- resolve item Ids and dimensions into product and variant Ids
    DECLARE @itemIds TABLE (ITEMID nvarchar(20), VARIANTINVENTDIMID nvarchar(20), PRODUCT bigint, DISTINCTPRODUCTVARIANT bigint)
    INSERT INTO @itemIds
    SELECT
        it.ITEMID,
        it.VARIANTINVENTDIMID,
        ISNULL(i.PRODUCT,0),
        ISNULL(idc.DISTINCTPRODUCTVARIANT,0)
    FROM @items AS it
    LEFT JOIN [ax].INVENTTABLE i ON i.ITEMID = it.ITEMID AND i.DATAAREAID = @nvc_DataAreaId
    LEFT JOIN [ax].INVENTDIMCOMBINATION idc ON idc.ITEMID = it.ITEMID AND idc.INVENTDIMID = it.VARIANTINVENTDIMID AND idc.DATAAREAID = @nvc_DataAreaId

    -- fetch actual price adjustments
    SELECT DISTINCT
        promo.OFFERID,
        promo.VALIDFROM,
        promo.VALIDTO,
        promo.CONCURRENCYMODE,
        promo.DATEVALIDATIONTYPE,
        promo.VALIDATIONPERIODID,
        promoOffer.DISCOUNTMETHOD,
        promoOffer.OFFERPRICE,
        promoOffer.OFFERPRICEINCLTAX,
        promoOffer.DISCPCT,
        promoOffer.DISCAMOUNT,
        promoOffer.RECID,
        it.ITEMID,
        it.VARIANTINVENTDIMID AS INVENTDIMID,
uom.SYMBOL
    FROM [ax].RETAILPERIODICDISCOUNT promo
INNER JOIN [ax].RETAILCHANNELTABLE AS c
ON c.INVENTLOCATIONDATAAREAID = promo.DATAAREAID AND c.RECID = @bi_ChannelId
    INNER JOIN [ax].RETAILDISCOUNTPRICEGROUP rdpg on rdpg.OFFERID = promo.OFFERID AND rdpg.DATAAREAID = promo.DATAAREAID
    INNER JOIN @priceGroupRecIds pg ON rdpg.PRICEDISCGROUP = pg.PRICEGROUP 
    INNER JOIN [ax].RETAILPERIODICDISCOUNTLINE promoLine ON promo.OFFERID = promoLine.OFFERID AND promo.DATAAREAID = promoLine.DATAAREAID
    INNER JOIN [ax].RETAILDISCOUNTLINEOFFER promoOffer ON promoLine.RECID = promoOffer.RECID
    INNER JOIN [ax].RETAILGROUPMEMBERLINE rgl ON promoLine.RETAILGROUPMEMBERLINE = rgl.RECID
    LEFT JOIN [crt].RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW rpca ON rgl.CATEGORY = rpca.CATEGORY
    LEFT JOIN [ax].UNITOFMEASURE uom ON uom.RECID = promoLine.UNITOFMEASURE
    INNER JOIN @itemIds it ON
        ((rgl.VARIANT != 0 AND rgl.VARIANT = it.DISTINCTPRODUCTVARIANT) OR
        (rgl.VARIANT = 0 AND rgl.PRODUCT != 0 AND rgl.PRODUCT = it.PRODUCT) OR
        (rgl.VARIANT = 0 AND rgl.PRODUCT = 0 AND
        (rpca.PRODUCT = it.PRODUCT OR rpca.PRODUCT = it.DISTINCTPRODUCTVARIANT)))
    WHERE promo.STATUS = 1
        AND promo.PERIODICDISCOUNTTYPE = 3 -- get only price adjustments
        AND (promo.VALIDFROM <= @fromDate OR promo.VALIDFROM <= @NoDate)
        AND (promo.VALIDTO >= @toDate OR promo.VALIDTO >= @Never)
AND promo.DATAAREAID = @nvc_DataAreaId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPRICEADJUSTMENTSFORITEMS]'
GO
-- End creating stored procedure [crt].[GETPRICEADJUSTMENTSFORITEMS]


GRANT EXECUTE ON [crt].[GETPRICEADJUSTMENTSFORITEMS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETPRICEADJUSTMENTSFORITEMS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETNEXTNUMBERSEQUENCEVALUE]
PRINT N'Creating stored procedure [crt].[GETNEXTNUMBERSEQUENCEVALUE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETNEXTNUMBERSEQUENCEVALUE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETNEXTNUMBERSEQUENCEVALUE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETNEXTNUMBERSEQUENCEVALUE].';
END
GO


ALTER PROCEDURE [crt].[GETNEXTNUMBERSEQUENCEVALUE]
    @bi_ChannelId       BIGINT,
    @i_TypeId           INT,
    @nvc_StoreId        NVARCHAR(10),
    @nvc_TerminalId     NVARCHAR(10) = '',
    @bi_NextValue       BIGINT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @bi_FirstValue  BIGINT;
    DECLARE @nvc_DataAreaId NVARCHAR(4);

    -- Initialize variables
    SET @bi_NextValue = -1;
    SET @bi_FirstValue = 1;

    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct
        WHERE rct.RECID = @bi_ChannelId

    -- Try to find the number sequence
    IF NOT EXISTS
    (
        SELECT *
        FROM [ax].RETAILPOSSEEDDATA
        WHERE DATATYPE = @i_TypeId AND STORENUMBER = @nvc_StoreId AND TERMINALID = @nvc_TerminalId AND DATAAREAID = @nvc_DataAreaId
    )
    -- Insert the number sequence if not exists
    BEGIN
        -- since we are taking @bi_FirstValue, the next available number will be (@bi_FirstValue + 1)
        INSERT INTO [ax].RETAILPOSSEEDDATA (DATATYPE, STORENUMBER, TERMINALID, DATAAREAID, DATAVALUE)
        VALUES (@i_TypeId, @nvc_StoreId, @nvc_TerminalId, @nvc_DataAreaId, @bi_FirstValue + 1);

        SET @bi_NextValue = @bi_FirstValue;
    END
    ELSE
    -- Update the number sequence value
    BEGIN
        -- we first reserve the next available number, then we increment it
        UPDATE [ax].RETAILPOSSEEDDATA
        SET
            @bi_NextValue = DATAVALUE,
            DATAVALUE = DATAVALUE + 1
        WHERE
            DATATYPE = @i_TypeId AND
            STORENUMBER = @nvc_StoreId AND
            TERMINALID = @nvc_TerminalId AND
            DATAAREAID = @nvc_DataAreaId;
    END;

    RETURN 0;
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETNEXTNUMBERSEQUENCEVALUE]'
GO
-- End creating stored procedure [crt].[GETNEXTNUMBERSEQUENCEVALUE]


GRANT EXECUTE ON [crt].[GETNEXTNUMBERSEQUENCEVALUE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS]
PRINT N'Creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS].';
END
GO


ALTER PROCEDURE [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS]
    @bi_ChannelId                   BIGINT,
    @TVP_RetailStockCountJournal    [crt].[RETAILSTOCKCOUNTJOURNALSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;


    -- UPSERT INTO THE RETAILSTOCKCOUNTJOURNALS
    MERGE INTO [crt].[RETAILSTOCKCOUNTJOURNALS]
    USING @TVP_RetailStockCountJournal AS SOURCE
    ON
        RETAILSTOCKCOUNTJOURNALS.JOURNALID = SOURCE.JOURNALID
    WHEN MATCHED THEN
        UPDATE
        SET
            RECID = SOURCE.RECID,
            DESCRIPTION = SOURCE.DESCRIPTION
    WHEN NOT MATCHED THEN
        INSERT
        (
            [RECID],
            [JOURNALID],
            [DESCRIPTION]
        )
        VALUES
        (
            SOURCE.RECID,
            SOURCE.JOURNALID,
            SOURCE.DESCRIPTION
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;


    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS]'
GO
-- End creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS]


GRANT EXECUTE ON [crt].[CREATEUPDATERETAILSTOCKCOUNTJOURNALS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNT]
PRINT N'Creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[CREATEUPDATERETAILSTOCKCOUNT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[CREATEUPDATERETAILSTOCKCOUNT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[CREATEUPDATERETAILSTOCKCOUNT].';
END
GO


ALTER PROCEDURE [crt].[CREATEUPDATERETAILSTOCKCOUNT]
    @bi_ChannelId                   BIGINT,
    @TVP_RetailStockCount           [crt].[RETAILSTOCKCOUNTTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;


    -- UPSERT INTO THE RETAILSTOCKCOUNT
    MERGE INTO [crt].[RETAILSTOCKCOUNT]
    USING @TVP_RetailStockCount AS SOURCE
    ON
        RETAILSTOCKCOUNT.[JOURNALID] = SOURCE.[JOURNALID] AND
        RETAILSTOCKCOUNT.[ITEMID] = SOURCE.[ITEMID] AND
(SOURCE.[INVENTSIZEID] IS NULL OR RETAILSTOCKCOUNT.[INVENTSIZEID] = SOURCE.[INVENTSIZEID]) AND
        (SOURCE.[INVENTCOLORID] IS NULL OR RETAILSTOCKCOUNT.[INVENTCOLORID] = SOURCE.[INVENTCOLORID]) AND
        (SOURCE.[INVENTSTYLEID] IS NULL OR RETAILSTOCKCOUNT.[INVENTSTYLEID] = SOURCE.[INVENTSTYLEID]) AND
        (SOURCE.[CONFIGID] IS NULL OR RETAILSTOCKCOUNT.[CONFIGID] = SOURCE.[CONFIGID])
    WHEN MATCHED THEN
        UPDATE
        SET
            OPERATIONTYPE = SOURCE.[OPERATIONTYPE]
            ,ITEMNAME = SOURCE.[ITEMNAME]
            ,COUNTED = SOURCE.[COUNTED]
            ,QUANTITY = SOURCE.[QUANTITY]
            ,UNIT = SOURCE.[UNIT]
            ,USERID = SOURCE.[USERID]
            ,TERMINALID = SOURCE.[TERMINALID]
            ,COUNTDATE = SOURCE.[COUNTDATE]
            ,STATUS = SOURCE.[STATUS]
            ,INVENTSIZEID = SOURCE.[INVENTSIZEID]
            ,INVENTCOLORID = SOURCE.[INVENTCOLORID]
            ,INVENTSTYLEID = SOURCE.[INVENTSTYLEID]
            ,CONFIGID = SOURCE.[CONFIGID]
            ,TRACKINGGUID = SOURCE.[TRACKINGGUID]

    WHEN NOT MATCHED THEN
        INSERT
        (
            [RECID],
            [JOURNALID],
            [OPERATIONTYPE],
            [ITEMID],
            [ITEMNAME],
            [COUNTED],
            [QUANTITY],
            [UNIT],
            [USERID],
            [TERMINALID],
            [COUNTDATE],
            [STATUS],
            [INVENTSIZEID],
            [INVENTCOLORID],
            [INVENTSTYLEID],
            [CONFIGID],
            [TRACKINGGUID]
        )
        VALUES
        (
            SOURCE.[RECID],
            SOURCE.[JOURNALID],
            SOURCE.[OPERATIONTYPE],
            SOURCE.[ITEMID],
            SOURCE.[ITEMNAME],
            SOURCE.[COUNTED],
            SOURCE.[QUANTITY],
            SOURCE.[UNIT],
            SOURCE.[USERID],
            SOURCE.[TERMINALID],
            SOURCE.[COUNTDATE],
            SOURCE.[STATUS],
            SOURCE.[INVENTSIZEID],
            SOURCE.[INVENTCOLORID],
            SOURCE.[INVENTSTYLEID],
            SOURCE.[CONFIGID],
            SOURCE.[TRACKINGGUID]
        );

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNT]'
GO
-- End creating stored procedure [crt].[CREATEUPDATERETAILSTOCKCOUNT]


GRANT EXECUTE ON [crt].[CREATEUPDATERETAILSTOCKCOUNT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETESTOCKCOUNTJOURNALS]
PRINT N'Creating stored procedure [crt].[DELETESTOCKCOUNTJOURNALS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETESTOCKCOUNTJOURNALS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETESTOCKCOUNTJOURNALS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETESTOCKCOUNTJOURNALS].';
END
GO


ALTER PROCEDURE [crt].[DELETESTOCKCOUNTJOURNALS]
    @bi_ChannelId       BIGINT,
    @tvp_JournalIds     [crt].[STRINGIDTABLETYPE]READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Delete the stock count journal from Journal table.
    DELETE RSCJ 
FROM [crt].[RETAILSTOCKCOUNTJOURNALS] RSCJ 
INNER JOIN @tvp_JournalIds TVPJI 
ON RSCJ.JOURNALID = TVPJI.STRINGID

    -- Delete all the transactions from RetailStockCount table.
    DELETE RSC 
FROM [crt].[RETAILSTOCKCOUNT] RSC 
INNER JOIN @tvp_JournalIds TVPJI 
ON RSC.JOURNALID = TVPJI.STRINGID

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
    SET NOCOUNT OFF
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETESTOCKCOUNTJOURNALS]'
GO
-- End creating stored procedure [crt].[DELETESTOCKCOUNTJOURNALS]


GRANT EXECUTE ON [crt].[DELETESTOCKCOUNTJOURNALS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETESTOCKCOUNTTRANSACTIONS]
PRINT N'Creating stored procedure [crt].[DELETESTOCKCOUNTTRANSACTIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETESTOCKCOUNTTRANSACTIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETESTOCKCOUNTTRANSACTIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETESTOCKCOUNTTRANSACTIONS].';
END
GO


ALTER PROCEDURE [crt].[DELETESTOCKCOUNTTRANSACTIONS]
    @bi_ChannelIdBIGINT,
    @nvc_JournalIdNVARCHAR(50),
    @nvc_ItemIdNVARCHAR(20),
@nvc_InventSizeIdNVARCHAR(20) = NULL,
@nvc_InventColorIdNVARCHAR(20) = NULL,
@nvc_InventStyleIdNVARCHAR(20) = NULL,
@nvc_ConfigIdNVARCHAR(20) = NULL
AS
BEGIN

    SET NOCOUNT ON
DECLARE @nvc_InventSizeIdIsNull BIT = CASE WHEN (@nvc_InventSizeId IS NULL OR DATALENGTH(LTRIM(RTRIM(@nvc_InventSizeId))) = 0) THEN 1 ELSE 0 END
DECLARE @nvc_InventColorIdIsNull BIT = CASE WHEN (@nvc_InventColorId IS NULL OR DATALENGTH(LTRIM(RTRIM(@nvc_InventColorId))) = 0) THEN 1 ELSE 0 END
DECLARE @nvc_InventStyleIdIsNull BIT = CASE WHEN (@nvc_InventStyleId IS NULL OR DATALENGTH(LTRIM(RTRIM(@nvc_InventStyleId))) = 0) THEN 1 ELSE 0 END
DECLARE @nvc_ConfigIdIsNull BIT = CASE WHEN (@nvc_ConfigId IS NULL OR DATALENGTH(LTRIM(RTRIM(@nvc_ConfigId))) = 0) THEN 1 ELSE 0 END

    IF (@nvc_ItemId IS NULL OR @nvc_ItemId = '')
    BEGIN
        DELETE FROM [crt].[RETAILSTOCKCOUNT] WHERE JOURNALID = @nvc_JournalId 
    END
    ELSE
    BEGIN
        DELETEFROM [crt].[RETAILSTOCKCOUNT] 
WHEREJOURNALID = @nvc_JournalId
ANDITEMID = @nvc_ItemId
AND(@nvc_InventSizeIdIsNull = 1 OR INVENTSIZEID = @nvc_InventSizeId)
AND(@nvc_InventColorIdIsNull = 1 OR INVENTCOLORID = @nvc_InventColorId)
AND(@nvc_InventStyleIdIsNull = 1 OR INVENTSTYLEID = @nvc_InventStyleId)
AND(@nvc_ConfigIdIsNull = 1 OR CONFIGID = @nvc_ConfigId)
    END

    SET NOCOUNT OFF
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETESTOCKCOUNTTRANSACTIONS]'
GO
-- End creating stored procedure [crt].[DELETESTOCKCOUNTTRANSACTIONS]


GRANT EXECUTE ON [crt].[DELETESTOCKCOUNTTRANSACTIONS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW]
PRINT N'Creating stored procedure [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW].';
END
GO


ALTER PROCEDURE [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW]
    @bi_ChannelId       BIGINT,
    @COUNT              INT,
    @LASTSYNCVERSION    BIGINT = 0
AS
BEGIN
    SET NOCOUNT ON

    IF (@COUNT IS NULL)
    BEGIN
        RAISERROR (N'NUMBER OF RECORDS TO RETRIEVE IS MANDATORY', 16, 1)
        RETURN;
    END

    IF (@LASTSYNCVERSION IS NULL)
    BEGIN
        RAISERROR (N'VERSION OF LAST SYNCHRONIZATION IS MANDATORY', 16, 1)
        RETURN;
    END

    SELECT TOP(@COUNT)
        SPV.PACKINGSLIPID,
        SPV.SALESID,
        SPV.CHANNEL,
        SPV.TRANSACTIONID,
        SPV.SHIPCARRIERID,
        SPV.CARRIERNAME,
        SPV.SHIPDATE,
        SPV.TRACKINGNUMBER,
        CAST(SPV.ROWVERSION as BIGINT) as SEQUENCE
    FROM [crt].SHIPMENTSVIEW SPV
    WHERE
        SPV.CHANNEL = @bi_ChannelId
        AND SPV.ROWVERSION > @LASTSYNCVERSION
    ORDER BY SPV.ROWVERSION ASC

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW]'
GO
-- End creating stored procedure [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW]


GRANT EXECUTE ON [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETFORINCREMENTALSYNC_SHIPMENTSVIEW] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETREPORTCONFIGBYID]
PRINT N'Creating stored procedure [crt].[GETREPORTCONFIGBYID]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETREPORTCONFIGBYID]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETREPORTCONFIGBYID] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETREPORTCONFIGBYID].';
END
GO


ALTER PROCEDURE [crt].[GETREPORTCONFIGBYID]
    @tvp_QueryResultSettings    [crt].[QUERYRESULTSETTINGSTYPE] READONLY,
    @bi_ChannelId               BIGINT,
    @nvc_ReportId               NVARCHAR(100),
    @nvc_UserId                 NVARCHAR(25)
AS
BEGIN
    SET NOCOUNT ON

    -- Paging is disabled for reports which is why @tvp_QueryResultSettings remains unused.
SELECT
        RCP.REPORTID AS REPORTID,
        RCP.POSPERMISSIONGROUPID AS ROLEALLOWED,
        RCP.REPORTDEFINITIONXML AS REPORTDEFINITIONXML,
RST.STAFFID
FROM [ax].HCMWORKER HW WITH (NOLOCK)
INNER JOIN [ax].HCMPOSITIONWORKERASSIGNMENT PWA WITH (NOLOCK) ON PWA.WORKER = HW.RECID
INNER JOIN [ax].HCMPOSITION POS WITH (NOLOCK) ON POS.RECID = PWA.POSITION
INNER JOIN [ax].HCMPOSITIONDETAIL PD WITH (NOLOCK) ON PD.POSITION = POS.RECID
INNER JOIN [ax].HCMJOB HJ WITH (NOLOCK) ON HJ.RECID = PD.JOB
INNER JOIN [ax].RETAILJOBPOSPERMISSIONGROUP JP WITH (NOLOCK) ON JP.JOB = HJ.RECID
INNER JOIN [ax].RETAILPOSPERMISSIONGROUP PG WITH (NOLOCK) ON PG.RECID = JP.RETAILPOSPERMISSIONGROUP
INNER JOIN [crt].RETAILCHANNELREPORTVIEW RCP WITH (NOLOCK) ON RCP.POSPERMISSIONGROUPID = PG.POSPERMISSIONGROUPID
INNER JOIN [ax].RETAILSTAFFTABLE RST WITH (NOLOCK) ON RST.STAFFID = HW.PERSONNELNUMBER
WHERE RCP.REPORTID = @nvc_ReportId AND RST.STAFFID = @nvc_UserId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETREPORTCONFIGBYID]'
GO
-- End creating stored procedure [crt].[GETREPORTCONFIGBYID]


GRANT EXECUTE ON [crt].[GETREPORTCONFIGBYID] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETREPORTCONFIGURATION]
PRINT N'Creating stored procedure [crt].[GETREPORTCONFIGURATION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETREPORTCONFIGURATION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETREPORTCONFIGURATION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETREPORTCONFIGURATION].';
END
GO


ALTER PROCEDURE [crt].[GETREPORTCONFIGURATION]
    @tvp_QueryResultSettings [crt].[QUERYRESULTSETTINGSTYPE] READONLY,
    @bi_ChannelId           BIGINT,
    @nvc_UserId            NVARCHAR(25)
AS
BEGIN
    SET NOCOUNT ON
SELECT
    RCP.REPORTID AS REPORTID,
    RCP.POSPERMISSIONGROUPID AS ROLEALLOWED,
    RCP.REPORTDEFINITIONXML AS REPORTDEFINITIONXML,
RST.STAFFID
    FROM [ax].HCMWORKER HW WITH (NOLOCK)
INNER JOIN [ax].HCMPOSITIONWORKERASSIGNMENT PWA WITH (NOLOCK) ON PWA.WORKER = HW.RECID
INNER JOIN [ax].HCMPOSITION POS WITH (NOLOCK) ON POS.RECID = PWA.POSITION
INNER JOIN [ax].HCMPOSITIONDETAIL PD WITH (NOLOCK) ON PD.POSITION = POS.RECID
INNER JOIN [ax].HCMJOB HJ WITH (NOLOCK) ON HJ.RECID = PD.JOB
INNER JOIN [ax].RETAILJOBPOSPERMISSIONGROUP JP WITH (NOLOCK) ON JP.JOB = HJ.RECID
INNER JOIN [ax].RETAILPOSPERMISSIONGROUP PG WITH (NOLOCK) ON PG.RECID = JP.RETAILPOSPERMISSIONGROUP
INNER JOIN [crt].RETAILCHANNELREPORTVIEW RCP WITH (NOLOCK) ON RCP.POSPERMISSIONGROUPID = PG.POSPERMISSIONGROUPID
INNER JOIN [ax].RETAILSTAFFTABLE RST WITH (NOLOCK) ON RST.STAFFID = HW.PERSONNELNUMBER
    WHERE RST.STAFFID = @nvc_UserId
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETREPORTCONFIGURATION]'
GO
-- End creating stored procedure [crt].[GETREPORTCONFIGURATION]


GRANT EXECUTE ON [crt].[GETREPORTCONFIGURATION] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLOCALIZEDREPORTSTRINGS]
PRINT N'Creating stored procedure [crt].[GETLOCALIZEDREPORTSTRINGS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLOCALIZEDREPORTSTRINGS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLOCALIZEDREPORTSTRINGS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLOCALIZEDREPORTSTRINGS].';
END
GO


ALTER PROCEDURE [crt].[GETLOCALIZEDREPORTSTRINGS]
    @tvp_QueryResultSettings [crt].[QUERYRESULTSETTINGSTYPE] READONLY,
    @bi_ChannelId       BIGINT,
    @nvc_LocaleCode     NVARCHAR(10)
AS
BEGIN
    SET NOCOUNT ON

    SELECT
        STRINGID,
        STRINGVALUE
    FROM [crt].RETAILREPORTLOCALIZEDSTRINGVIEW WITH (NOLOCK)
    WHERE LOCALECODE = @nvc_LocaleCode

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLOCALIZEDREPORTSTRINGS]'
GO
-- End creating stored procedure [crt].[GETLOCALIZEDREPORTSTRINGS]


GRANT EXECUTE ON [crt].[GETLOCALIZEDREPORTSTRINGS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSALESBYHOURREPORT]
PRINT N'Creating stored procedure [crt].[GETSALESBYHOURREPORT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSALESBYHOURREPORT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSALESBYHOURREPORT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSALESBYHOURREPORT].';
END
GO


ALTER PROCEDURE [crt].[GETSALESBYHOURREPORT]
    @bi_ChannelId       BIGINT,    
    @dt_StartDate          DATE,
    @dt_EndDate   DATE,
    @nvc_UserId   NVARCHAR(25) = NULL
AS
BEGIN
    SET NOCOUNT ON
    SELECT CONVERT(NVARCHAR(20), (RTA.TRANSTIME / 3600) + 1, 1) as SALESHOUR,
COUNT(*) AS NOOFTRANSACTIONS,
CAST(SUM(RTA.PAYMENTAMOUNT) AS DECIMAL(18,2)) AS SALESAMOUNT,
CAST(AVG(RTA.PAYMENTAMOUNT) AS DECIMAL(18,2)) AS AVGSALESAMOUNT
FROM [ax].RETAILTRANSACTIONTABLE RTA WITH (NOLOCK)
WHERE RTA.CHANNEL = @bi_ChannelId AND
@dt_StartDate <= RTA.TRANSDATE AND @dt_EndDate >= RTA.TRANSDATE
AND (RTA.TYPE = 19 OR RTA.TYPE = 2 OR RTA.TYPE = 14)--TYPE=2 SALES TRANSACTION, TYPE=19 CUSTOMER ORDER TYPE=14 SALES ORDER
AND RTA.PAYMENTAMOUNT <> 0.00
AND ((@nvc_UserId IS NULL) OR (@nvc_UserId IS NOT NULL AND RTA.STAFF = @nvc_UserId))
GROUP BY (RTA.TRANSTIME / 3600)
ORDER BY (RTA.TRANSTIME / 3600)
END;

GO
PRINT N'Finished creating stored procedure [crt].[GETSALESBYHOURREPORT]'
GO
-- End creating stored procedure [crt].[GETSALESBYHOURREPORT]


GRANT EXECUTE ON [crt].[GETSALESBYHOURREPORT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSALESBYREGISTERREPORT]
PRINT N'Creating stored procedure [crt].[GETSALESBYREGISTERREPORT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSALESBYREGISTERREPORT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSALESBYREGISTERREPORT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSALESBYREGISTERREPORT].';
END
GO


ALTER PROCEDURE [crt].[GETSALESBYREGISTERREPORT] 
@bi_ChannelId          BIGINT,
    @dt_StartDate          DATE,
    @dt_EndDate   DATE,
    @nvc_UserId   NVARCHAR(25) = NULL
AS
BEGIN
    SET NOCOUNT ON   
    SELECT RTT.NAME as TERMINALNAME,
COUNT(*) AS NOOFTRANSACTIONS,
CAST(SUM(RTA.PAYMENTAMOUNT) AS DECIMAL(18,2)) AS SALESAMOUNT,
CAST(AVG(RTA.PAYMENTAMOUNT) AS DECIMAL(18,2)) AS AVGSALESAMOUNT
FROM [ax].RETAILTRANSACTIONTABLE RTA WITH (NOLOCK)
INNER JOIN [ax].RETAILTERMINALTABLE RTT WITH (NOLOCK)
ON RTA.TERMINAL = RTT.TERMINALID
WHERE RTA.CHANNEL = @bi_ChannelId AND
(@nvc_UserId is null OR @nvc_UserId = RTA.STAFF) AND
@dt_StartDate <= RTA.TRANSDATE AND @dt_EndDate >= RTA.TRANSDATE AND
(RTA.TYPE = 19 OR RTA.TYPE = 2 OR RTA.TYPE = 14)--TYPE=2 SALES TRANSACTION, TYPE=19 CUSTOMER ORDER TYPE=14 SALES ORDER
AND RTA.PAYMENTAMOUNT <> 0.00
AND ((@nvc_UserId IS NULL) OR (@nvc_UserId IS NOT NULL AND RTA.STAFF = @nvc_UserId))
GROUP BY RTT.NAME
ORDER BY SALESAMOUNT DESC

END;

GO
PRINT N'Finished creating stored procedure [crt].[GETSALESBYREGISTERREPORT]'
GO
-- End creating stored procedure [crt].[GETSALESBYREGISTERREPORT]


GRANT EXECUTE ON [crt].[GETSALESBYREGISTERREPORT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETSALESBYSTAFFREPORT]
PRINT N'Creating stored procedure [crt].[GETSALESBYSTAFFREPORT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETSALESBYSTAFFREPORT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETSALESBYSTAFFREPORT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETSALESBYSTAFFREPORT].';
END
GO


ALTER PROCEDURE [crt].[GETSALESBYSTAFFREPORT] 
 @bi_ChannelId      BIGINT, 
    @dt_StartDate          DATE,
    @dt_EndDate   DATE
AS
BEGIN
    SET NOCOUNT ON 
    SELECT RST.NAMEONRECEIPT AS STAFFNAME, 
    COUNT(*) AS NOOFTRANSACTIONS,
CAST(SUM(RTA.PAYMENTAMOUNT) AS DECIMAL(18,2)) AS SALESAMOUNT,
CAST(AVG(RTA.PAYMENTAMOUNT) AS DECIMAL(18,2)) AS AVGSALESAMOUNT
    FROM [ax].RETAILTRANSACTIONTABLE RTA WITH (NOLOCK)
INNER JOIN [ax].RETAILSTAFFTABLE RST WITH (NOLOCK)
ON RTA.STAFF = RST.STAFFID
WHERE RTA.CHANNEL = @bi_ChannelId AND
@dt_StartDate <= RTA.TRANSDATE AND @dt_EndDate >= RTA.TRANSDATE AND
(RTA.TYPE = 19 OR RTA.TYPE = 2 OR RTA.TYPE = 14)--TYPE=2 SALES TRANSACTION, TYPE=19 CUSTOMER ORDER TYPE=14 SALES ORDER
AND RTA.PAYMENTAMOUNT <> 0.00
GROUP BY RST.NAMEONRECEIPT
    ORDER BY SALESAMOUNT DESC
END;

GO
PRINT N'Finished creating stored procedure [crt].[GETSALESBYSTAFFREPORT]'
GO
-- End creating stored procedure [crt].[GETSALESBYSTAFFREPORT]


GRANT EXECUTE ON [crt].[GETSALESBYSTAFFREPORT] TO [UsersRole];
GO


-- Creating stored procedure [crt].[GETTOP10PRODUCTSREPORT]
PRINT N'Creating stored procedure [crt].[GETTOP10PRODUCTSREPORT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETTOP10PRODUCTSREPORT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETTOP10PRODUCTSREPORT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETTOP10PRODUCTSREPORT].';
END
GO


ALTER PROCEDURE [crt].[GETTOP10PRODUCTSREPORT]
    @bi_ChannelId   BIGINT,
    @dt_StartDate   DATE,
    @dt_EndDate     DATE
AS
BEGIN
    SET NOCOUNT ON

    -- Get the data area for the specified channel identifier.
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId;

    -- Get the top 10 products based on sales.
    SELECT TOP 10
        rta.PRODUCTNAME AS PRODUCTNAME,
        CAST(-1 * SUM(rta.NETAMOUNT) + -1 * SUM(rta.TAXAMOUNT) AS DECIMAL(18,2)) AS SALESAMOUNT,
        SUM(-1 * CONVERT(INT, rta.QTY)) AS QUANTITY
    FROM [crt].GETRETAILTRANSACTIONCATEGORIES(@bi_ChannelId, @nvc_DataAreaId) rta
    WHERE @dt_StartDate <= rta.TRANSDATE AND @dt_EndDate >= rta.TRANSDATE
    GROUP BY rta.PRODUCTNAME
    ORDER BY SALESAMOUNT DESC

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETTOP10PRODUCTSREPORT]'
GO
-- End creating stored procedure [crt].[GETTOP10PRODUCTSREPORT]


GRANT EXECUTE ON [crt].[GETTOP10PRODUCTSREPORT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETALLDISCOUNTTRADEAGREEMENTS]
PRINT N'Creating stored procedure [crt].[GETALLDISCOUNTTRADEAGREEMENTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETALLDISCOUNTTRADEAGREEMENTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETALLDISCOUNTTRADEAGREEMENTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETALLDISCOUNTTRADEAGREEMENTS].';
END
GO


ALTER PROCEDURE [crt].[GETALLDISCOUNTTRADEAGREEMENTS]
    @bi_ChannelId       BIGINT,
    @ItemIds            [crt].[STRINGIDTABLETYPE] READONLY,
    @Customer           nvarchar(20),
    @MinDate            DATE,
    @MaxDate            DATE,
@nvc_CurrencyCode   NVARCHAR(3)
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @NoDate date = CAST([crt].[PRICE_NODATE]() AS DATE);
DECLARE @nvc_DataAreaId NVARCHAR(4);
SELECT @nvc_DataAreaId = INVENTLOCATIONDATAAREAID from [ax].RETAILCHANNELTABLE where RECID = @bi_ChannelId

    DECLARE @CustomerPriceGroups TABLE (LINEDISC nvarchar(20), MULTILINEDISC nvarchar(20), ENDDISC nvarchar(20));

    INSERT INTO @CustomerPriceGroups
        (LINEDISC, MULTILINEDISC, ENDDISC)
    (SELECT LINEDISC, MULTILINEDISC, ENDDISC
        FROM [ax].CUSTTABLE WHERE ACCOUNTNUM = @Customer AND DATAAREAID = @nvc_DataAreaId)

    DECLARE @LineDiscGroup nvarchar(20) = (SELECT LINEDISC from @CustomerPriceGroups)
    DECLARE @MultilineDiscGroup nvarchar(20) = (SELECT MULTILINEDISC from @CustomerPriceGroups)
    DECLARE @TotalDiscGroup nvarchar(20) = (SELECT ENDDISC from @CustomerPriceGroups)

    select STRINGID into #tempItem from @ItemIds

    DECLARE @ItemLineDiscGroups TABLE (LINEDISC nvarchar(20));
    INSERT INTO @ItemLineDiscGroups
        (LINEDISC)
    (SELECT DISTINCT LINEDISC FROM [ax].[INVENTTABLEMODULE]
        INNER JOIN #tempItem ON ITEMID = STRINGID
WHERE MODULETYPE = 2 AND DATAAREAID = @nvc_DataAreaId)

    DECLARE @ItemMultilineDiscGroups TABLE (MULTILINEDISC nvarchar(20));
    INSERT INTO @ItemMultilineDiscGroups
        (MULTILINEDISC)
    (SELECT DISTINCT MULTILINEDISC FROM [ax].[INVENTTABLEMODULE]
        INNER JOIN #tempItem ON ITEMID = STRINGID
WHERE MODULETYPE = 2 AND DATAAREAID = @nvc_DataAreaId)

    SELECT
        ta.RECID,
        ta.ITEMCODE,
        ta.ACCOUNTCODE,
        ta.ITEMRELATION,
        ta.ACCOUNTRELATION,
        ta.QUANTITYAMOUNTFROM,
        ta.QUANTITYAMOUNTTO,
        ta.FROMDATE,
        ta.TODATE,
        ta.AMOUNT,
        ta.CURRENCY,
        ta.PERCENT1,
        ta.PERCENT2,
        ta.SEARCHAGAIN,
        ta.PRICEUNIT,
        ta.RELATION,
        ta.UNITID,
        ta.MARKUP,
        ta.ALLOCATEMARKUP,
        ta.INVENTDIMID,
ta.MAXIMUMRETAILPRICE_IN AS MAXIMUMRETAILPRICEINDIA,
        invdim.CONFIGID,
        invdim.INVENTCOLORID,
        invdim.INVENTSIZEID,
        invdim.INVENTSTYLEID
    FROM [ax].PRICEDISCTABLE ta
INNER JOIN [ax].RETAILCHANNELTABLE AS c
ON c.INVENTLOCATIONDATAAREAID = ta.DATAAREAID AND c.RECID = @bi_ChannelId
    LEFT JOIN [ax].INVENTDIM invdim ON ta.INVENTDIMID = invdim.INVENTDIMID AND ta.DATAAREAID = invdim.DATAAREAID
    WHERE
        -- agreement is of one of the sales discount types
        ta.RELATION IN (5, 6, 7)
AND ta.CURRENCY = @nvc_CurrencyCode 

        -- and currently active
        AND ((ta.FROMDATE <= @MinDate OR ta.FROMDATE <= @NoDate)
                AND (ta.TODATE >= @MaxDate OR ta.TODATE <= @NoDate))

AND ta.DATAAREAID = @nvc_DataAreaId
        -- and customer/group relation matches
        AND
        (
         -- account code is group and relation is in the price groups
         ((ta.ACCOUNTCODE = 1) AND
          (
            (ta.RELATION = 5 AND ta.ACCOUNTRELATION = @LineDiscGroup)) OR
            (ta.RELATION = 6 AND ta.ACCOUNTRELATION = @MultilineDiscGroup) OR
            (ta.RELATION = 7 AND ta.ACCOUNTRELATION = @TotalDiscGroup))
         OR
         -- or account code is customer and customer is on the agreement
         ((ta.ACCOUNTCODE = 0) AND (ta.ACCOUNTRELATION = @Customer))
         OR
         -- or account code is ALL customers
         ((ta.ACCOUNTCODE = 2))
        )

        -- and item/group relation matches
        AND
        (
         -- item code is one of the items passed in
         ((ta.ITEMCODE = 0) AND (ta.ITEMRELATION in (SELECT i.STRINGID FROM @ItemIds i)))
         OR
         -- item code is group and trade agreement type is line discount, match item line discounts
         ((ta.ITEMCODE = 1) AND (ta.RELATION = 5) AND (ta.ITEMRELATION IN (SELECT LINEDISC FROM @ItemLineDiscGroups)))
         OR
         -- item code is group and trade agreement type is multiline discount, match item line multiline discounts
         ((ta.ITEMCODE = 1) AND (ta.RELATION = 6) AND (ta.ITEMRELATION IN (SELECT MULTILINEDISC FROM @ItemMultilineDiscGroups)))
         OR
         -- item code is all items
         (ta.ITEMCODE = 2)
        )

  -- and warehouse is either for all or for current channel
  AND
  (
   invdim.INVENTLOCATIONID = '' OR (invdim.INVENTLOCATIONID = c.INVENTLOCATION)
  )

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETALLDISCOUNTTRADEAGREEMENTS]'
GO
-- End creating stored procedure [crt].[GETALLDISCOUNTTRADEAGREEMENTS]


GRANT EXECUTE ON [crt].[GETALLDISCOUNTTRADEAGREEMENTS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETRETAILDISCOUNTSFORITEMS]
PRINT N'Creating stored procedure [crt].[GETRETAILDISCOUNTSFORITEMS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETRETAILDISCOUNTSFORITEMS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETRETAILDISCOUNTSFORITEMS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETRETAILDISCOUNTSFORITEMS].';
END
GO


ALTER PROCEDURE [crt].[GETRETAILDISCOUNTSFORITEMS]
    @bi_ChannelId       BIGINT,
    @items              [crt].[ITEMVARIANTINVENTDIMTABLETYPE] READONLY,
    @priceGroups        [crt].[PRICEGROUPTABLETYPE] READONLY,
    @nvc_CurrencyCode   NVARCHAR(3),
    @MinDate            DATE,
    @MaxDate            DATE
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @NoDate date = CAST([crt].[PRICE_NODATE]() AS DATE);
DECLARE @nvc_DataAreaId NVARCHAR(4);
SELECT @nvc_DataAreaId = INVENTLOCATIONDATAAREAID from [ax].RETAILCHANNELTABLE where RECID = @bi_ChannelId

    -- fetch price group record ids or lookup if missing
    DECLARE @priceGroupRecIds TABLE (PRICEGROUP BIGINT);
    INSERT INTO @priceGroupRecIds (PRICEGROUP)
    SELECT (CASE(pa.PRICEGROUP)
        WHEN 0
        THEN pg.RECID
        ELSE pa.PRICEGROUP
        END)
    FROM @priceGroups AS pa
    INNER JOIN [ax].PRICEDISCGROUP pg ON pg.GROUPID = pa.GROUPID AND DATAAREAID = @nvc_DataAreaId

    -- resolve item Ids and dimensions into product and variant Ids
    DECLARE @itemIds TABLE (ITEMID nvarchar(20), VARIANTINVENTDIMID nvarchar(20), PRODUCT bigint, DISTINCTPRODUCTVARIANT bigint)
    INSERT INTO @itemIds
    SELECT
        it.ITEMID,
        it.VARIANTINVENTDIMID,
        ISNULL(i.PRODUCT,0),
        ISNULL(idc.DISTINCTPRODUCTVARIANT,0)
    FROM @items AS it
    LEFT JOIN [ax].INVENTTABLE i ON i.ITEMID = it.ITEMID AND i.DATAAREAID = @nvc_DataAreaId
    LEFT JOIN [ax].INVENTDIMCOMBINATION idc ON idc.ITEMID = it.ITEMID AND idc.INVENTDIMID = it.VARIANTINVENTDIMID AND idc.DATAAREAID = @nvc_DataAreaId

    SELECT DISTINCT
        pd.OFFERID,
        pd.NAME,
        pd.PERIODICDISCOUNTTYPE,
        pd.CONCURRENCYMODE,
        pd.ISDISCOUNTCODEREQUIRED,
        pd.VALIDATIONPERIODID,
        pd.DATEVALIDATIONTYPE,
        pd.VALIDFROM,
        pd.VALIDTO,
        pd.DISCOUNTTYPE,
        pd.DEALPRICEVALUE,
        pd.DISCOUNTPERCENTVALUE,
        pd.DISCOUNTAMOUNTVALUE,
        pd.NOOFLEASTEXPENSIVELINES,
        pd.NUMBEROFTIMESAPPLICABLE,
        pd.LINENUM,
        pd.DISCOUNTPERCENTORVALUE,

        ISNULL(mmol.LINEGROUP,'') AS LINEGROUP,
        ISNULL(mmol.DISCOUNTTYPE,'') AS MIXANDMATCHLINEDISCOUNTTYPE,
        ISNULL(mmol.NUMBEROFITEMSNEEDED,'') AS NUMBEROFITEMSNEEDED,

        ISNULL(dol.DISCOUNTMETHOD,0) AS DISCOUNTMETHOD,
        ISNULL(dol.DISCAMOUNT,0) AS DISCAMOUNT,
        ISNULL(dol.DISCPCT, 0) AS DISCPCT,
        ISNULL(dol.OFFERPRICE, 0) AS OFFERPRICE,
        ISNULL(dol.OFFERPRICEINCLTAX, 0) AS OFFERPRICEINCLTAX,

        ISNULL(uom.SYMBOL,'') AS SYMBOL,

        ISNULL(pd.COUNTNONDISCOUNTITEMS, 0) AS COUNTNONDISCOUNTITEMS,

        it.ITEMID,
        it.VARIANTINVENTDIMID AS INVENTDIMID
    FROM [crt].RETAILPERIODICDISCOUNTSFLATTENEDVIEW pd
INNER JOIN [ax].RETAILCHANNELTABLE AS c
ON c.INVENTLOCATIONDATAAREAID = pd.DATAAREAID AND c.RECID = @bi_ChannelId
    INNER JOIN [ax].RETAILDISCOUNTPRICEGROUP rdpg on rdpg.OFFERID = pd.OFFERID AND rdpg.DATAAREAID = pd.DATAAREAID
    INNER JOIN @priceGroupRecIds pg ON rdpg.PRICEDISCGROUP = pg.PRICEGROUP 
    LEFT JOIN [ax].UNITOFMEASURE uom ON uom.RECID = pd.UNITOFMEASURE
    INNER JOIN [ax].RETAILGROUPMEMBERLINE rgl ON pd.RETAILGROUPMEMBERLINE = rgl.RECID
    LEFT JOIN [crt].RETAILPRODUCTORVARIANTCATEGORYANCESTORSVIEW rpca ON rgl.CATEGORY = rpca.CATEGORY
    LEFT JOIN [ax].RETAILDISCOUNTLINEMIXANDMATCH mmol ON pd.DISCOUNTLINEID = mmol.RECID AND pd.DATAAREAID = mmol.DATAAREAID
    LEFT JOIN [ax].RETAILDISCOUNTLINEOFFER dol ON pd.DISCOUNTLINEID = dol.RECID AND pd.DATAAREAID = dol.DATAAREAID
    INNER JOIN @itemIds it ON
        ((rgl.VARIANT != 0 AND rgl.VARIANT = it.DISTINCTPRODUCTVARIANT) OR
        (rgl.VARIANT = 0 AND rgl.PRODUCT != 0 AND rgl.PRODUCT = it.PRODUCT) OR
        (rgl.VARIANT = 0 AND rgl.PRODUCT = 0 AND
        (rpca.PRODUCT = it.PRODUCT OR rpca.PRODUCT = it.DISTINCTPRODUCTVARIANT)))
    WHERE (pd.STATUS = 1)
        AND (pd.PERIODICDISCOUNTTYPE != 3) -- don't fetch price adjustments
        AND (pd.VALIDFROM <= @MinDate OR pd.VALIDFROM <= @NoDate)
        AND (pd.VALIDTO >= @MaxDate OR pd.VALIDTO <= @NoDate)
        AND pd.CURRENCYCODE = @nvc_CurrencyCode
AND pd.DATAAREAID = @nvc_DataAreaId

    ORDER BY pd.OFFERID, pd.LINENUM

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETRETAILDISCOUNTSFORITEMS]'
GO
-- End creating stored procedure [crt].[GETRETAILDISCOUNTSFORITEMS]


GRANT EXECUTE ON [crt].[GETRETAILDISCOUNTSFORITEMS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLISTINGMAP]
PRINT N'Creating stored procedure [crt].[GETLISTINGMAP]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLISTINGMAP]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLISTINGMAP] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLISTINGMAP].';
END
GO


ALTER PROCEDURE [crt].[GETLISTINGMAP]
    @bi_ChannelId BIGINT,
    @tvp_ListingIds     [crt].[RECORDIDTABLETYPE] READONLY
    
AS
BEGIN
    SET NOCOUNT ON

    SELECT
        CATALOGID, 
LISTINGRECID,
LANGUAGEID,
        LISTID
    FROM [crt].[CATALOGLISTMAPPING]
    INNER JOIN @tvp_ListingIds listingIds ON listingIds.RECID = LISTINGRECID
WHERE CHANNELID = @bi_ChannelId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLISTINGMAP]'
GO
-- End creating stored procedure [crt].[GETLISTINGMAP]


GRANT EXECUTE ON [crt].[GETLISTINGMAP] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETLISTINGMAP] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETALLLISTINGSMAP]
PRINT N'Creating stored procedure [crt].[GETALLLISTINGSMAP]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETALLLISTINGSMAP]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETALLLISTINGSMAP] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETALLLISTINGSMAP].';
END
GO


ALTER PROCEDURE [crt].[GETALLLISTINGSMAP]
    @bi_ChannelId BIGINT

AS
BEGIN
    SET NOCOUNT ON

    SELECT
        CATALOGID, 
LISTINGRECID,
LANGUAGEID,
        LISTID
    FROM [crt].[CATALOGLISTMAPPING]
WHERE CHANNELID = @bi_ChannelId
ORDER BY CATALOGID, LISTID

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETALLLISTINGSMAP]'
GO
-- End creating stored procedure [crt].[GETALLLISTINGSMAP]


GRANT EXECUTE ON [crt].[GETALLLISTINGSMAP] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETALLLISTINGSMAP] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETNOTEXISTINGCATALOGS]
PRINT N'Creating stored procedure [crt].[GETNOTEXISTINGCATALOGS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETNOTEXISTINGCATALOGS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETNOTEXISTINGCATALOGS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETNOTEXISTINGCATALOGS].';
END
GO


ALTER PROCEDURE [crt].[GETNOTEXISTINGCATALOGS]
    @bi_ChannelId BIGINT,
    @tvp_CatalogIds crt.RECORDIDTABLETYPE READONLY

AS
BEGIN
    SET NOCOUNT ON

    SELECT
        LISTID, CATALOGID
    FROM [crt].[CATALOGLISTMAPPING]
WHERE CHANNELID = @bi_ChannelId
  AND CATALOGID NOT IN (SELECT RECID FROM @tvp_CatalogIds)
    GROUP BY LISTID, CATALOGID

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETNOTEXISTINGCATALOGS]'
GO
-- End creating stored procedure [crt].[GETNOTEXISTINGCATALOGS]


GRANT EXECUTE ON [crt].[GETNOTEXISTINGCATALOGS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETNOTEXISTINGCATALOGS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[DELETELISTINGSBYCATALOGS]
PRINT N'Creating stored procedure [crt].[DELETELISTINGSBYCATALOGS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETELISTINGSBYCATALOGS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETELISTINGSBYCATALOGS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETELISTINGSBYCATALOGS].';
END
GO


ALTER PROCEDURE [crt].[DELETELISTINGSBYCATALOGS]
    @bi_ChannelId BIGINT,
    @tvp_CatalogIds crt.RECORDIDTABLETYPE READONLY

AS
BEGIN
    SET NOCOUNT ON

    DELETE C
    FROM [crt].[CATALOGLISTMAPPING] AS C
INNER JOIN @tvp_CatalogIds IDS on IDS.RECID = C.CATALOGID
WHERE CHANNELID = @bi_ChannelId

END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETELISTINGSBYCATALOGS]'
GO
-- End creating stored procedure [crt].[DELETELISTINGSBYCATALOGS]


GRANT EXECUTE ON [crt].[DELETELISTINGSBYCATALOGS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[DELETELISTINGSBYCATALOGS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[DELETELISTINGSBYLANGUAGES]
PRINT N'Creating stored procedure [crt].[DELETELISTINGSBYLANGUAGES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETELISTINGSBYLANGUAGES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETELISTINGSBYLANGUAGES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETELISTINGSBYLANGUAGES].';
END
GO


ALTER PROCEDURE [crt].[DELETELISTINGSBYLANGUAGES]
    @bi_ChannelId BIGINT,
    @tvp_LanguageIds crt.LANGUAGEIDTABLETYPE READONLY

AS
BEGIN
    SET NOCOUNT ON

    DELETE C
    FROM [crt].[CATALOGLISTMAPPING] AS C
INNER JOIN @tvp_LanguageIds ids on ids.LANGUAGEID = C.LANGUAGEID
WHERE CHANNELID = @bi_ChannelId

END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETELISTINGSBYLANGUAGES]'
GO
-- End creating stored procedure [crt].[DELETELISTINGSBYLANGUAGES]


GRANT EXECUTE ON [crt].[DELETELISTINGSBYLANGUAGES] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[DELETELISTINGSBYLANGUAGES] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[DELETELISTINGSBYCOMPOSITEIDS]
PRINT N'Creating stored procedure [crt].[DELETELISTINGSBYCOMPOSITEIDS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETELISTINGSBYCOMPOSITEIDS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETELISTINGSBYCOMPOSITEIDS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETELISTINGSBYCOMPOSITEIDS].';
END
GO


ALTER PROCEDURE [crt].[DELETELISTINGSBYCOMPOSITEIDS]
    @bi_ChannelId BIGINT,
    @bi_CatalogId BIGINT,
@tvp_ProductIds [crt].[RECORDIDLANGUAGETABLETYPE] READONLY

AS
BEGIN
    SET NOCOUNT ON

    DELETE C
    FROM [crt].[CATALOGLISTMAPPING] AS C
INNER JOIN @tvp_ProductIds ids on ids.RECID = C.LISTINGRECID AND ids.LANGUAGEID = c.LANGUAGEID
WHERE CHANNELID = @bi_ChannelId
  AND CATALOGID = @bi_CatalogId

END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETELISTINGSBYCOMPOSITEIDS]'
GO
-- End creating stored procedure [crt].[DELETELISTINGSBYCOMPOSITEIDS]


GRANT EXECUTE ON [crt].[DELETELISTINGSBYCOMPOSITEIDS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[DELETELISTINGSBYCOMPOSITEIDS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[STORECATALOGDEFINITION]
PRINT N'Creating stored procedure [crt].[STORECATALOGDEFINITION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[STORECATALOGDEFINITION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[STORECATALOGDEFINITION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[STORECATALOGDEFINITION].';
END
GO


ALTER PROCEDURE [crt].[STORECATALOGDEFINITION]
    @bi_ChannelId BIGINT,
    @tvp_CatalogDefinition  [crt].[CATALOGDEFINITIONTABLETYPE] READONLY

AS
BEGIN

    SET NOCOUNT ON

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION storeCatalogDefinition;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- drop and repopulate the catalog definition table
    DELETE FROM [crt].[CATALOGDEFINITION]
WHERE CHANNELID = @bi_ChannelId

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    INSERT [crt].[CATALOGDEFINITION] (CHANNELID, LISTID, ATTRIBUTERECID, ATTRIBUTEKEYNAME, LISTGROUPID)
        SELECT
            @bi_ChannelId,
catDef.LISTID,
            catDef.ATTRIBUTERECID,
            catDef.ATTRIBUTEKEYNAME,
            catDef.LISTGROUPID
        FROM @tvp_CatalogDefinition AS catDef

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION storeCatalogDefinition;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION storeCatalogDefinition;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[STORECATALOGDEFINITION]'
GO
-- End creating stored procedure [crt].[STORECATALOGDEFINITION]


GRANT EXECUTE ON [crt].[STORECATALOGDEFINITION] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[STORECATALOGDEFINITION] TO [PublishersRole];
GO


-- Creating stored procedure [crt].[STORELISTINGMAP]
PRINT N'Creating stored procedure [crt].[STORELISTINGMAP]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[STORELISTINGMAP]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[STORELISTINGMAP] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[STORELISTINGMAP].';
END
GO


ALTER PROCEDURE [crt].[STORELISTINGMAP]
    @bi_ChannelID BIGINT,
@bi_CatalogID BIGINT,
    @tvp_UpsertListingMap   [crt].[CATALOGLISTMAPPINGTABLETYPE] READONLY
AS
BEGIN

    SET NOCOUNT ON

MERGE INTO [crt].[CATALOGLISTMAPPING] AS TARGETTABLE
USING @tvp_UpsertListingMap AS SOURCETABLE
ON 
TARGETTABLE.LISTINGRECID = SOURCETABLE.LISTINGRECID
AND TARGETTABLE.LANGUAGEID = SOURCETABLE.LANGUAGEID
AND TARGETTABLE.CHANNELID = @bi_ChannelID
AND TARGETTABLE.CATALOGID = @bi_CatalogID

WHEN MATCHED THEN
UPDATE
        SET TARGETTABLE.LISTID = SOURCETABLE.LISTID
        
WHEN NOT MATCHED THEN
INSERT (CHANNELID, CATALOGID, LISTINGRECID, LANGUAGEID, LISTID)
VALUES (@bi_ChannelId, @bi_CatalogID, SOURCETABLE.LISTINGRECID, SOURCETABLE.LANGUAGEID, SOURCETABLE.LISTID);

    RETURN @@ERROR;
    
END;


GO
PRINT N'Finished creating stored procedure [crt].[STORELISTINGMAP]'
GO
-- End creating stored procedure [crt].[STORELISTINGMAP]


GRANT EXECUTE ON [crt].[STORELISTINGMAP] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[STORELISTINGMAP] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETCATALOGDEFINITION]
PRINT N'Creating stored procedure [crt].[GETCATALOGDEFINITION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETCATALOGDEFINITION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETCATALOGDEFINITION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETCATALOGDEFINITION].';
END
GO


ALTER PROCEDURE [crt].[GETCATALOGDEFINITION]
@bi_ChannelId BIGINT
AS
BEGIN
    SET NOCOUNT ON

    SELECT
        LISTID,
        ATTRIBUTERECID,
        ATTRIBUTEKEYNAME,
        LISTGROUPID,
        LISTLENGTH
    FROM [crt].CATALOGLISTDEFINITIONVIEW
WHERE CHANNELID = @bi_ChannelId

    ORDER BY LISTID

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETCATALOGDEFINITION]'
GO
-- End creating stored procedure [crt].[GETCATALOGDEFINITION]


GRANT EXECUTE ON [crt].[GETCATALOGDEFINITION] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETCATALOGDEFINITION] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETCUSTOMERLOYALTYCARDS]
PRINT N'Creating stored procedure [crt].[GETCUSTOMERLOYALTYCARDS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETCUSTOMERLOYALTYCARDS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETCUSTOMERLOYALTYCARDS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETCUSTOMERLOYALTYCARDS].';
END
GO


ALTER PROCEDURE [crt].[GETCUSTOMERLOYALTYCARDS]
    @nvc_CustomerAccountNumber   NVARCHAR(20),
    @nvc_CustomerDataAreaId      NVARCHAR(4)
AS
BEGIN
    SET NOCOUNT ON

    select
rlc.RECID,
rlc.CARDNUMBER,
rlc.CARDTENDERTYPE,
rlc.PARTY,
ct.ACCOUNTNUM
from [ax].[RETAILLOYALTYCARD] rlc
inner join [ax].[CUSTTABLE] ct
on ct.PARTY = rlc.PARTY
where ct.ACCOUNTNUM = @nvc_CustomerAccountNumber
and ct.DATAAREAID = @nvc_CustomerDataAreaId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETCUSTOMERLOYALTYCARDS]'
GO
-- End creating stored procedure [crt].[GETCUSTOMERLOYALTYCARDS]


GRANT EXECUTE ON [crt].[GETCUSTOMERLOYALTYCARDS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETTAXCODEINTERVALSINDIA]
PRINT N'Creating stored procedure [crt].[GETTAXCODEINTERVALSINDIA]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETTAXCODEINTERVALSINDIA]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETTAXCODEINTERVALSINDIA] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETTAXCODEINTERVALSINDIA].';
END
GO


-- Gets tax code intervals bases on the intersections of Sales tax group and Item sales tax group at the the specified date. 
ALTER PROCEDURE [crt].[GETTAXCODEINTERVALSINDIA]
    @bi_ChannelId       BIGINT,
    @nvc_SalesTaxGroup  NVARCHAR(10),
    @nvc_ItemTaxGroup   NVARCHAR(10),
    @dt_TransactionDate DATE
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_ReturnCodeINT;
    DECLARE @i_ErrorINT;
    DECLARE @dt_NoDateBoundaryDATE;
DECLARE @nvc_DataAreaIdNVARCHAR(4);
DECLARE @bi_SalesTaxFormTypeBIGINT;
DECLARE @i_IndiaTaxTypeCSTINT;

    SET @dt_NoDateBoundary = CAST('1900-01-01' AS DATE)
SET @i_IndiaTaxTypeCST = 2

SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct
WHERE rct.RECID = @bi_ChannelId

SELECT @bi_SalesTaxFormType = rsti.SALESTAXFORMTYPES FROM [ax].RETAILSTORETABLE rst
INNER JOIN [ax].RETAILSTORETABLE_IN rsti ON rsti.RETAILSTORETABLE = rst.RECID
WHERE rst.RECID = @bi_ChannelId

    SELECT DISTINCT
        toi.TAXITEMGROUP,
        toi.TAXCODE,
toi.ABATEMENTPERCENT_IN,
        ISNULL(td.TAXVALUE, 0.0) AS TAXVALUE,
        ISNULL(td.TAXLIMITMIN, 0.0) AS TAXLIMITMIN,
        ISNULL(td.TAXLIMITMAX, 0.0) AS TAXLIMITMAX,
        tgd.EXEMPTTAX,
        tgh.TAXGROUPROUNDING,
        tt.TAXCURRENCYCODE,
        tt.TAXBASE,
        tt.TAXLIMITBASE,
        tt.TAXCALCMETHOD,
        tt.TAXONTAX,
        tt.TAXUNIT,
tt.TAXTYPE_IN,
        ISNULL(tcl.TAXMAX,0) AS TAXMAX,
        ISNULL(tcl.TAXMIN,0) AS TAXMIN
    FROM [ax].TAXGROUPHEADING tgh
    INNER JOIN [ax].TAXGROUPDATA tgd ON tgh.TAXGROUP = tgd.TAXGROUP AND tgh.DATAAREAID = tgd.DATAAREAID
    INNER JOIN [ax].TAXONITEM toi ON tgd.TAXCODE = toi.TAXCODE AND tgd.DATAAREAID = toi.DATAAREAID
    INNER JOIN [ax].TAXDATA td ON toi.TAXCODE = td.TAXCODE AND toi.DATAAREAID = td.DATAAREAID
    INNER JOIN [ax].TAXTABLE tt ON tt.TAXCODE = td.TAXCODE AND tt.DATAAREAID = td.DATAAREAID
AND ((tt.TAXTYPE_IN = @i_IndiaTaxTypeCST 
AND td.SALESTAXFORMTYPES_IN = @bi_SalesTaxFormType) 
OR tt.TAXTYPE_IN <> @i_IndiaTaxTypeCST)
    LEFT JOIN [ax].TAXCOLLECTLIMIT tcl ON 
        tcl.TAXCODE = td.TAXCODE 
AND tcl.DATAAREAID = @nvc_DataAreaId
        -- The date range to cover the transaction date.
AND (tcl.TAXFROMDATE IS NULL
            OR (@dt_TransactionDate >= tcl.TAXFROMDATE)
            OR (tcl.TAXFROMDATE = @dt_NoDateBoundary))
        AND (tcl.TAXTODATE IS NULL
            OR @dt_TransactionDate < DATEADD(d, 1, tcl.TAXTODATE)
            OR tcl.TAXTODATE = @dt_NoDateBoundary)
    WHERE
        toi.TAXITEMGROUP = @nvc_ItemTaxGroup
        AND tgh.TAXGROUP = @nvc_SalesTaxGroup
-- The date range to cover the transaction date.
        AND ((@dt_TransactionDate >= td.TAXFROMDATE 
OR td.TAXFROMDATE = @dt_NoDateBoundary)
        AND (@dt_TransactionDate < DATEADD(d, 1, td.TAXTODATE) 
OR td.TAXTODATE = @dt_NoDateBoundary))
AND tgh.DATAAREAID = @nvc_DataAreaId

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

exit_label:

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETTAXCODEINTERVALSINDIA]'
GO
-- End creating stored procedure [crt].[GETTAXCODEINTERVALSINDIA]


GRANT EXECUTE ON [crt].[GETTAXCODEINTERVALSINDIA] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLOYALTYEARNSCHEMELINES]
PRINT N'Creating stored procedure [crt].[GETLOYALTYEARNSCHEMELINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLOYALTYEARNSCHEMELINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLOYALTYEARNSCHEMELINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLOYALTYEARNSCHEMELINES].';
END
GO


ALTER PROCEDURE [crt].[GETLOYALTYEARNSCHEMELINES]
    @bi_ChannelId                   BIGINT,
@dt_ChannelLocalDateDATE,
    @nvc_LoyaltyCardNumberNVARCHAR(30)
AS
BEGIN
    SET NOCOUNT ON

    -- Select all RetailLoyaltyEarnSchemeLine records that applies to the given loyalty card in the given channel.
select
        rlesl.RECID,
ActiveLoyaltyCardTier.AFFILIATION as LOYALTYGROUPRECID,
ActiveLoyaltyCardTier.LOYALTYTIER as LOYALTYTIERRECID,
        rlesl.FROMACTIVITYAMOUNTCURRENCY,
        rlesl.FROMACTIVITYAMOUNTQTY,
        rlesl.FROMACTIVITYTYPE,
COALESCE(rgml.CATEGORY, 0) as CATEGORYRECID,
COALESCE(rgml.PRODUCT, 0) as PRODUCTRECID,
COALESCE(rgml.VARIANT, 0) as VARIANTRECID,
        rlesl.TOREWARDPOINT,
rlrp.REWARDPOINTID as TOREWARDPOINTID,
rlrp.REWARDPOINTTYPE as TOREWARDPOINTTYPE,
rlrp.REDEEMABLE as TOREWARDPOINTREDEEMABLE,
rlrp.REWARDPOINTCURRENCY as TOREWARDPOINTCURRENCY,
        rlesl.TOREWARDPOINTAMOUNTQTY,
rlrp.EXPIRATIONTIMEUNIT as TOREWARDPOINTEXPIRATIONTIMEUNIT,
rlrp.EXPIRATIONTIMEVALUE as TOREWARDPOINTEXPIRATIONTIMEVALUE,
rlesl.VALIDFROM,
rlesl.VALIDTO
    from 
(
select
ValidLoyaltyCardTier.LOYALTYCARD,
ValidLoyaltyCardTier.AFFILIATION,
ValidLoyaltyCardTier.LOYALTYTIER
from 
(
select
ROW_NUMBER() OVER (PARTITION BY rlct.LOYALTYCARD, rlct.AFFILIATION ORDER BY TIERLEVEL DESC) Ordinal,
rlct.LOYALTYCARD,
rlct.AFFILIATION,
rlct.LOYALTYTIER,
COALESCE(rlt.TIERLEVEL, 0) as TIERLEVEL
from [ax].[RETAILLOYALTYCARD] rlc
inner join [ax].[RETAILLOYALTYCARDTIER] rlct
on rlct.LOYALTYCARD = rlc.RECID
left join [ax].[RETAILLOYALTYTIER] rlt
on rlct.LOYALTYTIER = rlt.RECID
where rlc.CARDNUMBER = @nvc_LoyaltyCardNumber
and (rlct.VALIDFROM is NULL or @dt_ChannelLocalDate >= rlct.VALIDFROM)
and (rlct.VALIDTO is NULL or @dt_ChannelLocalDate <= rlct.VALIDTO)
) ValidLoyaltyCardTier
where ValidLoyaltyCardTier.Ordinal = 1
) ActiveLoyaltyCardTier
inner join [ax].[RETAILLOYALTYSCHEME] rls
on rls.AFFILIATION = ActiveLoyaltyCardTier.AFFILIATION
inner join [ax].[RETAILLOYALTYSCHEMECHANNELEXPLODED] rlsce
on rlsce.LOYALTYSCHEME = rls.RECID
inner join [ax].[RETAILCHANNELTABLE] rct
on rct.OMOPERATINGUNITID = rlsce.OMOPERATINGUNIT
inner join [ax].[RETAILLOYALTYEARNSCHEMELINE] rlesl
on rlesl.LOYALTYSCHEME = rls.RECID
and (rlesl.LOYALTYTIER = ActiveLoyaltyCardTier.LOYALTYTIER or rlesl.LOYALTYTIER = 0)
inner join [ax].[RETAILLOYALTYREWARDPOINT] rlrp
on rlrp.RECID = rlesl.TOREWARDPOINT
left outer join [ax].[RETAILGROUPMEMBERLINE] rgml
on rgml.RECID = rlesl.FROMACTIVITYRETAILGROUPMEMBERLINE
where rct.RECID = @bi_ChannelId
and (rlesl.VALIDFROM is NULL or @dt_ChannelLocalDate >= rlesl.VALIDFROM)
and (rlesl.VALIDTO is NULL or @dt_ChannelLocalDate <= rlesl.VALIDTO);

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLOYALTYEARNSCHEMELINES]'
GO
-- End creating stored procedure [crt].[GETLOYALTYEARNSCHEMELINES]


GRANT EXECUTE ON [crt].[GETLOYALTYEARNSCHEMELINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETLOYALTYREDEEMSCHEMELINES]
PRINT N'Creating stored procedure [crt].[GETLOYALTYREDEEMSCHEMELINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETLOYALTYREDEEMSCHEMELINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETLOYALTYREDEEMSCHEMELINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETLOYALTYREDEEMSCHEMELINES].';
END
GO


ALTER PROCEDURE [crt].[GETLOYALTYREDEEMSCHEMELINES]
    @bi_ChannelId                   BIGINT,
    @dt_ChannelLocalDateDATE,
@nvc_LoyaltyCardNumberNVARCHAR(30),
    @nvc_RewardPointRewardIdNVARCHAR(64)
AS
BEGIN
    SET NOCOUNT ON

    -- Select all RetailLoyaltyRedeemSchemeLine records that applies to the given loyalty card and reward point in the given channel.
select 
rlrsl.RECID,
ActiveLoyaltyCardTier.AFFILIATION as LOYALTYGROUPRECID,
ActiveLoyaltyCardTier.LOYALTYTIER as LOYALTYTIERRECID,
rlrsl.FROMREWARDPOINT,
rlrsl.FROMREWARDPOINTAMOUNTQTY,
COALESCE(rgml.CATEGORY, 0) as CATEGORYRECID,
COALESCE(rgml.PRODUCT, 0) as PRODUCTRECID,
COALESCE(rgml.VARIANT, 0) as VARIANTRECID,
rlrsl.TOREWARDAMOUNTCURRENCY,
rlrsl.TOREWARDAMOUNTQTY,
rlrsl.TOREWARDTYPE,
rlrp.REWARDPOINTID AS FROMREWARDPOINTID,
rlrp.REWARDPOINTTYPE AS FROMREWARDPOINTTYPE,
rlrp.REDEEMABLE AS FROMREWARDPOINTREDEEMABLE,
rlrp.REWARDPOINTCURRENCY AS FROMREWARDPOINTCURRENCY,
rlrp.EXPIRATIONTIMEVALUE AS FROMREWARDPOINTEXPIRATIONTIMEVALUE,
rlrp.EXPIRATIONTIMEUNIT AS FROMREWARDPOINTEXPIRATIONTIMEUNIT
from 
(
select
ValidLoyaltyCardTier.LOYALTYCARD,
ValidLoyaltyCardTier.AFFILIATION,
ValidLoyaltyCardTier.LOYALTYTIER
from 
(
select
ROW_NUMBER() OVER (PARTITION BY rlct.LOYALTYCARD, rlct.AFFILIATION ORDER BY TIERLEVEL DESC) Ordinal,
rlct.LOYALTYCARD,
rlct.AFFILIATION,
rlct.LOYALTYTIER,
COALESCE(rlt.TIERLEVEL, 0) as TIERLEVEL
from [ax].[RETAILLOYALTYCARD] rlc
inner join [ax].[RETAILLOYALTYCARDTIER] rlct
on rlct.LOYALTYCARD = rlc.RECID
left join [ax].[RETAILLOYALTYTIER] rlt
on rlct.LOYALTYTIER = rlt.RECID
where rlc.CARDNUMBER = @nvc_LoyaltyCardNumber
and (rlct.VALIDFROM is NULL or @dt_ChannelLocalDate >= rlct.VALIDFROM)
and (rlct.VALIDTO is NULL or @dt_ChannelLocalDate <= rlct.VALIDTO)
) ValidLoyaltyCardTier
where ValidLoyaltyCardTier.Ordinal = 1
) ActiveLoyaltyCardTier
inner join [ax].[RETAILLOYALTYSCHEME] rls
on rls.AFFILIATION = ActiveLoyaltyCardTier.AFFILIATION
inner join [ax].[RETAILLOYALTYSCHEMECHANNELEXPLODED] rlsce
on rlsce.LOYALTYSCHEME = rls.RECID
inner join [ax].[RETAILCHANNELTABLE] rct
on rct.OMOPERATINGUNITID = rlsce.OMOPERATINGUNIT
inner join [ax].[RETAILLOYALTYREDEEMSCHEMELINE] rlrsl
on rlrsl.LOYALTYSCHEME = rls.RECID
and (rlrsl.LOYALTYTIER = ActiveLoyaltyCardTier.LOYALTYTIER or rlrsl.LOYALTYTIER = 0)
inner join [ax].[RETAILLOYALTYREWARDPOINT] rlrp
on rlrp.RECID = rlrsl.FROMREWARDPOINT
left outer join [ax].[RETAILGROUPMEMBERLINE] rgml
on rgml.RECID = rlrsl.TORETAILGROUPMEMBERLINE
where rct.RECID = @bi_ChannelId
and rlrp.REWARDPOINTID = @nvc_RewardPointRewardId
and (rlrsl.VALIDFROM is NULL or @dt_ChannelLocalDate >= rlrsl.VALIDFROM)
and (rlrsl.VALIDTO is NULL or @dt_ChannelLocalDate <= rlrsl.VALIDTO);

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETLOYALTYREDEEMSCHEMELINES]'
GO
-- End creating stored procedure [crt].[GETLOYALTYREDEEMSCHEMELINES]


GRANT EXECUTE ON [crt].[GETLOYALTYREDEEMSCHEMELINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTLOYALTYCARD]
PRINT N'Creating stored procedure [crt].[INSERTLOYALTYCARD]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTLOYALTYCARD]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTLOYALTYCARD] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTLOYALTYCARD].';
END
GO


ALTER PROCEDURE [crt].[INSERTLOYALTYCARD]
    @TVP_LOYALTYCARDTABLETYPE[crt].[LOYALTYCARDTABLETYPE]            READONLY,
    @TVP_LOYALTYCARDTIERTABLETYPE[crt].[LOYALTYCARDTIERTABLETYPE]        READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    --
    -- Insert loyalty card
    --

    -- Perform Insert
    INSERT INTO [ax].[RETAILLOYALTYCARD]
    (
        [RECID],
[CARDNUMBER],
[CARDTENDERTYPE],
[PARTY]
    )
    SELECT
        [RECID],
[CARDNUMBER],
[CARDTENDERTYPE],
[PARTY]
    FROM @TVP_LOYALTYCARDTABLETYPE;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    -- Insert loyalty card tier
    EXEC @i_Error = [crt].[INSERTLOYALTYCARDTIER] @TVP_LOYALTYCARDTIERTABLETYPE;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;


    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTLOYALTYCARD]'
GO
-- End creating stored procedure [crt].[INSERTLOYALTYCARD]


GRANT EXECUTE ON [crt].[INSERTLOYALTYCARD] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTLOYALTYCARDTIER]
PRINT N'Creating stored procedure [crt].[INSERTLOYALTYCARDTIER]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTLOYALTYCARDTIER]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTLOYALTYCARDTIER] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTLOYALTYCARDTIER].';
END
GO


ALTER PROCEDURE [crt].[INSERTLOYALTYCARDTIER]
    @TVP_LOYALTYCARDTIERTABLETYPE       [crt].[LOYALTYCARDTIERTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].[RETAILLOYALTYCARDTIER]
    (
        [RECID],
[AFFILIATION],
[LOYALTYCARD],
[LOYALTYTIER],
[VALIDFROM],
[VALIDTO]
    )
    SELECT
        [RECID],
[AFFILIATION],
[LOYALTYCARD],
[LOYALTYTIER],
[VALIDFROM],
[VALIDTO]
    FROM @TVP_LOYALTYCARDTIERTABLETYPE;


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTLOYALTYCARDTIER]'
GO
-- End creating stored procedure [crt].[INSERTLOYALTYCARDTIER]


GRANT EXECUTE ON [crt].[INSERTLOYALTYCARDTIER] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPARTYBYADDRESS]
PRINT N'Creating stored procedure [crt].[GETPARTYBYADDRESS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPARTYBYADDRESS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPARTYBYADDRESS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPARTYBYADDRESS].';
END
GO


ALTER PROCEDURE [crt].[GETPARTYBYADDRESS]
@nvc_SearchConditionNVARCHAR(250)
AS
BEGIN

DECLARE @nvc_FormattedSearch NVARCHAR(300) = '"' + @nvc_SearchCondition + '*"'

    SELECT dpt.RECID AS PARTY
    FROM [ax].LOGISTICSPOSTALADDRESS lpa
    INNER JOIN [ax].DIRPARTYLOCATION dpl ON lpa.LOCATION = dpl.LOCATION
    INNER JOIN  [ax].DIRPARTYTABLE dpt ON dpl.PARTY = dpt.RECID
    WHERE GETUTCDATE() BETWEEN lpa.VALIDFROM AND lpa.VALIDTO 
      AND CONTAINS(lpa.[ADDRESS], @nvc_FormattedSearch)

    RETURN
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPARTYBYADDRESS]'
GO
-- End creating stored procedure [crt].[GETPARTYBYADDRESS]


GRANT EXECUTE ON [crt].[GETPARTYBYADDRESS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPARTYBYCONTACT]
PRINT N'Creating stored procedure [crt].[GETPARTYBYCONTACT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPARTYBYCONTACT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPARTYBYCONTACT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPARTYBYCONTACT].';
END
GO


ALTER PROCEDURE [crt].[GETPARTYBYCONTACT]
(
@nvc_SEARCHVALUENVARCHAR(255)
)
AS
BEGIN
DECLARE @nvc_FormattedSearch NVARCHAR(300) = '"' + @nvc_SEARCHVALUE  + '*"'

SELECT dpt.RECID AS PARTY
FROM 
[ax].LOGISTICSELECTRONICADDRESS lea
INNER JOIN[ax].DIRPARTYLOCATION dpl
ON lea.LOCATION = dpl.LOCATION
INNER JOIN [ax].DIRPARTYTABLE dpt
ON dpl.PARTY = dpt.RECID
WHERE
 lea.ISPRIMARY = 1 AND lea.ISPRIVATE = 0
 AND (lea.TYPE = 1 OR lea.TYPE = 2 OR lea.TYPE = 3)-- 1:Phone, 2:Email, 3:URL
 AND CONTAINS(lea.LOCATOR, @nvc_FormattedSearch)
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPARTYBYCONTACT]'
GO
-- End creating stored procedure [crt].[GETPARTYBYCONTACT]


GRANT EXECUTE ON [crt].[GETPARTYBYCONTACT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPARTYBYCUSTOMER]
PRINT N'Creating stored procedure [crt].[GETPARTYBYCUSTOMER]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPARTYBYCUSTOMER]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPARTYBYCUSTOMER] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPARTYBYCUSTOMER].';
END
GO


ALTER PROCEDURE [crt].[GETPARTYBYCUSTOMER]
@nvc_SearchConditionNVARCHAR(100)
AS
BEGIN

-- CustTable.AccountNum is NVARCHAR(20) so trimming input search condition to not exceed that length
DECLARE @nvc_RawSearchForCustTable NVARCHAR(20) =  LEFT(@nvc_SearchCondition, 20)
DECLARE @nvc_FormattedSearchForCustTable NVARCHAR(50) = '"' + @nvc_RawSearchForCustTable + '*"'

-- DirPartyTable.Name is NVARCHAR(100), which matches input parameter so don't need to trim anything, just surrounding it with an appropriate search formatting
DECLARE @nvc_FormattedSearchForDirPartyTable NVARCHAR(150) = '"' + @nvc_SearchCondition + '*"'

SELECT ct.PARTY
FROM [ax].CUSTTABLE ct
WHERE CONTAINS(ct.ACCOUNTNUM, @nvc_FormattedSearchForCustTable)

UNION ALL

SELECT dpt.RECID
FROM [ax].DIRPARTYTABLE dpt
WHERE CONTAINS(dpt.NAME, @nvc_FormattedSearchForDirPartyTable)

RETURN
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPARTYBYCUSTOMER]'
GO
-- End creating stored procedure [crt].[GETPARTYBYCUSTOMER]


GRANT EXECUTE ON [crt].[GETPARTYBYCUSTOMER] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPARTYBYLOYALTYCARD]
PRINT N'Creating stored procedure [crt].[GETPARTYBYLOYALTYCARD]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPARTYBYLOYALTYCARD]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPARTYBYLOYALTYCARD] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPARTYBYLOYALTYCARD].';
END
GO


ALTER PROCEDURE [crt].[GETPARTYBYLOYALTYCARD]
(
@nvc_SEARCHVALUENVARCHAR(30)
)
AS
BEGIN

DECLARE @nvc_SearchCondition NVARCHAR(80) = '"' + @nvc_SEARCHVALUE + '*"'

SELECT PARTY
FROM [ax].RETAILLOYALTYCARD
WHERE PARTY != 0 AND CONTAINS(CARDNUMBER, @nvc_SearchCondition)

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPARTYBYLOYALTYCARD]'
GO
-- End creating stored procedure [crt].[GETPARTYBYLOYALTYCARD]


GRANT EXECUTE ON [crt].[GETPARTYBYLOYALTYCARD] TO [UsersRole];
GO

-- Creating stored procedure [crt].[CUSTOMERSEARCH]
PRINT N'Creating stored procedure [crt].[CUSTOMERSEARCH]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[CUSTOMERSEARCH]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[CUSTOMERSEARCH] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[CUSTOMERSEARCH].';
END
GO


ALTER PROCEDURE [crt].[CUSTOMERSEARCH]
    -- MAX length for FTS is 4000, taking into account prefix '"' and suffix '*"' for the FTS query the maximum allowed length of the parameter is 4000-3 = 3997
    -- The current set of sprocs used inside this SP may not necessary allow so many (3997) characters but we still want to use the maximum allowed by FTS value
    -- as a parameter to this SP because this SP can in future be modified by leveraging other SPs which would allow up to 3997 characters as a search value.
    -- So when this value is passed to any SPs below which expect shorter parameter the value wil just be trimmed and we cannot do anything else here because
    -- queries to different table uses different columns and they have different length, therefore we must truncate when needed.
    @tvp_QueryResultSettings    [crt].[QUERYRESULTSETTINGSTYPE] READONLY,
    @nvc_SearchKeyword          NVARCHAR(3997),
    @b_SearchCrossCompany       BIT = 1,
@bi_ChannelIdBIGINT,
    @nvc_DataAreaId             nvarchar(4) = ''
AS
BEGIN
    SET NOCOUNT ON
    DECLARE @ORDERBY    NVARCHAR(60);
    declare @ASCENDING  BIT;
    DECLARE @SKIP       INT;
    DECLARE @TOP        INT;

    DECLARE @PARTYIDS TABLE (PARTY BIGINT)
    DECLARE @UNIQUEPARTYIDS TABLE (PARTY BIGINT)

    DECLARE @CUSTOMERSEARCHRESULT TABLE (
        ACCOUNTNUMBER               NVARCHAR(20)    NULL,
        ORGID                       NVARCHAR(10)    NULL,
        NAME                        NVARCHAR(100)   NULL,
        FULLADDRESS                 NVARCHAR(255)   NULL,
        EMAIL                       NVARCHAR(255)   NULL,
        PHONE                       NVARCHAR(255)   NULL,
        URL                         NVARCHAR(255)   NULL,
        PARTYNUMBER                 NVARCHAR(40),
        CUSTOMERTYPE                BIGINT,
        RECORDID                    BIGINT)

    INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYCUSTOMER @nvc_SearchKeyword

    INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYCONTACT @nvc_SearchKeyword

    INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYADDRESS @nvc_SearchKeyword

    INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYLOYALTYCARD @nvc_SearchKeyword

    INSERT INTO @UNIQUEPARTYIDS
    SELECT DISTINCT p.PARTY FROM @PARTYIDS p
INNER JOIN (SELECT PARTY, ADDRESSBOOK FROM [ax].[DIRADDRESSBOOKPARTY] WHERE PARTY NOT IN (SELECT RECID FROM ax.OMINTERNALORGANIZATION)) dap on p.PARTY = dap.PARTY
INNER JOIN [ax].[RETAILSTOREADDRESSBOOK] rsab on dap.ADDRESSBOOK = rsab.ADDRESSBOOK
WHERE rsab.STORERECID = @bi_ChannelId;

    -- need to define paging and how many rows.
INSERT INTO @CUSTOMERSEARCHRESULT
(PARTYNUMBER, ACCOUNTNUMBER, [NAME], [FULLADDRESS], PHONE, EMAIL, CUSTOMERTYPE, ORGID, RECORDID)
SELECT [PARTYNUMBER]
  ,CASE WHEN gcv.DATAAREAID = @nvc_DataAreaId 
THEN gcv.ACCOUNTNUMBER  
    ELSE '' 
   END AS ACCOUNTNUMBER
  ,[NAME]
  ,[FULLADDRESS]
  ,[PHONE]
  ,[EMAIL] 
  ,INSTANCERELATIONTYPE
  ,ORGID
  ,RECORDID
FROM [crt].GLOBALCUSTOMERSVIEW gcv
INNER JOIN @UNIQUEPARTYIDS pid ON gcv.RECORDID = pid.PARTY
WHERE (@b_SearchCrossCompany <> 1 AND ACCOUNTNUMBER != '' AND gcv.DATAAREAID = @nvc_DataAreaId)
   OR (@b_SearchCrossCompany = 1)

    SELECT @SKIP = [SKIP], @TOP = [TOP], @ORDERBY = ORDERBY, @ASCENDING = [ASCENDING]
    FROM @tvp_QueryResultSettings

    IF (@ASCENDING = 1)
    BEGIN
        SELECT [PARTYNUMBER]
               ,ACCOUNTNUMBER
               ,[NAME]
               ,[FULLADDRESS]
               ,[PHONE]
               ,[EMAIL]
               ,CUSTOMERTYPE
               ,ORGID
               ,RECORDID
            FROM
                (
                    SELECT ROW_NUMBER() OVER(ORDER BY
                                                CASE
                                                    WHEN @ORDERBY='ACCOUNTNUMBER' THEN ACCOUNTNUMBER
                                                    WHEN @ORDERBY='ORGID' THEN ORGID
                                                    ELSE NAME
                                                END
                                                ASC) AS ROWNUM
                        ,PARTYNUMBER, ACCOUNTNUMBER, NAME, [FULLADDRESS], PHONE, EMAIL, CUSTOMERTYPE, ORGID, RECORDID
                    FROM
                        @CUSTOMERSEARCHRESULT
                ) AS CUSTOMERRESULT
            WHERE
                ROWNUM BETWEEN (@SKIP + 1)
                        AND (@SKIP + @TOP)
    END
    ELSE
    BEGIN
        SELECT [PARTYNUMBER]
               ,ACCOUNTNUMBER
               ,[NAME]
               ,[FULLADDRESS]
               ,[PHONE]
               ,[EMAIL]
               ,CUSTOMERTYPE
               ,ORGID
               ,RECORDID
            FROM
                (
                    SELECT ROW_NUMBER() OVER(ORDER BY
                                                CASE
                                                    WHEN @ORDERBY='ACCOUNTNUMBER' THEN ACCOUNTNUMBER
                                                    WHEN @ORDERBY='ORGID' THEN ORGID
                                                    ELSE NAME
                                                END
                                                DESC) AS ROWNUM
                        ,PARTYNUMBER, ACCOUNTNUMBER, NAME, [FULLADDRESS], PHONE, EMAIL, CUSTOMERTYPE, ORGID, RECORDID
                    FROM
                        @CUSTOMERSEARCHRESULT
                ) AS CUSTOMERRESULT
            WHERE
                ROWNUM BETWEEN (@SKIP + 1)
                        AND (@SKIP + @TOP)
    END

END;


GO
PRINT N'Finished creating stored procedure [crt].[CUSTOMERSEARCH]'
GO
-- End creating stored procedure [crt].[CUSTOMERSEARCH]


GRANT EXECUTE ON [crt].[CUSTOMERSEARCH] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETTILLLAYOUT]
PRINT N'Creating stored procedure [crt].[GETTILLLAYOUT]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETTILLLAYOUT]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETTILLLAYOUT] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETTILLLAYOUT].';
END
GO


ALTER PROCEDURE [crt].[GETTILLLAYOUT]
@tvp_QueryResultSettings [crt].[QUERYRESULTSETTINGSTYPE] READONLY,
@bi_ChannelIdBIGINT,
@bi_TerminalIdBIGINT,
@nvc_StaffIdNVARCHAR(25)
AS
BEGIN

    SET NOCOUNT ON

DECLARE @bi_DeviceTypeIdbigint
DECLARE @nvc_TillLayoutIdnvarchar(10) = NULL

-- Select device type
SELECT @bi_DeviceTypeId = rd.TYPE 
FROM ax.RETAILDEVICE AS rd
INNER JOIN ax.RETAILTERMINALTABLE AS rtt ON rtt.TERMINALID = rd.TERMINAL
WHERE rtt.RECID = @bi_TerminalId 

-- Default to device type 0 (Enterprise POS)
IF @@ROWCOUNT < 1
BEGIN
SELECT @bi_DeviceTypeId = rdt.RECID
FROM ax.RETAILDEVICETYPES AS rdt
WHERE rdt.TYPE = 0
END;

-- Select layout using staff id
SELECT @nvc_TillLayoutId = rtl.LAYOUTID
FROM ax.RETAILTILLLAYOUT AS rtl 
INNER JOIN ax.RETAILTILLLAYOUTSTAFF AS rtls ON rtls.LAYOUTID = rtl.LAYOUTID
INNER JOIN ax.RETAILSTAFFTABLE AS rts ON rts.RECID = rtls.STAFF
WHERE rts.STAFFID = @nvc_StaffId AND 
rtl.DEVICETYPE = @bi_DeviceTypeId

-- Select layout using terminal id
IF @@ROWCOUNT < 1 
BEGIN
SELECT @nvc_TillLayoutId = rtl.LAYOUTID
FROM ax.RETAILTILLLAYOUT AS rtl 
INNER JOIN ax.RETAILTERMINALTABLE AS rtt ON rtt.LAYOUTID = rtl.LAYOUTID
WHERE rtt.RECID = @bi_TerminalId AND 
rtl.DEVICETYPE = @bi_DeviceTypeId

-- Select layout using channel id
IF @@ROWCOUNT < 1 
BEGIN
SELECT @nvc_TillLayoutId = rtl.LAYOUTID
FROM ax.RETAILTILLLAYOUT AS rtl 
INNER JOIN ax.RETAILTILLLAYOUTSTORE AS rtls ON rtls.LAYOUTID = rtl.LAYOUTID
INNER JOIN ax.RETAILCHANNELTABLE AS rct ON rct.RECID = rtls.STORE
WHERE rct.RECID = @bi_ChannelId AND 
rtl.DEVICETYPE = @bi_DeviceTypeId
END;
END;

SELECT 
[NAME]
,[WIDTH]
,[HEIGHT]
,[LAYOUTID]
,[CUSTOMERLAYOUTID]
,[TOTALID]
,[RECEIPTID]
,[LAYOUTXML]
,[CUSTOMERLAYOUTXML]
,[TOTALSLAYOUTXML]
,[CASHCHANGERLAYOUTXML]
,[RECEIPTPAYMENTLAYOUTXML]
,[RECEIPTITEMSLAYOUTXML]
,[RECID]
,[DEVICETYPE]
,[DEVICETYPERECID]
FROM crt.RETAILTILLLAYOUTVIEW
WHERE LAYOUTID = @nvc_TillLayoutId

SELECT 
[BUTTONGRIDID]
,[ZONEID]
,[ZONENAME]
FROM crt.RETAILTILLLAYOUTBUTTONGRIDZONEVIEW
WHERE LAYOUTID = @nvc_TillLayoutId

SELECT 
tillLayoutView.[PICTUREID]
,tillLayoutView.[ZONEID]
,tillLayoutView.[ZONENAME]
,retailImages.PICTURE
FROM crt.RETAILTILLLAYOUTIMAGEZONEVIEW AS tillLayoutView
INNER JOIN ax.RETAILIMAGES AS retailImages
ON tillLayoutView.[PICTUREID] = retailImages.PICTUREID
WHERE LAYOUTID = @nvc_TillLayoutId

SELECT 
[REPORT]
,[ZONEID]
,[ZONENAME]
FROM crt.RETAILTILLLAYOUTREPORTZONEVIEW
WHERE LAYOUTID = @nvc_TillLayoutId

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETTILLLAYOUT]'
GO
-- End creating stored procedure [crt].[GETTILLLAYOUT]


GRANT EXECUTE ON [crt].[GETTILLLAYOUT] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETPRODUCTS]
PRINT N'Creating stored procedure [crt].[GETPRODUCTS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETPRODUCTS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETPRODUCTS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETPRODUCTS].';
END
GO


ALTER PROCEDURE [crt].[GETPRODUCTS]
    @bi_ChannelId           BIGINT, -- The unique channel identifier (required).
    @bi_CatalogId           BIGINT, -- The catalog identifier (optional).
    @i_DataLevel            INT,    -- A value to control the richness of the products returned.
    @dt_ChannelDate         DATE,   -- The current date in the channel's time zone.
    @b_IsForwardLooking     BIT,    -- A value indicating whether to include products in future assortments.
    @b_SkipVariantExpansion BIT,    -- A value indicating whether product masters are to be expanded.
    @tvp_ProductIds     [crt].[RECORDIDTABLETYPE]   READONLY
AS
BEGIN
/*  // data level map for product:
    //
    // data level   |   content
    // =============|================================================================
    // identity     |   id, item id, invent dim
    // minimal      |   + behavior data: is (master, serialized, kit) flags, validity
    // standard     |   + first class properties, indexed properties
    // extended     |   + composition information
    // complete     |   + change tracking information
    // =============|================================================================
 */
    SET NOCOUNT ON

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_Error                    INT;

    DECLARE @tvp_ExpandedWorkingIdSet       [crt].[RECORDIDTABLETYPE]
    DECLARE @tvp_LookupIds                  [crt].[RECORDIDTABLETYPE]
    DECLARE @tvp_AttributeIds               [crt].[RECORDIDTABLETYPE]
    DECLARE @tvp_DummyId                    [crt].[RECORDIDTABLETYPE]
    DECLARE @tvp_DistinctProductVariantIds  [crt].[RECORDIDTABLETYPE]
    DECLARE @tvp_ProductIdsNormalized       [crt].[RECORDIDSTABLETYPE]
    DECLARE @tvp_AssortedProductIds         [crt].[PRODUCTLOOKUPIDTABLETYPE]
    DECLARE @tvp_CatalogAssortedProductIds  [crt].[PRODUCTLOOKUPIDTABLETYPE]

    DECLARE @ProductNameAttributeName           NVARCHAR(256) = 'ProductName'
    DECLARE @ProductDescriptionAttributeName    NVARCHAR(256) = 'Description'
    DECLARE @ProductImageAttributeName          NVARCHAR(256) = 'Image'

    -- Insert dummy record to satisfy API contract
    INSERT INTO @tvp_DummyId VALUES (0)

    -- initializes the return code; we'll return the number of data sets as the return code.
    SET @i_ReturnCode = 0;
    SET @bi_CatalogId = ISNULL(@bi_CatalogId, 0);

    -- Retrieve the data area for the current channel identifier.
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId

    -- The copy operation into @tvp_Ids below is needed for performance improvements, do not remove it.
    DECLARE @tvp_Ids crt.RECORDIDTABLETYPE
    INSERT INTO @tvp_Ids(RECID)
    SELECT tpi.RECID
    FROM @tvp_ProductIds tpi

    -- Normalize all input identifiers. That means standalone, product master and variant
    -- identifiers all return the parent product as the lookup identifer. This is necessary
    -- because the input product identifiers can be any type of product (standalone, product
    -- master, variant, kit, etc).
    INSERT @tvp_ProductIdsNormalized (RECID, PARENTRECID)
    SELECT DISTINCT
        ids.RECID AS 'PRODUCTID',
        COALESCE(pv2.PRODUCTMASTER, pv.PRODUCTMASTER, ids.RECID) AS 'LOOKUPID'
    FROM @tvp_Ids ids
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON [pv].RECID = [ids].RECID
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv2 ON [pv2].PRODUCTMASTER = [ids].RECID

    -- Retrieve the unique parent product identifiers.
    INSERT @tvp_LookupIds (RECID)
    SELECT DISTINCT PARENTRECID -- LOOKUPID
    FROM @tvp_ProductIdsNormalized

    -- Filter lookup identifiers by assortment and expand all product masters to their individually assorted variants if requested.
    INSERT @tvp_AssortedProductIds (LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO)
    SELECT
        ap.PRODUCTID,
        CASE
            WHEN ap.VARIANTID = 0 THEN ap.PRODUCTID
            ELSE ap.VARIANTID
        END AS 'VARIANTID',
        ap.ISREMOTE,
        ap.VALIDFROM,
        ap.VALIDTO
    FROM [crt].GETASSORTEDPRODUCTS(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking, 0/*b_SkipVariantExpansion*/, 1/*b_ProductIdsPassed*/, @tvp_LookupIds) ap

    -- Build the expanded working set
    IF (@bi_CatalogId = 0)
    BEGIN
        INSERT @tvp_CatalogAssortedProductIds (LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO)
        SELECT LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO
        FROM @tvp_AssortedProductIds

        INSERT @tvp_ExpandedWorkingIdSet (RECID)
        SELECT DISTINCT ap.PRODUCTID
        FROM @tvp_CatalogAssortedProductIds ap
    END
    ELSE
    BEGIN
        -- Filter out any products that are not in the specified catalog.
        WITH cte_CatalogProducts AS
        (
            SELECT
                ap.LOOKUPID,
                ap.PRODUCTID,
                ap.ISREMOTE,
                CASE
                    WHEN ap.VALIDFROM > pc.VALIDFROM THEN ap.VALIDFROM
                    ELSE pc.VALIDFROM
                END AS 'VALIDFROM',
                CASE
                    WHEN pc.VALIDTO < ap.VALIDTO THEN pc.VALIDTO
                    ELSE ap.VALIDTO
                END AS 'VALIDTO'
            FROM @tvp_AssortedProductIds ap
            INNER JOIN [ax].RETAILPUBCATALOGPRODUCT pcp ON pcp.PRODUCT = ap.LOOKUPID OR pcp.PRODUCT = ap.PRODUCTID
            INNER JOIN [ax].RETAILPUBCATALOG pc ON pc.ORIGIN = pcp.CATALOG
            INNER JOIN [crt].PUBCATALOGCHANNELVIEW ccv ON ccv.CATALOG = pcp.CATALOG
            WHERE ccv.CHANNEL = @bi_ChannelId AND ccv.CATALOG = @bi_CatalogId AND
                ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN ap.VALIDFROM AND ap.VALIDTO) OR
                    (@b_IsForwardLooking = 1 AND ap.VALIDTO >= @dt_ChannelDate))
        )
        INSERT @tvp_CatalogAssortedProductIds (LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO)
        -- Retrieve the product masters that are either explicitly or implicitly part of the specified catalog.
        SELECT cp.LOOKUPID, cp.PRODUCTID, cp.ISREMOTE, cp.VALIDFROM, cp.VALIDTO
        FROM cte_CatalogProducts cp
        WHERE ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN cp.VALIDFROM AND cp.VALIDTO) OR
                (@b_IsForwardLooking = 1 AND cp.VALIDTO >= @dt_ChannelDate))
        UNION
        -- Retrieve the product variants that are either explicitly or implicitly part of the specified catalog.
        SELECT cp.LOOKUPID, cp.LOOKUPID, cp.ISREMOTE, cp.VALIDFROM, cp.VALIDTO
        FROM cte_CatalogProducts cp
        WHERE ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN cp.VALIDFROM AND cp.VALIDTO) OR
                (@b_IsForwardLooking = 1 AND cp.VALIDTO >= @dt_ChannelDate))

        INSERT @tvp_ExpandedWorkingIdSet (RECID)
        SELECT DISTINCT ids.PRODUCTID
        FROM @tvp_CatalogAssortedProductIds ids
    END

    DECLARE @tbl_ProductIdentities TABLE (
        LOOKUPID BIGINT NOT NULL,
        PRODUCTID BIGINT NOT NULL,
        ISMASTER BIT NOT NULL,
        ISKIT BIT NOT NULL,
        ISREMOTE BIT NOT NULL,
        MASTERPRODUCT BIGINT NOT NULL,
        DISPLAYPRODUCTNUMBER NVARCHAR(70) NOT NULL,
        SEARCHNAME NVARCHAR(20) NULL,
        ITEMID NVARCHAR(20) NOT NULL,
        INVENTDIMID NVARCHAR(20) NOT NULL
    )

    -- For the filtered identifiers, we can now build the identity for each product.
    INSERT INTO @tbl_ProductIdentities
    SELECT DISTINCT
        ap.LOOKUPID,
        ap.PRODUCTID,
        CASE
            WHEN (([pv].RECID IS NULL) AND ([pv2].RECID IS NOT NULL)) THEN 1
            ELSE 0
        END AS ISMASTER,
        CASE
            WHEN ([rk].RECID IS NULL) THEN 0
            ELSE 1
        END AS ISKIT,
        ap.ISREMOTE,
        CASE
            WHEN (([pv].RECID IS NULL) AND ([pv2].RECID IS NOT NULL)) THEN 0 -- IsMaster
            ELSE ap.LOOKUPID
        END AS MASTERPRODUCT,
        erp.DISPLAYPRODUCTNUMBER,
        erp.SEARCHNAME,
        COALESCE(it.ITEMID, idc.ITEMID) AS ITEMID,
        ISNULL(idc.INVENTDIMID, '') AS INVENTDIMID
    FROM @tvp_CatalogAssortedProductIds ap
    INNER JOIN [ax].ECORESPRODUCT erp ON [erp].RECID = [ap].PRODUCTID
    LEFT OUTER JOIN [ax].INVENTTABLE it ON [it].PRODUCT = [ap].PRODUCTID AND [it].DATAAREAID = @nvc_DataAreaId
    LEFT OUTER JOIN [ax].INVENTDIMCOMBINATION idc ON [idc].DISTINCTPRODUCTVARIANT = [ap].PRODUCTID AND [idc].DATAAREAID = @nvc_DataAreaId
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON [pv].RECID = [ap].PRODUCTID
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv2 ON [pv2].PRODUCTMASTER = [ap].PRODUCTID
    LEFT OUTER JOIN [ax].RETAILKIT rk ON [rk].PRODUCTMASTER = [ap].PRODUCTID
    WHERE @b_SkipVariantExpansion = 0 OR (@b_SkipVariantExpansion = 1 AND [ap].PRODUCTID = [ap].LOOKUPID) -- IsMaster or Standalone

    -- retrieve product identities
    SELECT
        [piv].PRODUCTID AS 'RECID',
        [piv].LOOKUPID,
        [piv].ISMASTER,
        [piv].ISKIT,
        [piv].ISREMOTE,
        [piv].MASTERPRODUCT,
        [piv].ITEMID,
        [piv].INVENTDIMID,
        [piv].DISPLAYPRODUCTNUMBER,
        [piv].SEARCHNAME
    FROM @tbl_ProductIdentities piv

    SET @i_ReturnCode = @i_ReturnCode + 1;

    -- retrieve the distinct product variant identifiers for each variant in our expanded set
    INSERT INTO @tvp_DistinctProductVariantIds (RECID)
    SELECT DISTINCT [piv].[PRODUCTID]
    FROM @tbl_ProductIdentities piv
    WHERE [piv].ISMASTER = 0 AND [piv].MASTERPRODUCT <> 0

    -- retrieve the product variant identities
    SELECT
        [vv].ITEMID,
        [vv].VARIANTID,
        [vv].INVENTDIMID,
        [vv].DISTINCTPRODUCTVARIANT,
        [vv].SIZEID,
        [vv].COLORID,
        [vv].STYLEID,
        [vv].CONFIGID,
        [vv].COLOR,
        [vv].SIZE,
        [vv].STYLE,
        [vv].CONFIG
    FROM [crt].GETVARIANTS(@bi_ChannelId, @dt_ChannelDate, @tvp_DistinctProductVariantIds) vv

    SET @i_ReturnCode = @i_ReturnCode + 1;
    IF (@i_DataLevel < 1)
        RETURN @i_ReturnCode;

    -- Retrieve the product rules
    SELECT
        [prv].PRODUCTID AS 'RECID',
        [prv].BLOCKEDONPOS,
        [prv].DATEBLOCKED,
        [prv].DATETOACTIVATEITEM,
        [prv].DATETOBEBLOCKED,
        [prv].KEYINGINPRICE,
        [prv].KEYINGINQTY,
        [prv].MUSTKEYINCOMMENT,
        [prv].QTYBECOMESNEGATIVE,
        [prv].SCALEITEM,
        [prv].ZEROPRICEVALID,
        [prv].ISSERIALIZED,
        [prv].DEFAULTUNITOFMEASURE
    FROM [crt].PRODUCTRULESVIEW prv
    INNER JOIN @tvp_ExpandedWorkingIdSet ids ON [ids].RECID = [prv].PRODUCTID
    WHERE [prv].DATAAREAID = @nvc_DataAreaId

    SET @i_ReturnCode = @i_ReturnCode + 1;

    IF (@i_DataLevel < 2)
    BEGIN
        -- extract attribute ids of the first-class attributes for this data level.
        INSERT @tvp_AttributeIds(RECID)
        SELECT [pas].ATTRIBUTE
        FROM [crt].GETPRODUCTATTRIBUTESCHEMAS(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @tvp_ExpandedWorkingIdSet, @tvp_DummyId) AS pas
            INNER JOIN [crt].PRODUCTATTRIBUTEMETADATAVIEW pamv ON [pamv].ATTRIBUTE = [pas].ATTRIBUTE
            WHERE [pamv].CHANNEL = @bi_ChannelId
                AND ([pamv].KEYNAME = @ProductNameAttributeName
                    OR [pamv].KEYNAME = @ProductDescriptionAttributeName
                    OR [pamv].KEYNAME = @ProductImageAttributeName)

        -- Retrieve the attribute schema.
        SELECT
            [pas].ATTRIBUTE,
            [pamv].KEYNAME,
            [pamv].DATATYPE AS DATATYPE,
            [pas].PRODUCT,
            [pas].[CATALOG],
            [pas].ATTRIBUTEGROUP,
            [pas].ATTRIBUTEGROUPTYPE
            FROM [crt].GETPRODUCTATTRIBUTESCHEMAS(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @tvp_ExpandedWorkingIdSet, @tvp_DummyId) AS pas
            INNER JOIN @tvp_AttributeIds attribs ON [attribs].RECID = [pas].ATTRIBUTE
            INNER JOIN [crt].PRODUCTATTRIBUTEMETADATAVIEW pamv ON [pamv].ATTRIBUTE = [pas].ATTRIBUTE
            WHERE [pamv].CHANNEL = @bi_ChannelId

        SET @i_ReturnCode = @i_ReturnCode + 1;

        -- Retrieve product attributes
        SELECT
            [pavfn].[ATTRIBUTE],
            [pavfn].[VALUE],
            [pavfn].[ISREFERENCE],
            [pavfn].[PRODUCT],
            [pavfn].[CATEGORY],
            [pavfn].[CATALOG],
            [pavfn].[DISTANCE],
            [pavfn].[SOURCE],
            [pavfn].[BOOLEANVALUE],
            [pavfn].[CURRENCYVALUE],
            [pavfn].[CURRENCYCODE],
            [pavfn].[DATETIMEVALUE],
            [pavfn].[DATETIMEVALUETZID],
            [pavfn].[FLOATVALUE],
            [pavfn].[FLOATUNITSYMBOL],
            [pavfn].[INTVALUE],
            [pavfn].[INTUNITSYMBOL],
            [pavfn].[TEXTVALUE],
            [pavfn].[LANGUAGE],
            [pavfn].[TRANSLATION]
        FROM [crt].GETPRODUCTATTRIBUTEVALUES(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @b_IsForwardLooking, @tvp_ExpandedWorkingIdSet, @tvp_DummyId) AS pavfn
            INNER JOIN @tvp_AttributeIds attribs ON [attribs].RECID = [pavfn].ATTRIBUTE

        SET @i_ReturnCode = @i_ReturnCode + 1;

        -- exit here if the data level is minimal
        RETURN @i_ReturnCode
    END
    ELSE BEGIN
        -- Retrieve the attribute schema.
        SELECT
            [pas].ATTRIBUTE,
            [pamv].KEYNAME,
            [pamv].DATATYPE AS DATATYPE,
            [pas].PRODUCT,
            [pas].[CATALOG],
            [pas].ATTRIBUTEGROUP,
            [pas].ATTRIBUTEGROUPTYPE
        FROM [crt].GETPRODUCTATTRIBUTESCHEMAS(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @tvp_ExpandedWorkingIdSet, @tvp_DummyId) AS pas
            INNER JOIN [crt].PRODUCTATTRIBUTEMETADATAVIEW pamv ON [pamv].ATTRIBUTE = [pas].ATTRIBUTE
            WHERE [pamv].CHANNEL = @bi_ChannelId

        SET @i_ReturnCode = @i_ReturnCode + 1;

        -- Retrieve product attributes
        SELECT
            [pavfn].[ATTRIBUTE],
            [pavfn].[VALUE],
            [pavfn].[ISREFERENCE],
            [pavfn].[PRODUCT],
            [pavfn].[CATEGORY],
            [pavfn].[CATALOG],
            [pavfn].[DISTANCE],
            [pavfn].[SOURCE],
            [pavfn].[BOOLEANVALUE],
            [pavfn].[CURRENCYVALUE],
            [pavfn].[CURRENCYCODE],
            [pavfn].[DATETIMEVALUE],
            [pavfn].[DATETIMEVALUETZID],
            [pavfn].[FLOATVALUE],
            [pavfn].[FLOATUNITSYMBOL],
            [pavfn].[INTVALUE],
            [pavfn].[INTUNITSYMBOL],
            [pavfn].[TEXTVALUE],
            [pavfn].[LANGUAGE],
            [pavfn].[TRANSLATION]
        FROM [crt].GETPRODUCTATTRIBUTEVALUES(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @b_IsForwardLooking, @tvp_ExpandedWorkingIdSet, @tvp_DummyId) AS pavfn

        SET @i_ReturnCode = @i_ReturnCode + 1;
    END

    -- Retrieve active or all catalogs depending on the value of @bi_CatalogId.
    SELECT
        pcp.CATALOG,
        ap.PRODUCTID AS 'PRODUCT',
        CASE
            WHEN ap.VALIDFROM > pc.VALIDFROM THEN ap.VALIDFROM
            ELSE pc.VALIDFROM
        END AS 'VALIDFROM',
        CASE
            WHEN pc.VALIDTO < ap.VALIDTO THEN pc.VALIDTO
            ELSE ap.VALIDTO
        END AS 'VALIDTO'
    FROM @tvp_CatalogAssortedProductIds ap
    INNER JOIN [ax].RETAILPUBCATALOGPRODUCT pcp ON pcp.PRODUCT = ap.PRODUCTID OR pcp.PRODUCT = ap.LOOKUPID
    INNER JOIN [ax].RETAILPUBCATALOG pc ON pc.ORIGIN = pcp.CATALOG
    INNER JOIN [crt].PUBCATALOGCHANNELVIEW ccv ON ccv.CATALOG = pcp.CATALOG
    WHERE ccv.CHANNEL = @bi_ChannelId AND (ccv.CATALOG = @bi_CatalogId OR @bi_CatalogId = 0)
        AND pc.VALIDTO >= @dt_ChannelDate AND (@b_IsForwardLooking = 1 OR pc.VALIDFROM <= @dt_ChannelDate)

    UNION ALL

    -- Retrieve assortment dates when no catalogs have been requested.
    SELECT
        0 AS 'CATALOG',
        ap.PRODUCTID AS 'PRODUCT',
        ap.VALIDFROM,
        ap.VALIDTO
    FROM @tvp_CatalogAssortedProductIds ap
    WHERE @bi_CatalogId = 0 AND (@b_IsForwardLooking = 1 OR @dt_ChannelDate BETWEEN ap.VALIDFROM AND ap.VALIDTO)
    ORDER BY VALIDFROM DESC

    SET @i_ReturnCode = @i_ReturnCode + 1;

    -- Retrieve product categories
    SELECT DISTINCT
        categories.PRODUCT,
        categories.CATEGORY,
        categories.[CATALOG],
        0 AS ISPRIMARY
    FROM [crt].GETPRODUCTCATEGORIES(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @b_IsForwardLooking, 1 /* @b_ProductIdsPassed */, @tvp_ExpandedWorkingIdSet, 0 /* @b_CategoryIdsPassed */, @tvp_DummyId) categories

    SET @i_ReturnCode = @i_ReturnCode + 1;

    IF (@i_DataLevel < 3)
        RETURN @i_ReturnCode;

    -- Retrieve product relations
    SELECT
        [prfn].PRODUCT,
        [prfn].RELATEDPRODUCT,
        [prfn].PRODUCTRELATIONTYPE,
        [prfn].[CATALOG],
        [prfn].EXCLUSION
    FROM [crt].GETPRODUCTRELATIONS(@bi_ChannelId, @bi_CatalogId, @dt_ChannelDate, @tvp_LookupIds) AS prfn

    SET @i_ReturnCode = @i_ReturnCode + 1;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETPRODUCTS]'
GO
-- End creating stored procedure [crt].[GETPRODUCTS]


GRANT EXECUTE ON [crt].[GETPRODUCTS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETPRODUCTS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[VERIFYPRODUCTSEXISTENCE]
PRINT N'Creating stored procedure [crt].[VERIFYPRODUCTSEXISTENCE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[VERIFYPRODUCTSEXISTENCE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[VERIFYPRODUCTSEXISTENCE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[VERIFYPRODUCTSEXISTENCE].';
END
GO


ALTER PROCEDURE [crt].[VERIFYPRODUCTSEXISTENCE]
    @bi_ChannelId       BIGINT, -- The unique channel identifier (required).
    @bi_CatalogId       BIGINT, -- The catalog identifier (optional).
    @dt_ChannelDate     DATE,   -- The current date in the channel's time zone.
    @tvp_Ids            [crt].[RECORDIDLANGUAGETABLETYPE] READONLY
AS
BEGIN

    SET NOCOUNT ON

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_Error                    INT;
    DECLARE @b_IsForwardLooking         BIT = 1;
    DECLARE @b_SkipVariantExpansion     BIT = 0;

    DECLARE @tvp_ExpandedWorkingIdSet       [crt].[RECORDIDTABLETYPE]
    DECLARE @tvp_LookupIds                  [crt].[RECORDIDTABLETYPE]
    DECLARE @tvp_ProductIdsNormalized       [crt].[RECORDIDSTABLETYPE]
    DECLARE @tvp_AssortedProductIds         [crt].[PRODUCTLOOKUPIDTABLETYPE]
    DECLARE @tvp_CatalogAssortedProductIds  [crt].[PRODUCTLOOKUPIDTABLETYPE]  
    
    -- initializes the return code; we'll return the number of data sets as the return code.
    SET @i_ReturnCode = 0;
    SET @bi_CatalogId = ISNULL(@bi_CatalogId, 0);

    -- Retrieve the data area for the current channel identifier.
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId

    -- Normalize all input identifiers. That means standalone, product master and variant
    -- identifiers all return the parent product as the lookup identifer. This is necessary
    -- because the input product identifiers can be any type of product (standalone, product
    -- master, variant, kit, etc).
    INSERT @tvp_ProductIdsNormalized (RECID, PARENTRECID)
    SELECT DISTINCT
        ids.RECID AS 'PRODUCTID',
        COALESCE(pv2.PRODUCTMASTER, pv.PRODUCTMASTER, ids.RECID) AS 'LOOKUPID'
    FROM @tvp_Ids ids
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON [pv].RECID = [ids].RECID
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv2 ON [pv2].PRODUCTMASTER = [ids].RECID

    -- Retrieve the unique parent product identifiers.
    INSERT @tvp_LookupIds (RECID)
    SELECT DISTINCT PARENTRECID -- LOOKUPID
    FROM @tvp_ProductIdsNormalized

    -- Filter lookup identifiers by assortment and expand all product masters to their individually assorted variants if requested.
    INSERT @tvp_AssortedProductIds (LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO)
    SELECT
        ap.PRODUCTID,
        CASE
            WHEN ap.VARIANTID = 0 THEN ap.PRODUCTID
            ELSE ap.VARIANTID
        END AS 'VARIANTID',
        ap.ISREMOTE,
        ap.VALIDFROM,
        ap.VALIDTO
    FROM [crt].GETASSORTEDPRODUCTS(@bi_ChannelId, @dt_ChannelDate, @b_IsForwardLooking, @b_SkipVariantExpansion, 1/*b_ProductIdsPassed*/, @tvp_LookupIds) ap
    
    -- Build the expanded working set
    IF (@bi_CatalogId = 0)
    BEGIN
        INSERT @tvp_CatalogAssortedProductIds (LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO)
        SELECT LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO
        FROM @tvp_AssortedProductIds

        INSERT @tvp_ExpandedWorkingIdSet (RECID)
        SELECT DISTINCT ap.PRODUCTID
        FROM @tvp_CatalogAssortedProductIds ap
    END
    ELSE
    BEGIN
        -- Filter out any products that are not in the specified catalog.
        WITH cte_CatalogProducts AS
        (
            SELECT
                ap.LOOKUPID,
                ap.PRODUCTID,
                ap.ISREMOTE,
                CASE
                    WHEN ap.VALIDFROM > pc.VALIDFROM THEN ap.VALIDFROM
                    ELSE pc.VALIDFROM
                END AS 'VALIDFROM',
                CASE
                    WHEN pc.VALIDTO < ap.VALIDTO THEN pc.VALIDTO
                    ELSE ap.VALIDTO
                END AS 'VALIDTO'
            FROM @tvp_AssortedProductIds ap
            INNER JOIN [ax].RETAILPUBCATALOGPRODUCT pcp ON pcp.PRODUCT = ap.LOOKUPID OR pcp.PRODUCT = ap.PRODUCTID
            INNER JOIN [ax].RETAILPUBCATALOG pc ON pc.ORIGIN = pcp.CATALOG
            INNER JOIN [crt].PUBCATALOGCHANNELVIEW ccv ON ccv.CATALOG = pcp.CATALOG
            WHERE ccv.CHANNEL = @bi_ChannelId AND ccv.CATALOG = @bi_CatalogId AND
                ((@b_IsForwardLooking = 0 AND @dt_ChannelDate BETWEEN ap.VALIDFROM AND ap.VALIDTO) OR
                    (@b_IsForwardLooking = 1 AND ap.VALIDTO >= @dt_ChannelDate))
        )
        INSERT @tvp_CatalogAssortedProductIds (LOOKUPID, PRODUCTID, ISREMOTE, VALIDFROM, VALIDTO)
        -- Retrieve the product masters that are either explicitly or implicitly part of the specified catalog.
        SELECT cp.LOOKUPID, cp.PRODUCTID, cp.ISREMOTE, cp.VALIDFROM, cp.VALIDTO
        FROM cte_CatalogProducts cp
        UNION
        -- Retrieve the product variants that are either explicitly or implicitly part of the specified catalog.
        SELECT cp.LOOKUPID, cp.LOOKUPID, cp.ISREMOTE, cp.VALIDFROM, cp.VALIDTO
        FROM cte_CatalogProducts cp

        INSERT @tvp_ExpandedWorkingIdSet (RECID)
        SELECT DISTINCT ids.PRODUCTID
        FROM @tvp_CatalogAssortedProductIds ids
    END

    -- Filter out all product masters and any variants not requested.
    SELECT DISTINCT cap.PRODUCTID
    FROM @tvp_CatalogAssortedProductIds cap
    INNER JOIN @tvp_Ids ids ON ids.RECID = cap.PRODUCTID
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON pv.RECID = cap.PRODUCTID
    LEFT OUTER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv2 ON pv2.PRODUCTMASTER = cap.PRODUCTID
    WHERE ([pv].RECID IS NOT NULL) OR ([pv2].RECID IS NULL) -- Filter out product masters
END


GO
PRINT N'Finished creating stored procedure [crt].[VERIFYPRODUCTSEXISTENCE]'
GO
-- End creating stored procedure [crt].[VERIFYPRODUCTSEXISTENCE]


GRANT EXECUTE ON [crt].[VERIFYPRODUCTSEXISTENCE] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[VERIFYPRODUCTSEXISTENCE] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[DELETEEXPIREDSESSIONS]
PRINT N'Creating stored procedure [crt].[DELETEEXPIREDSESSIONS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETEEXPIREDSESSIONS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETEEXPIREDSESSIONS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETEEXPIREDSESSIONS].';
END
GO


ALTER PROCEDURE [crt].[DELETEEXPIREDSESSIONS] 
    @int_RetentionDays INT
AS
BEGIN 
DECLARE @todayUTCDate DATETIME;
SELECT @todayUTCDate = GETUTCDATE();

DELETE [crt].[TABLEREPLICATIONLOG] FROM [crt].[TABLEREPLICATIONLOG] TRL 
INNER JOIN [crt].[UPLOADSESSION] US ON TRL.UPLOADSESSIONID = US.ID
WHERE US.DATEUPLOADED IS NOT NULL AND (US.STATUS = 1) AND @todayUTCDate >= DATEADD(D, @int_RetentionDays, ISNULL(US.DATEUPLOADED, 0))

DELETE [crt].UPLOADSESSION FROM [crt].UPLOADSESSION US
WHERE US.DATEUPLOADED IS NOT NULL AND (US.STATUS = 1) AND @todayUTCDate >= DATEADD(D, @int_RetentionDays, ISNULL(US.DATEUPLOADED, 0))

END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETEEXPIREDSESSIONS]'
GO
-- End creating stored procedure [crt].[DELETEEXPIREDSESSIONS]


GRANT EXECUTE ON [crt].[DELETEEXPIREDSESSIONS] TO [DataSyncUsersRole];
GO

-- Creating stored procedure [crt].[DELETEPURCHASEORDERLINES]
PRINT N'Creating stored procedure [crt].[DELETEPURCHASEORDERLINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETEPURCHASEORDERLINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETEPURCHASEORDERLINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETEPURCHASEORDERLINES].';
END
GO


ALTER PROCEDURE [crt].[DELETEPURCHASEORDERLINES]
    @nvc_OrderId     NVARCHAR(50)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Delete the purchase order line from table.
    DELETE FROM [crt].[PURCHASEORDERLINE] WHERE ORDERID = @nvc_OrderId

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
    SET NOCOUNT OFF
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETEPURCHASEORDERLINES]'
GO
-- End creating stored procedure [crt].[DELETEPURCHASEORDERLINES]


GRANT EXECUTE ON [crt].[DELETEPURCHASEORDERLINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETETRANSFERORDERLINES]
PRINT N'Creating stored procedure [crt].[DELETETRANSFERORDERLINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETETRANSFERORDERLINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETETRANSFERORDERLINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETETRANSFERORDERLINES].';
END
GO


ALTER PROCEDURE [crt].[DELETETRANSFERORDERLINES]
    @nvc_OrderId     NVARCHAR(50)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Delete the transfer order lines from table.
    DELETE FROM [crt].[TRANSFERORDERLINE] WHERE ORDERID = @nvc_OrderId

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
    SET NOCOUNT OFF
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETETRANSFERORDERLINES]'
GO
-- End creating stored procedure [crt].[DELETETRANSFERORDERLINES]


GRANT EXECUTE ON [crt].[DELETETRANSFERORDERLINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETEPICKINGLISTLINES]
PRINT N'Creating stored procedure [crt].[DELETEPICKINGLISTLINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETEPICKINGLISTLINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETEPICKINGLISTLINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETEPICKINGLISTLINES].';
END
GO


ALTER PROCEDURE [crt].[DELETEPICKINGLISTLINES]
    @nvc_OrderId     NVARCHAR(50)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                           INT;
    DECLARE @i_TransactionIsOurs                    INT;
    DECLARE @i_Error                                INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Delete the purchase order line from table.
    DELETE FROM [crt].[PICKINGLISTLINE] WHERE ORDERID = @nvc_OrderId

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
    SET NOCOUNT OFF
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETEPICKINGLISTLINES]'
GO
-- End creating stored procedure [crt].[DELETEPICKINGLISTLINES]


GRANT EXECUTE ON [crt].[DELETEPICKINGLISTLINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[SAVEPURCHASEORDERLINES]
PRINT N'Creating stored procedure [crt].[SAVEPURCHASEORDERLINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVEPURCHASEORDERLINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVEPURCHASEORDERLINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVEPURCHASEORDERLINES].';
END
GO


ALTER PROCEDURE [crt].[SAVEPURCHASEORDERLINES]
    @TVP_PURCHASEORDERLINES         [crt].[PURCHASEORDERLINETABLETYPE]    READONLY,
@nvc_OrderIdNVARCHAR(50)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;
    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

--Delete product line operation is NOT SUPPORTED since no scenario of removal product lines on end client.

    -- Perform Insert
    MERGE INTO [crt].PURCHASEORDERLINE
USING @TVP_PURCHASEORDERLINES AS SOURCE
ON
PURCHASEORDERLINE.ORDERID = @nvc_OrderId AND
PURCHASEORDERLINE.RECID = SOURCE.RECID AND
PURCHASEORDERLINE.ITEMID = SOURCE.ITEMID AND
PURCHASEORDERLINE.CONFIGID = SOURCE.CONFIGID AND
PURCHASEORDERLINE.INVENTCOLORID = SOURCE.INVENTCOLORID AND
PURCHASEORDERLINE.INVENTSIZEID = SOURCE.INVENTSIZEID AND
PURCHASEORDERLINE.INVENTSTYLEID = SOURCE.INVENTSTYLEID
WHEN MATCHED THEN
        --Update existing product line rows
UPDATE
        SET
RECID = SOURCE.RECID,
ORDERID = @nvc_OrderId,
LINERECEIPTNUMBER = SOURCE.LINERECEIPTNUMBER,
ITEMID = SOURCE.ITEMID,
ITEMNAME = SOURCE.ITEMNAME,
INVENTDIMID = SOURCE.INVENTDIMID,
QUANTITYORDERED = SOURCE.QUANTITYORDERED,
PURCHASEQUANTITY = SOURCE.PURCHASEQUANTITY,
PURCHASEUNIT = SOURCE.PURCHASEUNIT,
PURCHASERECEIVED = SOURCE.PURCHASERECEIVED,
PURCHASERECEIVEDNOW = SOURCE.PURCHASERECEIVEDNOW,
INVENTBATCHID = SOURCE.INVENTBATCHID,
INVENTSITEID = SOURCE.INVENTSITEID,
INVENTLOCATIONID = SOURCE.INVENTLOCATIONID,
CONFIGID = SOURCE.CONFIGID,
INVENTSERIALID = SOURCE.INVENTSERIALID,
INVENTSIZEID = SOURCE.INVENTSIZEID,
INVENTCOLORID = SOURCE.INVENTCOLORID,
INVENTSTYLEID = SOURCE.INVENTSTYLEID,
RECEIPTDATE = SOURCE.RECEIPTDATE,
DELIVERYMETHOD = SOURCE.DELIVERYMETHOD
WHEN NOT MATCHED THEN
INSERT
        --Insert new product line rows that are added from end client.
    (
[RECID],
    [ORDERID],
    [LINERECEIPTNUMBER],
    [ITEMID],
    [ITEMNAME],
[INVENTDIMID],
    [QUANTITYORDERED],
[PURCHASEQUANTITY],
[PURCHASEUNIT],
    [PURCHASERECEIVED],
    [PURCHASERECEIVEDNOW],
    [INVENTBATCHID],
[INVENTSITEID],
[INVENTLOCATIONID],
[CONFIGID],
[INVENTSERIALID],
[INVENTSIZEID],
[INVENTCOLORID],
[INVENTSTYLEID],
[RECEIPTDATE],
    [DELIVERYMETHOD]
    )
    VALUES
(
SOURCE.[RECID],
    @nvc_OrderId,
    SOURCE.[LINERECEIPTNUMBER],
    SOURCE.[ITEMID],
    SOURCE.[ITEMNAME],
SOURCE.[INVENTDIMID],
    SOURCE.[QUANTITYORDERED],
SOURCE.[PURCHASEQUANTITY],
SOURCE.[PURCHASEUNIT],
    SOURCE.[PURCHASERECEIVED],
    SOURCE.[PURCHASERECEIVEDNOW],
    SOURCE.[INVENTBATCHID],
SOURCE.[INVENTSITEID],
SOURCE.[INVENTLOCATIONID],
SOURCE.[CONFIGID],
SOURCE.[INVENTSERIALID],
SOURCE.[INVENTSIZEID],
SOURCE.[INVENTCOLORID],
SOURCE.[INVENTSTYLEID],
SOURCE.[RECEIPTDATE],
    SOURCE.[DELIVERYMETHOD]
    );


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVEPURCHASEORDERLINES]'
GO
-- End creating stored procedure [crt].[SAVEPURCHASEORDERLINES]


GRANT EXECUTE ON [crt].[SAVEPURCHASEORDERLINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[SAVETRANSFERORDERLINES]
PRINT N'Creating stored procedure [crt].[SAVETRANSFERORDERLINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVETRANSFERORDERLINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVETRANSFERORDERLINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVETRANSFERORDERLINES].';
END
GO


ALTER PROCEDURE [crt].[SAVETRANSFERORDERLINES]
    @TVP_TRANSFEREORDERLINES         [crt].[TRANSFERORDERLINETABLETYPE]    READONLY,
@nvc_OrderId NVARCHAR(50)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

--Delete product line operation is NOT SUPPORTED since no scenario of removal product lines on end client.

    -- Perform Insert
    MERGE INTO [crt].TRANSFERORDERLINE
USING @TVP_TRANSFEREORDERLINES AS SOURCE
ON
TRANSFERORDERLINE.ORDERID = @nvc_OrderId AND
TRANSFERORDERLINE.RECID = SOURCE.RECID AND
TRANSFERORDERLINE.ITEMID = SOURCE.ITEMID AND
TRANSFERORDERLINE.CONFIGID = SOURCE.CONFIGID AND
TRANSFERORDERLINE.INVENTCOLORID = SOURCE.INVENTCOLORID AND
TRANSFERORDERLINE.INVENTSIZEID = SOURCE.INVENTSIZEID AND
TRANSFERORDERLINE.INVENTSTYLEID = SOURCE.INVENTSTYLEID
WHEN MATCHED THEN
        --Update existing product line rows
UPDATE
SET
RECID = SOURCE.RECID,
ORDERID = @nvc_OrderId,
LINERECEIPTNUMBER = SOURCE.LINERECEIPTNUMBER,
ITEMID = SOURCE.ITEMID,
ITEMNAME = SOURCE.ITEMNAME,
INVENTDIMID = SOURCE.INVENTDIMID,
QUANTITYTRANSFERRED = SOURCE.QUANTITYTRANSFERRED,
QUANTITYSHIPPED = SOURCE.QUANTITYSHIPPED,
QUANTITYRECEIVED = SOURCE.QUANTITYRECEIVED,
QUANTITYSHIPNOW = SOURCE.QUANTITYSHIPNOW,
QUANTITYRECEIVENOW = SOURCE.QUANTITYRECEIVENOW,
QUANTITYREMAINSHIP = SOURCE.QUANTITYREMAINSHIP,
QUANTITYREMAINRECEIVE = SOURCE.QUANTITYREMAINRECEIVE,
PURCHASEUNIT = SOURCE.PURCHASEUNIT,
INVENTBATCHID = SOURCE.INVENTBATCHID,
INVENTSITEID = SOURCE.INVENTSITEID,
INVENTLOCATIONID = SOURCE.INVENTLOCATIONID,
CONFIGID = SOURCE.CONFIGID,
INVENTSERIALID = SOURCE.INVENTSERIALID,
INVENTSIZEID = SOURCE.INVENTSIZEID,
INVENTCOLORID = SOURCE.INVENTCOLORID,
INVENTSTYLEID = SOURCE.INVENTSTYLEID,
DELIVERYMETHOD = SOURCE.DELIVERYMETHOD
WHEN NOT MATCHED THEN
INSERT
        --Insert new product line rows that are added from end client.
    (
[RECID],
    [ORDERID],
    [LINERECEIPTNUMBER],
    [ITEMID],
    [ITEMNAME],
[INVENTDIMID],
    [QUANTITYTRANSFERRED],
[QUANTITYSHIPPED],
[QUANTITYRECEIVED],
    [QUANTITYSHIPNOW],
    [QUANTITYRECEIVENOW],
[QUANTITYREMAINSHIP],
[QUANTITYREMAINRECEIVE],
[PURCHASEUNIT],
    [INVENTBATCHID],
[INVENTSITEID],
[INVENTLOCATIONID],
[CONFIGID],
[INVENTSERIALID],
[INVENTSIZEID],
[INVENTCOLORID],
[INVENTSTYLEID],
    [DELIVERYMETHOD]
    )
    VALUES
(
SOURCE.[RECID],
    @nvc_OrderId,
    SOURCE.[LINERECEIPTNUMBER],
    SOURCE.[ITEMID],
    SOURCE.[ITEMNAME],
SOURCE.[INVENTDIMID],
    SOURCE.[QUANTITYTRANSFERRED],
SOURCE.[QUANTITYSHIPPED],
SOURCE.[QUANTITYRECEIVED],
    SOURCE.[QUANTITYSHIPNOW],
    SOURCE.[QUANTITYRECEIVENOW],
SOURCE.[QUANTITYREMAINSHIP],
SOURCE.[QUANTITYREMAINRECEIVE],
SOURCE.[PURCHASEUNIT],
    SOURCE.[INVENTBATCHID],
SOURCE.[INVENTSITEID],
SOURCE.[INVENTLOCATIONID],
SOURCE.[CONFIGID],
SOURCE.[INVENTSERIALID],
SOURCE.[INVENTSIZEID],
SOURCE.[INVENTCOLORID],
SOURCE.[INVENTSTYLEID],
    SOURCE.[DELIVERYMETHOD]
    );


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVETRANSFERORDERLINES]'
GO
-- End creating stored procedure [crt].[SAVETRANSFERORDERLINES]


GRANT EXECUTE ON [crt].[SAVETRANSFERORDERLINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[SAVEPICKINGLISTLINES]
PRINT N'Creating stored procedure [crt].[SAVEPICKINGLISTLINES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVEPICKINGLISTLINES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVEPICKINGLISTLINES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVEPICKINGLISTLINES].';
END
GO


ALTER PROCEDURE [crt].[SAVEPICKINGLISTLINES]
    @TVP_PICKINGLISTLINES         [crt].[PICKINGLISTLINETABLETYPE]    READONLY,
@nvc_OrderIdNVARCHAR(50)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;
    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

-- Perform Delete of existing order rows
DELETE FROM [crt].PICKINGLISTLINE WHERE ORDERID IN
(
SELECT PL.RECID FROM [crt].PICKINGLISTLINE PL
LEFT JOIN @TVP_PICKINGLISTLINES TVP
ON PL.ORDERID = @nvc_OrderId WHERE TVP.RECID IS NULL
)

    -- Perform Insert
    MERGE INTO [crt].PICKINGLISTLINE
USING @TVP_PICKINGLISTLINES AS SOURCE
ON
PICKINGLISTLINE.ORDERID = @nvc_OrderId AND
PICKINGLISTLINE.RECID = SOURCE.RECID
WHEN MATCHED THEN
UPDATE
SET
RECID = SOURCE.RECID,
ORDERID = @nvc_OrderId,
ITEMID = SOURCE.ITEMID,
ITEMNAME = SOURCE.ITEMNAME,
INVENTDIMID = SOURCE.INVENTDIMID,
PURCHASERECEIVEDNOW = SOURCE.PURCHASERECEIVEDNOW,
INVENTBATCHID = SOURCE.INVENTBATCHID,
INVENTSITEID = SOURCE.INVENTSITEID,
INVENTLOCATIONID = SOURCE.INVENTLOCATIONID,
CONFIGID = SOURCE.CONFIGID,
INVENTSERIALID = SOURCE.INVENTSERIALID,
INVENTSIZEID = SOURCE.INVENTSIZEID,
INVENTCOLORID = SOURCE.INVENTCOLORID,
INVENTSTYLEID = SOURCE.INVENTSTYLEID,
DELIVERYMETHOD = SOURCE.DELIVERYMETHOD
WHEN NOT MATCHED THEN
INSERT
    (
[RECID],
    [ORDERID],
    [ITEMID],
    [ITEMNAME],
[INVENTDIMID],
    [PURCHASERECEIVEDNOW],
    [INVENTBATCHID],
[INVENTSITEID],
[INVENTLOCATIONID],
[CONFIGID],
[INVENTSERIALID],
[INVENTSIZEID],
[INVENTCOLORID],
[INVENTSTYLEID],
    [DELIVERYMETHOD]
    )
    VALUES
(
SOURCE.[RECID],
    @nvc_OrderId,
    SOURCE.[ITEMID],
    SOURCE.[ITEMNAME],
SOURCE.[INVENTDIMID],
    SOURCE.[PURCHASERECEIVEDNOW],
    SOURCE.[INVENTBATCHID],
SOURCE.[INVENTSITEID],
SOURCE.[INVENTLOCATIONID],
SOURCE.[CONFIGID],
SOURCE.[INVENTSERIALID],
SOURCE.[INVENTSIZEID],
SOURCE.[INVENTCOLORID],
SOURCE.[INVENTSTYLEID],
    SOURCE.[DELIVERYMETHOD]
    );


    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVEPICKINGLISTLINES]'
GO
-- End creating stored procedure [crt].[SAVEPICKINGLISTLINES]


GRANT EXECUTE ON [crt].[SAVEPICKINGLISTLINES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTKITTRANSACTION]
PRINT N'Creating stored procedure [crt].[INSERTKITTRANSACTION]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTKITTRANSACTION]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTKITTRANSACTION] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTKITTRANSACTION].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
[crt].[INSERTKITTRANSACTION] calls the corresponding stored procedures to insert into:
Header record into RetailTransactionTable 
Kit transaction lines into RETAILTRANSACTIONKITDISASSEMBLYTRANS.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[INSERTKITTRANSACTION]
    @bi_ChannelIdBIGINT,
    @tvp_Transaction[crt].[RETAILTRANSACTIONTABLETYPE]      READONLY,
    @tvp_kitTransaction[crt].[ITEMLINETRANSACTIONTABLETYPE]READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    --
    -- Insert RetailTransactionTable
    --
    EXEC [crt].[INSERTTRANSACTION] @bi_ChannelId, @tvp_Transaction;
    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    --
    -- Insert RetailTransactionKitDisassembly
    --

INSERT INTO [ax].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS]
           ([CHANNEL]
           ,[ITEMID]
           ,[LINENUM]
           ,[QTY]
           ,[STOREID]
           ,[TERMINALID]
           ,[TRANSACTIONID]
           ,[TRANSACTIONSTATUS]
           ,[VARIANTID]
           ,[DATAAREAID]
   )   
SELECT 
 @bi_ChannelId
,[ITEMID]
,[LINENUM]
,[QTY]
    ,[STOREID]
    ,[TERMINALID]
    ,[TRANSACTIONID]
    ,[TRANSACTIONSTATUS]
    ,[VARIANTID]
    ,[DATAAREAID]
    FROM @tvp_kitTransaction AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;


    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTKITTRANSACTION]'
GO
-- End creating stored procedure [crt].[INSERTKITTRANSACTION]


GRANT EXECUTE ON [crt].[INSERTKITTRANSACTION] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTAFFILIATIONTRANS]
PRINT N'Creating stored procedure [crt].[INSERTAFFILIATIONTRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTAFFILIATIONTRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTAFFILIATIONTRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTAFFILIATIONTRANS].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
    [crt].[INSERTAFFILIATIONTRANS] calls the corresponding stored procedures to insert into:
    Affilation lines into RETAILTRANSACTIONAFFILIATIONTRANS.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[INSERTAFFILIATIONTRANS]
    @bi_ChannelId              BIGINT,
    @TVP_AffiliationTrans      [crt].[RETAILTRANSACTIONAFFILIATIONTRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONAFFILIATIONTRANS
    (
        [AFFILIATION],
        [LOYALTYTIER],
        [TRANSACTIONID],
        [TERMINALID],
        [RECEIPTID],
        [STAFFID],
        [STOREID],
        [DATAAREAID],
        [CHANNEL]
    )
    SELECT
        [AFFILIATION],
        [LOYALTYTIER],
        [TRANSACTIONID],
        [TERMINALID],
        [RECEIPTID],
        [STAFFID],
        [STOREID],
        [DATAAREAID],
        @bi_ChannelId
    FROM @TVP_AffiliationTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTAFFILIATIONTRANS]'
GO
-- End creating stored procedure [crt].[INSERTAFFILIATIONTRANS]


GRANT EXECUTE ON [crt].[INSERTAFFILIATIONTRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETCHANGEDPRODUCTIDS]
PRINT N'Creating stored procedure [crt].[GETCHANGEDPRODUCTIDS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETCHANGEDPRODUCTIDS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETCHANGEDPRODUCTIDS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETCHANGEDPRODUCTIDS].';
END
GO


ALTER PROCEDURE [crt].[GETCHANGEDPRODUCTIDS]
@bi_ChannelId BIGINT
, @tvp_Watermark crt.PRODUCTCHANGETRACKINGANCHORSET READONLY
AS
BEGIN
DECLARE @changedProductIds TABLE
( 
RECID BIGINT,
SEQUENCE BIGINT
)

-- select ids of products changed given the input watermark
INSERT @changedProductIds(RECID, SEQUENCE)
SELECT RECID, SEQUENCE
FROM crt.GETPRODUCTIDSWITHATTRIBUTEVALUECHANGES(@tvp_Watermark) 

INSERT @changedProductIds(RECID, SEQUENCE)
SELECT RECID, SEQUENCE
FROM crt.GETPRODUCTIDSWITHTRANSLATIONCHANGES(@tvp_Watermark) 

INSERT @changedProductIds(RECID, SEQUENCE)
SELECT RECID, SEQUENCE
FROM crt.GETPRODUCTIDSWITHCATEGORYCHANGES(@tvp_Watermark)

INSERT @changedProductIds(RECID, SEQUENCE)
SELECT RECID, SEQUENCE
FROM crt.GETPRODUCTIDSWITHCOMPOSITIONCHANGES(@tvp_Watermark)

INSERT @changedProductIds(RECID, SEQUENCE)
SELECT RECID, SEQUENCE
FROM crt.GETPRODUCTIDSWITHPUBLISHEDCATALOGCHANGES(@tvp_Watermark)

INSERT @changedProductIds(RECID, SEQUENCE)
SELECT RECID, SEQUENCE
FROM crt.GETPRODUCTIDSWITHPUBLISHEDATTRIBUTEVALUECHANGES(@tvp_Watermark)

-- return ids in ascending order of timestamp
-- grouping them because the same record id can be returned more than once (the change to the same product could come from different sources)
SELECT piv.LOOKUPID AS RECID, MAX(ids.SEQUENCE) AS SEQUENCE
FROM @changedProductIds AS ids
INNER JOIN crt.PRODUCTIDENTITIESVIEW piv ON piv.RECID = ids.RECID
WHERE piv.CHANNELID = @bi_ChannelId
GROUP BY piv.LOOKUPID
ORDER BY MAX(SEQUENCE) ASC

-- select the new watermark
SELECT 
@bi_ChannelId AS CHANNELID,
ECORESPRODUCT,
ECORESPRODUCTINSTANCEVALUE,
ECORESINSTANCEVALUE,
ECORESATTRIBUTE,
ECORESATTRIBUTEVALUE,
ECORESVALUE,
ECORESBOOLEANVALUE,
ECORESDATETIMEVALUE,
ECORESCURRENCYVALUE,
ECORESFLOATVALUE,
ECORESINTVALUE,
ECORESREFERENCEVALUE,
ECORESTEXTVALUE,
ECORESTEXTVALUETRANSLATION,
ECORESPRODUCTTRANSLATION,
ECORESPRODUCTVARIANTCOLOR,
ECORESPRODUCTVARIANTCONFIGURATION,
ECORESPRODUCTVARIANTDIMENSIONVALUE,
ECORESPRODUCTVARIANTSIZE,
ECORESPRODUCTVARIANTSTYLE,
ECORESCOLOR,
ECORESCONFIGURATION,
ECORESSIZE,
ECORESSTYLE,
ECORESATTRIBUTEGROUPATTRIBUTE,
ECORESCATEGORYATTRIBUTEGROUP,
ECORESCATEGORYATTRIBUTELOOKUP,
ECORESDISTINCTPRODUCTVARIANT,
ECORESPRODUCTCATEGORY,
RETAILCATEGORYCONTAINMENTLOOKUP,
RETAILPUBCATALOGPRODUCT,
RETAILPUBCATALOGPRODUCTCATEGORY,
RETAILPUBCATALOGPRODUCTRELATION,
RETAILPUBCATALOGPRODUCTRELATIONEXCLUSION,
RETAILPUBINTERNALORGATTRIBUTEGROUP,
RETAILPUBINTORGINHERITANCEEXPLODED,
RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA,
RETAILPUBPRODUCTATTRIBUTEVALUE,
RETAILPUBRETAILCHANNELTABLE,
RETAILSHAREDPARAMETERS,
RETAILSTANDARDATTRIBUTE,
UNITOFMEASURE
FROM crt.GETPRODUCTINFOSOURCESCURRENTTIMESTAMPS(@bi_ChannelId)
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETCHANGEDPRODUCTIDS]'
GO
-- End creating stored procedure [crt].[GETCHANGEDPRODUCTIDS]


GRANT EXECUTE ON [crt].[GETCHANGEDPRODUCTIDS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETCHANGEDPRODUCTIDS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETRECEIPTHEADERTAXINFOINDIA]
PRINT N'Creating stored procedure [crt].[GETRECEIPTHEADERTAXINFOINDIA]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETRECEIPTHEADERTAXINFOINDIA]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETRECEIPTHEADERTAXINFOINDIA] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETRECEIPTHEADERTAXINFOINDIA].';
END
GO


ALTER PROCEDURE [crt].[GETRECEIPTHEADERTAXINFOINDIA]
@bi_ChannelId    BIGINT
AS
BEGIN

SET NOCOUNT ON

DECLARE @i_IsPrimaryINT;
SET @i_IsPrimary = 1

SELECT
vatrn.[REGISTRATIONNUMBER] AS [VALUEADDEDTAXTINNUMBER],
vatrn.[REGISTRATIONNUMBER] AS [CENTRALSALESTAXTINNUMBER],
stcrn.[REGISTRATIONNUMBER] AS [SERVICETAXNUMBER],
eccn.[REGISTRATIONNUMBER] AS [EXCISETAXNUMBER]
FROM [ax].RETAILCHANNELTABLE rct
LEFT OUTER JOIN [ax].INVENTLOCATION il ON rct.INVENTLOCATIONDATAAREAID = il.DATAAREAID AND rct.INVENTLOCATION = il.INVENTLOCATIONID
LEFT OUTER JOIN [ax].INVENTLOCATIONLOGISTICSLOCATION illl ON il.RECID = illl.INVENTLOCATION AND illl.ISPRIMARY = @i_IsPrimary
INNER JOIN [ax].LOGISTICSLOCATION ll ON illl.LOCATION = ll.RECID
LEFT OUTER JOIN [ax].TAXINFORMATION_IN ti_IN ON ll.RECID = ti_IN.REGISTRATIONLOCATION AND ti_IN.ISPRIMARY = @i_IsPrimary
LEFT OUTER JOIN [ax].TAXREGISTRATIONNUMBERS_IN vatrn ON ti_IN.TIN = vatrn.RECID
LEFT OUTER JOIN [ax].TAXREGISTRATIONNUMBERS_IN stcrn ON ti_IN.STCREGISTRATIONNUMBERTABLE = stcrn.RECID
LEFT OUTER JOIN [ax].TAXREGISTRATIONNUMBERS_IN eccn ON ti_IN.ECCNUMBER = eccn.RECID
WHERE (rct.RECID = @bi_ChannelId)

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETRECEIPTHEADERTAXINFOINDIA]'
GO
-- End creating stored procedure [crt].[GETRECEIPTHEADERTAXINFOINDIA]


GRANT EXECUTE ON [crt].[GETRECEIPTHEADERTAXINFOINDIA] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETKITCOMPONENTSINFO]
PRINT N'Creating stored procedure [crt].[GETKITCOMPONENTSINFO]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETKITCOMPONENTSINFO]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETKITCOMPONENTSINFO] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETKITCOMPONENTSINFO].';
END
GO


ALTER PROCEDURE [crt].[GETKITCOMPONENTSINFO]
@bi_ChannelIdBIGINT,
@tvp_KitComponentProductListings [crt].[RECORDIDTABLETYPE] READONLY
AS
BEGIN

    SET NOCOUNT ON

DECLARE @tvp_KitComponentVariantsInfo       [crt].[KITCOMPONENTINFOTYPE]
DECLARE @tvp_ExplodedKitComponentVariants       [crt].[KITCOMPONENTINFOTYPE]

-- First explode all the kit components/substitutes that are product masters
INSERT INTO @tvp_ExplodedKitComponentVariants
    SELECT 
PIV.RECID as KITLINEPRODUCTLISTING, 
RKLDV.QUANTITY as QUANTITY,
RKLDV.UNIT,
RKLDV.CHARGE,
PIV.ITEMID as ITEMID, 
PIV.LOOKUPID as KITLINEPRODUCTMASTERLISTING,
RKLDV.ISDEFAULTCOMPONENT,
RKLDV.KITPRODUCTMASTERLISTING AS KITPRODUCTMASTERLISTING,
RKLDV.KITLINEIDENTIFIER,
RKLDV.CHANNEL 
FROM [crt].RETAILKITLINEDEFINITIONVIEW RKLDV 
INNER JOIN [crt].PRODUCTIDENTITIESVIEW PIV ON RKLDV.KITLINEPRODUCTLISTING = PIV.LOOKUPID AND RKLDV.CHANNEL = PIV.CHANNELID 
WHERE PIV.ISMASTER = 0 
AND PIV.CHANNELID = @bi_ChannelId 
AND EXISTS (SELECT KCPL.RECID FROM @tvp_KitComponentProductListings AS KCPL WHERE KCPL.RECID = RKLDV.KITLINEPRODUCTLISTING OR KCPL.RECID = RKLDV.KITLINEPRODUCTMASTERLISTING);

-- Collect information of all kit components/substitutes that are non product masters.
INSERT INTO @tvp_KitComponentVariantsInfo
    SELECT 
PIV.RECID as KITLINEPRODUCTLISTING, 
RKLDV.QUANTITY as QUANTITY,
RKLDV.UNIT,  
RKLDV.CHARGE,
PIV.ITEMID as ITEMID, 
PIV.LOOKUPID as KITLINEPRODUCTMASTERLISTING,
RKLDV.ISDEFAULTCOMPONENT,
RKLDV.KITPRODUCTMASTERLISTING AS KITPRODUCTMASTERLISTING,
RKLDV.KITLINEIDENTIFIER,
RKLDV.CHANNEL 
FROM [crt].RETAILKITLINEDEFINITIONVIEW RKLDV 
INNER JOIN [crt].PRODUCTIDENTITIESVIEW PIV ON RKLDV.KITLINEPRODUCTLISTING = PIV.RECID AND RKLDV.CHANNEL = PIV.CHANNELID 
WHERE PIV.ISMASTER = 0 
AND PIV.CHANNELID = @bi_ChannelId 
AND EXISTS (SELECT KCPL.RECID FROM @tvp_KitComponentProductListings AS KCPL WHERE KCPL.RECID = RKLDV.KITLINEPRODUCTLISTING OR KCPL.RECID = RKLDV.KITLINEPRODUCTMASTERLISTING);

-- For the same product in a component line of a given kit, component information specified at the non-product-master level takes precedence over component information specified at the product master level.
-- Hence, add an entry from the exploded table only if an entry does not already exist in the non-product master table.
MERGE @tvp_KitComponentVariantsInfo AS KCVI
USING @tvp_ExplodedKitComponentVariants AS EKCV
ON (KCVI.KITLINEPRODUCTLISTING = EKCV.KITLINEPRODUCTLISTING AND KCVI.KITPRODUCTMASTERLISTING = EKCV.KITPRODUCTMASTERLISTING AND KCVI.KITLINEIDENTIFIER = EKCV.KITLINEIDENTIFIER)
WHEN NOT MATCHED THEN
INSERT (KITLINEPRODUCTLISTING, QUANTITY, UNIT, CHARGE, ITEMID, KITLINEPRODUCTMASTERLISTING, ISDEFAULTCOMPONENT, KITPRODUCTMASTERLISTING, KITLINEIDENTIFIER, CHANNEL)
VALUES (EKCV.KITLINEPRODUCTLISTING, EKCV.QUANTITY, EKCV.UNIT, EKCV.CHARGE, EKCV.ITEMID, EKCV.KITLINEPRODUCTMASTERLISTING, EKCV.ISDEFAULTCOMPONENT, EKCV.KITPRODUCTMASTERLISTING, EKCV.KITLINEIDENTIFIER, EKCV.CHANNEL)
;

    SELECT 
KITLINEPRODUCTLISTING,
QUANTITY,
UNIT,
CHARGE,
ITEMID, 
KITLINEPRODUCTMASTERLISTING, 
ISDEFAULTCOMPONENT, 
KITPRODUCTMASTERLISTING, 
KITLINEIDENTIFIER, 
CHANNEL
FROM @tvp_KitComponentVariantsInfo KCTVI;

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETKITCOMPONENTSINFO]'
GO
-- End creating stored procedure [crt].[GETKITCOMPONENTSINFO]


GRANT EXECUTE ON [crt].[GETKITCOMPONENTSINFO] TO [PublishersRole];
GO

GRANT EXECUTE ON [crt].[GETKITCOMPONENTSINFO] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETEMPLOYEEBREAKCATEGORIES]
PRINT N'Creating stored procedure [crt].[GETEMPLOYEEBREAKCATEGORIES]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETEMPLOYEEBREAKCATEGORIES]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETEMPLOYEEBREAKCATEGORIES] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETEMPLOYEEBREAKCATEGORIES].';
END
GO


/******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******
GETEMPLOYEEBREAKCATEGORIES gets employee break activities for the given break category names.
******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******/

ALTER PROCEDURE [crt].[GETEMPLOYEEBREAKCATEGORIES]
    @tvp_BreakCategoryNames     [crt].[STRINGIDTABLETYPE]READONLY
AS
BEGIN
SET NOCOUNT ON;

SELECTDISTINCT 
EBCV.RECID,
EBCV.BREAKCATEGORY,
EBCV.JOBID
FROM[crt].[GETEMPLOYEEBREAKCATEGORIESVIEW] EBCV
INNER JOIN @tvp_BreakCategoryNames TVPBCN ON EBCV.BREAKCATEGORY = TVPBCN.STRINGID;

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETEMPLOYEEBREAKCATEGORIES]'
GO
-- End creating stored procedure [crt].[GETEMPLOYEEBREAKCATEGORIES]


GRANT EXECUTE ON [crt].[GETEMPLOYEEBREAKCATEGORIES] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTTAXTRANSINDIA]
PRINT N'Creating stored procedure [crt].[INSERTTAXTRANSINDIA]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTTAXTRANSINDIA]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTTAXTRANSINDIA] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTTAXTRANSINDIA].';
END
GO


ALTER PROCEDURE [crt].[INSERTTAXTRANSINDIA]
    @bi_ChannelId           BIGINT,
    @TVP_TaxTransIndia      [crt].[RETAILTRANSACTIONTAXTRANSINDIATABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONTAXTRANS_IN
    (
        [SALELINENUM],
        [STOREID],
        [TAXCODE],
        [TERMINALID],
        [TRANSACTIONID],
        [CHANNEL],
[TAXITEMGROUP],
[TAXPERCENTAGE],
[TAXCOMPONENT],
[TAXFORMULA],
[TAXISEXEMPT],
[TAXBASIS],
[TAXISINCLUDEDINPRICE],
[ISTAXONTAX],
[DATAAREAID]
    )
    SELECT
        [SALELINENUM],
        [STOREID],
        [TAXCODE],
        [TERMINALID],
        [TRANSACTIONID],
        @bi_ChannelId,
[TAXITEMGROUP],
[TAXPERCENTAGE],
[TAXCOMPONENT],
[TAXFORMULA],
[TAXISEXEMPT],
[TAXBASIS],
[TAXISINCLUDEDINPRICE],
[ISTAXONTAX],
[DATAAREAID]
    FROM @TVP_TaxTransIndia AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTTAXTRANSINDIA]'
GO
-- End creating stored procedure [crt].[INSERTTAXTRANSINDIA]


GRANT EXECUTE ON [crt].[INSERTTAXTRANSINDIA] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETITEMSBYITEMIDS]
PRINT N'Creating stored procedure [crt].[GETITEMSBYITEMIDS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETITEMSBYITEMIDS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETITEMSBYITEMIDS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETITEMSBYITEMIDS].';
END
GO


ALTER PROCEDURE [crt].[GETITEMSBYITEMIDS]
    @bi_ChannelId   BIGINT,
    @dt_ChannelDate DATE,
    @tvp_ItemIds    [crt].[STRINGIDTABLETYPE]   READONLY
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @tvp_ProductIds [crt].RECORDIDTABLETYPE;
    DECLARE @nvc_DataAreaId NVARCHAR(4);

    -- Get the data area for the specified channel identifier.
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId;

    -- Convert the ITEMIDs into PRODUCTIDs.
    INSERT INTO @tvp_ProductIds (RECID)
    SELECT it.PRODUCT
    FROM @tvp_ItemIds ids
    INNER JOIN [ax].INVENTTABLE it ON it.ITEMID = ids.STRINGID AND it.DATAAREAID = @nvc_DataAreaId

    -- Retrieve the items.
    exec [crt].GETITEMSBYPRODUCTIDS @bi_ChannelId, @dt_ChannelDate, @tvp_ProductIds

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETITEMSBYITEMIDS]'
GO
-- End creating stored procedure [crt].[GETITEMSBYITEMIDS]


GRANT EXECUTE ON [crt].[GETITEMSBYITEMIDS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETITEMSBYITEMIDS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[GETITEMSBYPRODUCTIDS]
PRINT N'Creating stored procedure [crt].[GETITEMSBYPRODUCTIDS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETITEMSBYPRODUCTIDS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETITEMSBYPRODUCTIDS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETITEMSBYPRODUCTIDS].';
END
GO


ALTER PROCEDURE [crt].[GETITEMSBYPRODUCTIDS]
    @bi_ChannelId   BIGINT,
    @dt_ChannelDate DATE,
    @tvp_ProductIds [crt].[RECORDIDTABLETYPE]   READONLY
AS
BEGIN
    SET NOCOUNT ON

    -- Get the data area for the specified channel identifier.
    DECLARE @nvc_DataAreaId NVARCHAR(4);
    SELECT @nvc_DataAreaId = rct.INVENTLOCATIONDATAAREAID FROM [ax].RETAILCHANNELTABLE rct WHERE rct.RECID = @bi_ChannelId;

    -- Retrieve the item data.
    SELECT DISTINCT
        it.[RECID],
        it.[ITEMID],
        erpt.[NAME],
        erpt.[DESCRIPTION],
        itm.[PRICE],
        itm.[UNITID],
        it.[PRODUCT],
        itm.[MARKUPGROUPID],
        itm.[MARKUP],
        itm.[ALLOCATEMARKUP],
        itm.[PRICEQTY],
        itm.[LINEDISC],
        itm.[MULTILINEDISC],
        itm.[ENDDISC],
        rit.[NODISCOUNTALLOWED],
        itm.[TAXITEMGROUPID] AS 'ITEMTAXGROUPID',
        iitm.[UNITID] AS 'INVENTUNITID'
    FROM [crt].GETASSORTEDPRODUCTS(@bi_ChannelId, @dt_ChannelDate, 0/*b_IsForwardLooking*/, 1/*b_SkipVariantExpansion*/, 1/*b_ProductIdsPassed*/, @tvp_ProductIds) ap
    INNER JOIN [crt].CHANNELLANGUAGESVIEW clv ON clv.CHANNEL = @bi_ChannelId AND clv.ISDEFAULT = 1 -- Use default channel language
    INNER JOIN [ax].INVENTTABLE it ON it.PRODUCT = ap.PRODUCTID AND it.DATAAREAID = @nvc_DataAreaId
    INNER JOIN [ax].INVENTTABLEMODULE itm ON itm.MODULETYPE = 2 AND itm.ITEMID = it.ITEMID AND itm.DATAAREAID = it.DATAAREAID
    INNER JOIN [ax].INVENTTABLEMODULE iitm ON iitm.MODULETYPE = 0 AND iitm.ITEMID = it.ITEMID AND iitm.DATAAREAID = it.DATAAREAID
    INNER JOIN [ax].ECORESPRODUCTTRANSLATION erpt ON erpt.PRODUCT = it.PRODUCT AND erpt.LANGUAGEID = clv.LANGUAGEID
    INNER JOIN [ax].RETAILINVENTTABLE rit ON it.ITEMID = rit.ITEMID AND rit.DATAAREAID = it.DATAAREAID

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETITEMSBYPRODUCTIDS]'
GO
-- End creating stored procedure [crt].[GETITEMSBYPRODUCTIDS]


GRANT EXECUTE ON [crt].[GETITEMSBYPRODUCTIDS] TO [UsersRole];
GO

GRANT EXECUTE ON [crt].[GETITEMSBYPRODUCTIDS] TO [PublishersRole];
GO

-- Creating stored procedure [crt].[RESEEDUPLOADSESSIONIDENTITY]
PRINT N'Creating stored procedure [crt].[RESEEDUPLOADSESSIONIDENTITY]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[RESEEDUPLOADSESSIONIDENTITY]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[RESEEDUPLOADSESSIONIDENTITY] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[RESEEDUPLOADSESSIONIDENTITY].';
END
GO


ALTER PROCEDURE [crt].[RESEEDUPLOADSESSIONIDENTITY]
    @bi_latestUploadSessionId BIGINT
AS
BEGIN 
    BEGIN TRANSACTION;
    SET IDENTITY_INSERT [crt].[UPLOADSESSION] ON ;

    INSERT INTO [crt].[UPLOADSESSION] (ID, JOBID, STATUS, MESSAGE, UPLOADPATH, DATECREATED, DATEUPLOADED, FILESIZE, CHECKSUM)
    VALUES(@bi_latestUploadSessionId, '', 0, '', '', null, null, 0, '');

    DELETE FROM [crt].[UPLOADSESSION] WHERE ID = @bi_latestUploadSessionId;

    SET IDENTITY_INSERT [crt].[UPLOADSESSION] OFF;
    COMMIT TRANSACTION;
END;


GO
PRINT N'Finished creating stored procedure [crt].[RESEEDUPLOADSESSIONIDENTITY]'
GO
-- End creating stored procedure [crt].[RESEEDUPLOADSESSIONIDENTITY]


GRANT EXECUTE ON [crt].[RESEEDUPLOADSESSIONIDENTITY] TO [DataSyncUsersRole];
GO

-- Creating stored procedure [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST]
PRINT N'Creating stored procedure [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST].';
END
GO


ALTER PROCEDURE [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST]
    @EmailVARCHAR(100),
    @ActivationTokenVARCHAR(50)
AS
BEGIN
UPDATE [crt].[RETAILCUSTOMEREMAILACTIVATION] SET STATUS = [crt].GETCLOSEDACCOUNTACTIVATIONREQUESTSTATUS()
WHERE ACTIVATIONID = CAST(@ActivationToken AS UNIQUEIDENTIFIER) AND EMAIL = @Email AND STATUS = [crt].GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS() 

-- Clean up requrests older than one week
DELETE FROM [crt].[RETAILCUSTOMEREMAILACTIVATION]
WHERE LASTMODIFIEDTIME < DATEADD(DAY, -7, SYSUTCDATETIME())
END;


GO
PRINT N'Finished creating stored procedure [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST]'
GO
-- End creating stored procedure [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST]


GRANT EXECUTE ON [crt].[COMPLETECUSTOMERACCOUNTACTIVATIONREQUEST] TO [UsersRole];
GO

-- Creating stored procedure [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST]
PRINT N'Creating stored procedure [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST].';
END
GO


ALTER PROCEDURE [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST]
    @EmailVARCHAR(256),
@ActivationTokenVARCHAR(256)
AS
BEGIN
SET NOCOUNT ON;

-- If there is existing request, update the request; otherwise, create a new request
    MERGE [crt].[RETAILCUSTOMEREMAILACTIVATION] AS target
    USING (SELECT @Email, @ActivationToken) AS source (EMAIL, ACTIVATIONID)
    ON (target.EMAIL = source.EMAIL AND target.ACTIVATIONID = source.ACTIVATIONID AND STATUS = [crt].GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS())
    WHEN MATCHED THEN 
        UPDATE SET LASTMODIFIEDTIME = SYSUTCDATETIME()
WHEN NOT MATCHED THEN
    INSERT (EMAIL, ACTIVATIONID, LASTMODIFIEDTIME, STATUS)
    VALUES (source.EMAIL, source.ACTIVATIONID, SYSUTCDATETIME(), [crt].GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS());
END;


GO
PRINT N'Finished creating stored procedure [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST]'
GO
-- End creating stored procedure [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST]


GRANT EXECUTE ON [crt].[SAVECUSTOMERACCOUNTACTIVATIONREQUEST] TO [UsersRole];
GO

-- Creating stored procedure [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST]
PRINT N'Creating stored procedure [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST].';
END
GO


ALTER PROCEDURE [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST]
    @EmailVARCHAR(100),
    @ActivationTokenVARCHAR(50)
AS
BEGIN
    IF EXISTS (SELECT * FROM [crt].[RETAILCUSTOMEREMAILACTIVATION]
WHERE
ACTIVATIONID = CAST(@ActivationToken AS UNIQUEIDENTIFIER) AND
EMAIL = @Email AND
STATUS = [crt].GETACTIVEACCOUNTACTIVATIONREQUESTSTATUS())
RETURN 0;
ELSE
RETURN 1;
END;


GO
PRINT N'Finished creating stored procedure [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST]'
GO
-- End creating stored procedure [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST]


GRANT EXECUTE ON [crt].[VALIDATECUSTOMERACCOUNTACTIVATIONREQUEST] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTINVOICETRANS]
PRINT N'Creating stored procedure [crt].[INSERTINVOICETRANS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTINVOICETRANS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTINVOICETRANS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTINVOICETRANS].';
END
GO


ALTER PROCEDURE [crt].[INSERTINVOICETRANS]
    @bi_ChannelId           BIGINT,
    @TVP_InvoiceTrans       [crt].[RETAILTRANSACTIONORDERINVOICETRANSTABLETYPE]    READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode               INT;
    DECLARE @i_TransactionIsOurs        INT;
    DECLARE @i_Error                    INT;

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SELECT @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 1;
    END;

    -- Perform Insert
    INSERT INTO [ax].RETAILTRANSACTIONORDERINVOICETRANS
    (
        [DATAAREAID],
        [INVOICEID],
        [AMOUNTCUR],        
        [SALESORDERINVOICETYPE],
        [TRANSACTIONSTATUS],
        [LINENUM],
        [STOREID],
        [TERMINALID],
        [TRANSACTIONID],
        [CHANNEL]
    )
    SELECT
        [DATAAREAID],
        [INVOICEID],
        [AMOUNTCUR],
        1,--OrderInvoiceType::Invoice == 1
        [TRANSACTIONSTATUS],
        [LINENUM],
        [STOREID],
        [TERMINALID],
        [TRANSACTIONID],
        @bi_ChannelId
    FROM @TVP_InvoiceTrans AS Source;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTINVOICETRANS]'
GO
-- End creating stored procedure [crt].[INSERTINVOICETRANS]


GRANT EXECUTE ON [crt].[INSERTINVOICETRANS] TO [UsersRole];
GO

-- Creating stored procedure [crt].CREATEUPDATECUSTOMERAFFILIATION
PRINT N'Creating stored procedure [crt].CREATEUPDATECUSTOMERAFFILIATION';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].CREATEUPDATECUSTOMERAFFILIATION', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].CREATEUPDATECUSTOMERAFFILIATION AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].CREATEUPDATECUSTOMERAFFILIATION.';
END
GO


ALTER PROCEDURE [crt].[CREATEUPDATECUSTOMERAFFILIATION]
    @CUSTOMERACCOUNTNUMBER              NVARCHAR(20) = '',
@DATAAREAID                         NVARCHAR(10) ='',
    @TVP_CUSTOMERAFFILIATIONTABLETYPE   [crt].CUSTOMERAFFILIATIONTABLETYPE   READONLY
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @i_ReturnCode                       INT;
    DECLARE @i_TransactionIsOurs                INT;
    DECLARE @i_Error                            INT;
    DECLARE @n_DataAreaId                       NVARCHAR(4);

    -- initializes the return code and assume the transaction is not ours by default
    SET @i_ReturnCode = 0;
    SET @i_TransactionIsOurs = 0;
IF LEN(@DATAAREAID) > 4
BEGIN
SET @n_DataAreaId = SUBSTRING(@DATAAREAID,1,4);
END
ELSE
BEGIN
SET @n_DataAreaId = SUBSTRING(@DATAAREAID,1,LEN(@DATAAREAID));
END

    IF @@TRANCOUNT = 0
    BEGIN
        BEGIN TRANSACTION;

        SET @i_TransactionIsOurs = 1;
    END

-- Delete all the affiliations of the customer firstly.
DELETE FROM  [ax].RETAILCUSTAFFILIATION
WHERE [ax].RETAILCUSTAFFILIATION.CUSTACCOUNTNUM = @CUSTOMERACCOUNTNUMBER 
AND [ax].RETAILCUSTAFFILIATION.DATAAREAID = @n_DataAreaId;

-- Insert all the affiliations of the customer.
    INSERT INTO [ax].RETAILCUSTAFFILIATION (
RECID,
CUSTACCOUNTNUM,
RETAILAFFILIATIONID,
DATAAREAID)
SELECT 
RECID,
CUSTACCOUNTNUM,
RETAILAFFILIATIONID,
@n_DataAreaId
FROM @TVP_CUSTOMERAFFILIATIONTABLETYPE;

    SELECT @i_Error = @@ERROR;
    IF @i_Error <> 0
    BEGIN
        SET @i_ReturnCode = @i_Error;
        GOTO exit_label;
    END;

    IF @i_TransactionIsOurs = 1
    BEGIN
        COMMIT TRANSACTION;

        SET @i_Error = @@ERROR;
        IF @i_Error <> 0
        BEGIN
            SET @i_ReturnCode = @i_Error;
            GOTO exit_label;
        END;

        SET @i_TransactionIsOurs = 0;
    END;

exit_label:

    IF @i_TransactionIsOurs = 1
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    RETURN @i_ReturnCode;
END;


GO
PRINT N'Finished creating stored procedure [crt].CREATEUPDATECUSTOMERAFFILIATION'
GO
-- End creating stored procedure [crt].CREATEUPDATECUSTOMERAFFILIATION


GRANT EXECUTE ON [crt].CREATEUPDATECUSTOMERAFFILIATION TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETACTIVELOYALTYCARDTIERS]
PRINT N'Creating stored procedure [crt].[GETACTIVELOYALTYCARDTIERS]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETACTIVELOYALTYCARDTIERS]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETACTIVELOYALTYCARDTIERS] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETACTIVELOYALTYCARDTIERS].';
END
GO


ALTER PROCEDURE [crt].[GETACTIVELOYALTYCARDTIERS]
    @nvc_LoyaltyCardNumber            NVARCHAR(30),
    @dt_channelLocalDate              DATE
AS
BEGIN
    SET NOCOUNT ON
    
    SELECT 
        ral.AFFILIATION,
        COALESCE(tier.RECID, 0) AS LOYALTYTIER
    FROM (
        SELECT rlct.AFFILIATION, MAX(COALESCE(rlt.TIERLEVEL, 0)) AS MAXTIERLEVEL
        FROM [ax].[RETAILLOYALTYCARD] rlc
        JOIN [ax].[RETAILLOYALTYCARDTIER] rlct
            ON rlc.RECID = rlct.LOYALTYCARD
        LEFT JOIN [ax].[RETAILLOYALTYTIER] rlt
            ON rlct.LOYALTYTIER = rlt.RECID
        WHERE rlc.CARDNUMBER = @nvc_LoyaltyCardNumber
            AND (rlct.VALIDFROM IS NULL OR rlct.VALIDFROM <= @dt_channelLocalDate)
            AND (rlct.VALIDTO IS NULL OR rlct.VALIDTO >= @dt_channelLocalDate)
        GROUP BY rlct.AFFILIATION
    ) ral
    LEFT JOIN [ax].[RETAILLOYALTYTIER] tier
        ON (tier.AFFILIATION = ral.AFFILIATION AND tier.TIERLEVEL = ral.MAXTIERLEVEL)
END;


GO
PRINT N'Finished creating stored procedure [crt].[GETACTIVELOYALTYCARDTIERS]'
GO
-- End creating stored procedure [crt].[GETACTIVELOYALTYCARDTIERS]


GRANT EXECUTE ON [crt].[GETACTIVELOYALTYCARDTIERS] TO [UsersRole];
GO

-- Creating stored procedure [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE]
PRINT N'Creating stored procedure [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[GETAFFILIATIONSBYAFFILIATIONTYPE]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE].';
END
GO


ALTER PROCEDURE [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE]
    @i_affiliationType        INT,
@nvc_LocaleNVARCHAR(7)
AS
BEGIN
    SET NOCOUNT ON

    -- Select all RetailAffiliation which are associated with the affiliation type
SELECT
ra.RECID,
ra.AFFILIATIONTYPE,
ra.NAME,
rat.DESCRIPTION
FROM [crt].[RETAILAFFILIATIONSVIEW] ra
LEFT JOIN [ax].[RETAILAFFILIATIONTRANSLATION] rat
   ON rat.AFFILIATION = ra.RECID
    AND rat.LANGUAGEID = @nvc_Locale
WHERE ra.AFFILIATIONTYPE = @i_affiliationType

END;


GO
PRINT N'Finished creating stored procedure [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE]'
GO
-- End creating stored procedure [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE]


GRANT EXECUTE ON [crt].[GETAFFILIATIONSBYAFFILIATIONTYPE] TO [UsersRole];
GO

-- Creating stored procedure [crt].[INSERTRETAILSTAFFLOGINLOG]
PRINT N'Creating stored procedure [crt].[INSERTRETAILSTAFFLOGINLOG]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[INSERTRETAILSTAFFLOGINLOG]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[INSERTRETAILSTAFFLOGINLOG] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[INSERTRETAILSTAFFLOGINLOG].';
END
GO


ALTER PROCEDURE [crt].[INSERTRETAILSTAFFLOGINLOG]
     @TERMINALID nvarchar(10)
    ,@CHANNELID nvarchar(10)
    ,@STAFFID   nvarchar(25)    
    ,@DATAAREAID nvarchar(4)
,@RETURN_VALUE int output
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_Error INT;
DECLARE @loggedInTermianlId nvarchar(10);

SET @loggedInTermianlId = (SELECT TOP 1 TERMINALID FROM [crt].[RETAILSTAFFLOGINLOG]
WHERE CHANNELID = @CHANNELID AND STAFFID = @STAFFID AND DATAAREAID = @DATAAREAID)

IF(@loggedInTermianlId IS NULL)
BEGIN
INSERT INTO [crt].[RETAILSTAFFLOGINLOG]
(
[CHANNELID],
[TERMINALID],
[STAFFID],
[DATAAREAID],
[CREATEDDATETIME]
)
VALUES(@CHANNELID,
   @TERMINALID,    
   @STAFFID, 
   @DATAAREAID,
   GETDATE()   
   )

SELECT @i_Error = @@ERROR;

IF @i_Error <> 0
BEGIN
SET @RETURN_VALUE = @i_Error;        
END;
ELSE
BEGIN 
SET @RETURN_VALUE = 1;
END
END 
ELSE
BEGIN 
IF (@loggedInTermianlId = @TERMINALID)
BEGIN 
SET @RETURN_VALUE = 1;
END
ELSE
BEGIN 
SET @RETURN_VALUE = 0;
END 
END
END;


GO
PRINT N'Finished creating stored procedure [crt].[INSERTRETAILSTAFFLOGINLOG]'
GO
-- End creating stored procedure [crt].[INSERTRETAILSTAFFLOGINLOG]


GRANT EXECUTE ON [crt].[INSERTRETAILSTAFFLOGINLOG] TO [UsersRole];
GO

-- Creating stored procedure [crt].[DELETERETAILSTAFFLOGINLOG]
PRINT N'Creating stored procedure [crt].[DELETERETAILSTAFFLOGINLOG]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[crt].[DELETERETAILSTAFFLOGINLOG]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [crt].[DELETERETAILSTAFFLOGINLOG] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [crt].[DELETERETAILSTAFFLOGINLOG].';
END
GO


ALTER PROCEDURE [crt].[DELETERETAILSTAFFLOGINLOG]     
     @CHANNELID nvarchar(10)
    ,@STAFFID   nvarchar(25)    
    ,@DATAAREAID nvarchar(4)
,@RETURN_VALUE int output
AS
BEGIN
    SET NOCOUNT ON
    DECLARE @i_Error INT;
SET @RETURN_VALUE = 1;
DECLARE @allowMultipleLogin INT;

SET @allowMultipleLogin = (SELECT ALLOWMULTIPLELOGINS FROM [crt].EMPLOYEEPERMISSIONSVIEW WHERE STAFFID = @STAFFID)

IF @allowMultipleLogin = 0
BEGIN 
DELETE FROM [crt].[RETAILSTAFFLOGINLOG]
WHERE CHANNELID = @CHANNELID AND STAFFID = @STAFFID AND DATAAREAID = @DATAAREAID;

SELECT @i_Error = @@ERROR;
IF @i_Error <> 0
BEGIN
SET @RETURN_VALUE = @i_Error;        
END;
END
END;


GO
PRINT N'Finished creating stored procedure [crt].[DELETERETAILSTAFFLOGINLOG]'
GO
-- End creating stored procedure [crt].[DELETERETAILSTAFFLOGINLOG]


GRANT EXECUTE ON [crt].[DELETERETAILSTAFFLOGINLOG] TO [UsersRole];
GO

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[CUSTPACKINGSLIPJOUR]', N'U'), N'IX_CUSTPACKINGSLIPJOUR_PACKINGSLIPID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_CUSTPACKINGSLIPJOUR_PACKINGSLIPID'


CREATE NONCLUSTERED INDEX [IX_CUSTPACKINGSLIPJOUR_PACKINGSLIPID] ON [ax].[CUSTPACKINGSLIPJOUR]
(
    [PACKINGSLIPID]
)
INCLUDE
(
    [SALESID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_CUSTPACKINGSLIPJOUR_PACKINGSLIPID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[CUSTPACKINGSLIPTRANS]', N'U'), N'IX_CUSTPACKINGSLIPTRANS_PACKINGSLIPID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_CUSTPACKINGSLIPTRANS_PACKINGSLIPID'


CREATE NONCLUSTERED INDEX [IX_CUSTPACKINGSLIPTRANS_PACKINGSLIPID] ON [ax].[CUSTPACKINGSLIPTRANS]
(
    [PACKINGSLIPID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_CUSTPACKINGSLIPTRANS_PACKINGSLIPID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[DIRPARTYLOCATION]', N'U'), N'IX_DIRPARTYLOCATION_CODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_DIRPARTYLOCATION_CODE'


CREATE NONCLUSTERED INDEX [IX_DIRPARTYLOCATION_CODE] ON [ax].[DIRPARTYLOCATION]
(
    [LOCATION],
    [ISPOSTALADDRESS],
    [ISPRIMARY]
)
INCLUDE
(
    [PARTY]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_DIRPARTYLOCATION_CODE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESATTRIBUTEDEFAULTVALUE]', N'U'), N'IX_ECORESATTRIBUTEDEFAULTVALUE_ATTRIBUTE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESATTRIBUTEDEFAULTVALUE_ATTRIBUTE'


CREATE NONCLUSTERED INDEX IX_ECORESATTRIBUTEDEFAULTVALUE_ATTRIBUTE ON [ax].[ECORESATTRIBUTEDEFAULTVALUE] 
(
    ATTRIBUTE
)
INCLUDE
(
VALUE
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESATTRIBUTEDEFAULTVALUE_ATTRIBUTE'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESATTRIBUTEDEFAULTVALUE]', N'U'), N'IX_ECORESATTRIBUTEDEFAULTVALUE_VALUE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESATTRIBUTEDEFAULTVALUE_VALUE'


CREATE NONCLUSTERED INDEX IX_ECORESATTRIBUTEDEFAULTVALUE_VALUE ON [ax].[ECORESATTRIBUTEDEFAULTVALUE] 
(
VALUE
)
INCLUDE
(
    ATTRIBUTE
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESATTRIBUTEDEFAULTVALUE_VALUE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESDISTINCTPRODUCTVARIANT]', N'U'), N'IX_ECORESDISTINCTPRODUCTVARIANT_PRODUCTMASTER', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESDISTINCTPRODUCTVARIANT_PRODUCTMASTER'


CREATE NONCLUSTERED INDEX IX_ECORESDISTINCTPRODUCTVARIANT_PRODUCTMASTER ON [ax].[ECORESDISTINCTPRODUCTVARIANT] 
(
    PRODUCTMASTER
)
INCLUDE
(
    RECID
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESDISTINCTPRODUCTVARIANT_PRODUCTMASTER'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESPRODUCTCATEGORY]', N'U'), N'IX_ECORESPRODUCTCATEGORY_CATEGORY', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESPRODUCTCATEGORY_CATEGORY'


CREATE NONCLUSTERED INDEX [IX_ECORESPRODUCTCATEGORY_CATEGORY] ON [ax].[ECORESPRODUCTCATEGORY] 
(
    [CATEGORY]
)
INCLUDE
(
    [PRODUCT]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESPRODUCTCATEGORY_CATEGORY'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESPRODUCTCATEGORY]', N'U'), N'IX_ECORESPRODUCTCATEGORY_CATEGORYHIERARCHY', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESPRODUCTCATEGORY_CATEGORYHIERARCHY'


CREATE NONCLUSTERED INDEX [IX_ECORESPRODUCTCATEGORY_CATEGORYHIERARCHY] ON [ax].[ECORESPRODUCTCATEGORY] 
(
    [CATEGORYHIERARCHY]
)
INCLUDE 
(
    [PRODUCT],
    [CATEGORY]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESPRODUCTCATEGORY_CATEGORYHIERARCHY'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESPRODUCTCATEGORY]', N'U'), N'IX_ECORESPRODUCTCATEGORY_VERSION', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESPRODUCTCATEGORY_VERSION'


CREATE NONCLUSTERED INDEX [IX_ECORESPRODUCTCATEGORY_VERSION] ON [ax].[ECORESPRODUCTCATEGORY] 
(
    [ROWVERSION]
)
INCLUDE 
(
    [CATEGORY],
    [PRODUCT]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESPRODUCTCATEGORY_VERSION'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[ECORESPRODUCTRELATIONTABLE]', N'U'), N'IX_ECORESPRODUCTRELATIONTABLE_PRODUCT2', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_ECORESPRODUCTRELATIONTABLE_PRODUCT2'


CREATE NONCLUSTERED INDEX [IX_ECORESPRODUCTRELATIONTABLE_PRODUCT2] ON [ax].[ECORESPRODUCTRELATIONTABLE] 
(
    PRODUCT2
)
INCLUDE
(
    PRODUCT1
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_ECORESPRODUCTRELATIONTABLE_PRODUCT2'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[HCMJOB]', N'U'), N'IX_HCMJOB_CODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_HCMJOB_CODE'


CREATE NONCLUSTERED INDEX IX_HCMJOB_CODE ON [ax].[HCMJOB]
(
    [RECID]
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_HCMJOB_CODE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[HCMPOSITION]', N'U'), N'IX_HCMPOSITION_CODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_HCMPOSITION_CODE'


CREATE NONCLUSTERED INDEX IX_HCMPOSITION_CODE ON [ax].[HCMPOSITION]
(
    [RECID]
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[HCMPOSITIONWORKERASSIGNMENT]', N'U'), N'IX_HCMPOSITIONWORKERASSIGNMENT_CODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_HCMPOSITIONWORKERASSIGNMENT_CODE'


CREATE NONCLUSTERED INDEX IX_HCMPOSITIONWORKERASSIGNMENT_CODE ON [ax].[HCMPOSITIONWORKERASSIGNMENT]
(
    [POSITION]
)
INCLUDE
(
    [WORKER]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_HCMPOSITIONWORKERASSIGNMENT_CODE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[HCMWORKER]', N'U'), N'IX_HCMWORKER_CODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_HCMWORKER_CODE'


CREATE NONCLUSTERED INDEX IX_HCMWORKER_CODE ON [ax].[HCMWORKER]
(
    [PERSONNELNUMBER]
) 
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_HCMWORKER_CODE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLEMODULE]', N'U'), N'IX_INVENTTABLEMODULE_MODULE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLEMODULE_MODULE'


CREATE NONCLUSTERED INDEX [IX_INVENTTABLEMODULE_MODULE] ON [ax].[INVENTTABLEMODULE]
(
    [MODULETYPE]
)
INCLUDE
(
    [ITEMID],
    [UNITID],
    [PRICE],
    [MARKUP],
    [LINEDISC],
    [MULTILINEDISC],
    [ENDDISC],
    [TAXITEMGROUPID],
    [MARKUPGROUPID],
    [PRICEQTY],
    [ALLOCATEMARKUP]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTTABLEMODULE_MODULE'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLEMODULE]', N'U'), N'IX_INVENTTABLEMODULE_MODULE_ITEM_UNIT', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLEMODULE_MODULE_ITEM_UNIT'


CREATE NONCLUSTERED INDEX [IX_INVENTTABLEMODULE_MODULE_ITEM_UNIT] ON [ax].[INVENTTABLEMODULE]
(
    [MODULETYPE] ASC,
    [ITEMID] ASC,
    [UNITID] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTTABLEMODULE_MODULE_ITEM_UNIT'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLEMODULE]', N'U'), N'IX_INVENTTABLEMODULE_MODULE_VERSION', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLEMODULE_MODULE_VERSION'


CREATE NONCLUSTERED INDEX [IX_INVENTTABLEMODULE_MODULE_VERSION] ON [ax].[INVENTTABLEMODULE]
(
    [MODULETYPE],
    [ROWVERSION]
)
INCLUDE
(
    [ITEMID]
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index [IX_INVENTTABLEMODULE_MODULE_VERSION]'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTTABLEMODULE]', N'U'), N'IX_INVENTTABLEMODULE_ITEM_TYPE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTTABLEMODULE_ITEM_TYPE'


CREATE NONCLUSTERED INDEX [IX_INVENTTABLEMODULE_ITEM_TYPE] ON [ax].[INVENTTABLEMODULE]
(
    [ITEMID] ASC,
    [MODULETYPE] ASC
)
INCLUDE
(
    [ALLOCATEMARKUP],
    [ENDDISC],
    [LINEDISC],
    [MARKUP],
    [MARKUPGROUPID],
    [MULTILINEDISC],
    [PRICE],
    [PRICEQTY],
    [TAXITEMGROUPID],
    [UNITID]
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index [IX_INVENTTABLEMODULE_ITEM_TYPE]'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[LOGISTICSELECTRONICADDRESS]', N'U'), N'IX_LOGISTICSELECTRONICADDRESS_PRIV_LOC_PRIM_MOBILE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_LOGISTICSELECTRONICADDRESS_PRIV_LOC_PRIM_MOBILE'


CREATE NONCLUSTERED INDEX [IX_LOGISTICSELECTRONICADDRESS_PRIV_LOC_PRIM_MOBILE] ON [ax].[LOGISTICSELECTRONICADDRESS] 
(
[ISPRIVATE] ASC,
[LOCATION] ASC,
[ISPRIMARY] ASC,
[ISMOBILEPHONE] ASC
)
INCLUDE ( [RECID],
[DESCRIPTION],
[LOCATOR],
[LOCATOREXTENSION],
[TYPE]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_LOGISTICSELECTRONICADDRESS_PRIV_LOC_PRIM_MOBILE'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[LOGISTICSELECTRONICADDRESS]', N'U'), N'IX_LOGISTICSELECTRONICADDRESS_PRIM_PRIV_TYP', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_LOGISTICSELECTRONICADDRESS_PRIM_PRIV_TYP'


CREATE NONCLUSTERED INDEX IX_LOGISTICSELECTRONICADDRESS_PRIM_PRIV_TYP ON [ax].[LOGISTICSELECTRONICADDRESS]
(
[ISPRIMARY] ASC,
[ISPRIVATE] ASC,
[TYPE] ASC
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_LOGISTICSELECTRONICADDRESS_PRIM_PRIV_TYP'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[LOGISTICSLOCATION]', N'U'), N'IX_LOGISTICSLOCATION_ISPOSTAL_PARENTLOC_RECID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_LOGISTICSLOCATION_ISPOSTAL_PARENTLOC_RECID'


CREATE NONCLUSTERED INDEX [IX_LOGISTICSLOCATION_ISPOSTAL_PARENTLOC_RECID] ON [ax].[LOGISTICSLOCATION] 
(
    [ISPOSTALADDRESS],
[PARENTLOCATION],
RECID
)
INCLUDE ([LOCATIONID])
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_LOGISTICSLOCATION_ISPOSTAL_PARENTLOC_RECID'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[PRICEDISCTABLE]', N'U'), N'IX_PRICEDISCTABLE_ITEMCODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_PRICEDISCTABLE_ITEMCODE'


CREATE NONCLUSTERED INDEX [IX_PRICEDISCTABLE_ITEMCODE] ON [ax].[PRICEDISCTABLE] 
(
    [ITEMCODE],
    [ACCOUNTCODE],
    [RELATION]
)
INCLUDE
(
    [ITEMRELATION],
    [ACCOUNTRELATION],
    [INVENTDIMID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_PRICEDISCTABLE_ITEMCODE'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[PRICEDISCTABLE]', N'U'), N'IX_PRICEDISCTABLE_ACCT_REL_ITEM_ACCTREL', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_PRICEDISCTABLE_ACCT_REL_ITEM_ACCTREL'


CREATE NONCLUSTERED INDEX [IX_PRICEDISCTABLE_ACCT_REL_ITEM_ACCTREL] ON [ax].[PRICEDISCTABLE] 
(
    [ACCOUNTCODE] ASC,
    [RELATION] ASC,
    [ITEMCODE] ASC,
    [ACCOUNTRELATION] ASC
)
INCLUDE 
( 
    [ITEMRELATION]
) 
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_PRICEDISCTABLE_ACCT_REL_ITEM_ACCTREL'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[PRICEDISCTABLE]', N'U'), N'IX_PRICEDISCTABLE_RELATION_VERSION', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_PRICEDISCTABLE_RELATION_VERSION'


CREATE NONCLUSTERED INDEX [IX_PRICEDISCTABLE_RELATION_VERSION] ON [ax].[PRICEDISCTABLE] 
(
    [RELATION],
    [ROWVERSION]
)
INCLUDE 
(
    [ITEMRELATION],
    [INVENTDIMID]
)


END
ELSE
    PRINT 'Existing index IX_PRICEDISCTABLE_RELATION_VERSION'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILCATEGORYCONTAINMENTLOOKUP]', N'U'), N'IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY'


CREATE NONCLUSTERED INDEX [IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY] ON [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] 
(
    [CATEGORY]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILCATEGORYCONTAINMENTLOOKUP]', N'U'), N'IX_RETAILCATEGORYCONTAINMENTLOOKUP_CONTAINEDCATEGORY_RECID_CATEGORY', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILCATEGORYCONTAINMENTLOOKUP_CONTAINEDCATEGORY_RECID_CATEGORY'


CREATE NONCLUSTERED INDEX [IX_RETAILCATEGORYCONTAINMENTLOOKUP_CONTAINEDCATEGORY_RECID_CATEGORY] ON [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] 
(
    [CONTAINEDCATEGORY] ASC,
    [RECID] ASC,
    [CATEGORY] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILCATEGORYCONTAINMENTLOOKUP_CONTAINEDCATEGORY_RECID_CATEGORY'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILCATEGORYCONTAINMENTLOOKUP]', N'U'), N'IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY_RECID_CONTAINEDCATEGORY', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY_RECID_CONTAINEDCATEGORY'


CREATE NONCLUSTERED INDEX [IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY_RECID_CONTAINEDCATEGORY] ON [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] 
(
    [CATEGORY] ASC,
    [RECID] ASC,
    [CONTAINEDCATEGORY] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILCATEGORYCONTAINMENTLOOKUP_CATEGORY_RECID_CONTAINEDCATEGORY'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILCATEGORYCONTAINMENTLOOKUP]', N'U'), N'IX_RETAILCATEGORYCONTAINMENTLOOKUP_VERSION', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILCATEGORYCONTAINMENTLOOKUP_VERSION'


CREATE NONCLUSTERED INDEX [IX_RETAILCATEGORYCONTAINMENTLOOKUP_VERSION] ON [ax].[RETAILCATEGORYCONTAINMENTLOOKUP] 
(
    [ROWVERSION]
)
INCLUDE 
(
    [CATEGORY],
    [CONTAINEDCATEGORY]
)


END
ELSE
    PRINT 'Existing index IX_RETAILCATEGORYCONTAINMENTLOOKUP_VERSION'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILINVENTAVAILABILITY]', N'U'), N'IX_RETAILINVENTAVAILABILITY_RECID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILINVENTAVAILABILITY_RECID'


CREATE NONCLUSTERED INDEX [IX_RETAILINVENTAVAILABILITY_RECID] ON [ax].[RETAILINVENTAVAILABILITY] 
(
    [INVENTDIMRECID]
)
INCLUDE
(
    [ITEMRECID],
    [LASTINVENTTRANS],
    [RECID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILINVENTAVAILABILITY_RECID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].RETAILLISTINGSTATUSLOG', N'U'), N'IX_RETAILLISTINGSTATUSLOG_CHANNELBATCHID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILLISTINGSTATUSLOG_CHANNELBATCHID'


CREATE NONCLUSTERED INDEX IX_RETAILLISTINGSTATUSLOG_CHANNELBATCHID ON [ax].RETAILLISTINGSTATUSLOG
(
    CHANNELBATCHID
)


END
ELSE
    PRINT 'Existing index IX_RETAILLISTINGSTATUSLOG_CHANNELBATCHID'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].RETAILLISTINGSTATUSLOG', N'U'), N'IX_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIME', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIME'


CREATE NONCLUSTERED INDEX IX_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIME ON [ax].RETAILLISTINGSTATUSLOG
(
    LISTINGMODIFIEDDATETIME
)


END
ELSE
    PRINT 'Existing index IX_RETAILLISTINGSTATUSLOG_LISTINGMODIFIEDDATETIME'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPOSPERMISSIONGROUP]', N'U'), N'IX_RETAILPOSPERMISSIONGROUP_CODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPOSPERMISSIONGROUP_CODE'


CREATE NONCLUSTERED INDEX IX_RETAILPOSPERMISSIONGROUP_CODE ON [ax].[RETAILPOSPERMISSIONGROUP]
(
    [RECID]
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPOSPERMISSIONGROUP_CODE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBCATALOG]', N'U'), N'IX_RETAILPUBCATALOG_VALIDFROM_VALIDTO', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBCATALOG_VALIDFROM_VALIDTO'


CREATE NONCLUSTERED INDEX IX_RETAILPUBCATALOG_VALIDFROM_VALIDTO ON [ax].[RETAILPUBCATALOG] 
(
    VALIDFROM,
VALIDTO
)
INCLUDE
(
    ORIGIN
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBCATALOG_VALIDFROM_VALIDTO'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBCATALOGPRODUCTCATEGORY]', N'U'), N'IX_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORY', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORY'


CREATE NONCLUSTERED INDEX IX_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORY ON [ax].[RETAILPUBCATALOGPRODUCTCATEGORY] 
(
    CATEGORY
)
INCLUDE
(
    ORIGIN,
INCLUDEEXCLUDETYPE
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBCATALOGPRODUCTCATEGORY_CATEGORY'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBCATALOGPRODUCT]', N'U'), N'IX_RETAILPUBCATALOGPRODUCT_PRODUCT', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBCATALOGPRODUCT_PRODUCT'


CREATE NONCLUSTERED INDEX IX_RETAILPUBCATALOGPRODUCT_PRODUCT ON [ax].[RETAILPUBCATALOGPRODUCT] 
(
    PRODUCT
)
INCLUDE
(
[CATALOG]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBCATALOGPRODUCT_PRODUCT'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA]', N'U'), N'IX_RETAILPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTE'


CREATE NONCLUSTERED INDEX IX_RETAILPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTE ON [ax].[RETAILPUBPRODUCTATTRIBUTECHANNELMETADATA] 
(
    [ATTRIBUTE] ASC,
    [HOSTCHANNEL] ASC
)
INCLUDE 
(
    [KEYNAME]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPRODUCTATTRIBUTECHANNELMETADATA_ATTRIBUTE'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBPRODUCTATTRIBUTEVALUE]', N'U'), N'IX_RETAILPUBPRODUCTATTRIBUTEVALUE_ATTRIBUTE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_ATTRIBUTE'


CREATE NONCLUSTERED INDEX IX_RETAILPUBPRODUCTATTRIBUTEVALUE_ATTRIBUTE ON [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] 
(
    ATTRIBUTE
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_ATTRIBUTE'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBPRODUCTATTRIBUTEVALUE]', N'U'), N'IX_RETAILPUBPRODUCTATTRIBUTEVALUE_PRODUCT', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_PRODUCT'


CREATE NONCLUSTERED INDEX IX_RETAILPUBPRODUCTATTRIBUTEVALUE_PRODUCT ON [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] 
(
    PRODUCT
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_PRODUCT'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBPRODUCTATTRIBUTEVALUE]', N'U'), N'IX_RETAILPUBPRODUCTATTRIBUTEVALUE_INTERNALORGANIZATION', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_INTERNALORGANIZATION'


CREATE NONCLUSTERED INDEX [IX_RETAILPUBPRODUCTATTRIBUTEVALUE_INTERNALORGANIZATION] ON [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] 
(
    INTERNALORGANIZATION
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_INTERNALORGANIZATION'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPUBPRODUCTATTRIBUTEVALUE]', N'U'), N'IX_RETAILPUBPRODUCTATTRIBUTEVALUE_LANGUAGEID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_LANGUAGEID'


CREATE NONCLUSTERED INDEX IX_RETAILPUBPRODUCTATTRIBUTEVALUE_LANGUAGEID ON [ax].[RETAILPUBPRODUCTATTRIBUTEVALUE] 
(
    LANGUAGEID
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPUBPRODUCTATTRIBUTEVALUE_LANGUAGEID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONSALESTRANS]', N'U'), N'IX_RETAILTRANSACTIONSALESTRANS_INVENTDIMID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONSALESTRANS_INVENTDIMID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONSALESTRANS_INVENTDIMID ON [ax].[RETAILTRANSACTIONSALESTRANS]
(
    [INVENTDIMID]
) 
INCLUDE
(
    [TRANSACTIONID],
    [ITEMID],
    [QTY],
    [STORE],
    [TERMINALID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONSALESTRANS_INVENTDIMID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONADDRESSTRANS]', N'U'), N'IX_RETAILTRANSACTIONADDRESSTRANS_TRANSACTIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONADDRESSTRANS_TRANSACTIONID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONADDRESSTRANS_TRANSACTIONID ON [ax].[RETAILTRANSACTIONADDRESSTRANS]
(
    [TRANSACTIONID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONADDRESSTRANS_TRANSACTIONID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONATTRIBUTETRANS]', N'U'), N'IX_RETAILTRANSACTIONATTRIBUTETRANS_TRANSACTIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONATTRIBUTETRANS_TRANSACTIONID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONATTRIBUTETRANS_TRANSACTIONID ON [ax].[RETAILTRANSACTIONATTRIBUTETRANS]
(
    [TRANSACTIONID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONATTRIBUTETRANS_TRANSACTIONID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONDISCOUNTTRANS]', N'U'), N'IX_RETAILTRANSACTIONDISCOUNTTRANS_TRANSACTIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONDISCOUNTTRANS_TRANSACTIONID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONDISCOUNTTRANS_TRANSACTIONID ON [ax].[RETAILTRANSACTIONDISCOUNTTRANS]
(
    [TRANSACTIONID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONDISCOUNTTRANS_TRANSACTIONID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONMARKUPTRANS]', N'U'), N'IX_RETAILTRANSACTIONMARKUPTRANS_TRANSACTIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONMARKUPTRANS_TRANSACTIONID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONMARKUPTRANS_TRANSACTIONID ON [ax].[RETAILTRANSACTIONMARKUPTRANS]
(
    [TRANSACTIONID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONMARKUPTRANS_TRANSACTIONID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONORDERSTATUS]', N'U'), N'IX_RETAILTRANSACTIONORDERSTATUS_SALESID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONORDERSTATUS_SALESID'


CREATE NONCLUSTERED INDEX [IX_RETAILTRANSACTIONORDERSTATUS_SALESID] ON [ax].[RETAILTRANSACTIONORDERSTATUS]
(
    [SALESID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONORDERSTATUS_SALESID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONPAYMENTTRANS]', N'U'), N'IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONID ON [ax].[RETAILTRANSACTIONPAYMENTTRANS]
(
    [TRANSACTIONID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONID'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONPAYMENTTRANS]', N'U'), N'IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONSTATUS', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONSTATUS'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONSTATUS ON [ax].[RETAILTRANSACTIONPAYMENTTRANS]
(
    TRANSACTIONSTATUS
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONPAYMENTTRANS_TRANSACTIONSTATUS'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONTABLE]', N'U'), N'IX_RETAILTRANSACTIONTABLE_MODIFIEDDATETIME', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONTABLE_MODIFIEDDATETIME'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONTABLE_MODIFIEDDATETIME ON [ax].[RETAILTRANSACTIONTABLE]
(
    [MODIFIEDDATETIME]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONTABLE_MODIFIEDDATETIME'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONTABLE]', N'U'), N'IX_RETAILTRANSACTIONTABLE_ENTRYSTATUS', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONTABLE_ENTRYSTATUS'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONTABLE_ENTRYSTATUS ON [ax].[RETAILTRANSACTIONTABLE]
(
    ENTRYSTATUS
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONTABLE_ENTRYSTATUS'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONTABLE]', N'U'), N'IX_RETAILTRANSACTIONTABLE_PAYMENTAMOUNT', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONTABLE_PAYMENTAMOUNT'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONTABLE_PAYMENTAMOUNT ON [ax].[RETAILTRANSACTIONTABLE]
(
    [PAYMENTAMOUNT]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONTABLE_PAYMENTAMOUNT'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONTAXTRANS]', N'U'), N'IX_RETAILTRANSACTIONTAXTRANS_TRANSACTIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONTAXTRANS_TRANSACTIONID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONTAXTRANS_TRANSACTIONID ON [ax].[RETAILTRANSACTIONTAXTRANS]
(
    [TRANSACTIONID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONTAXTRANS_TRANSACTIONID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTDIMCOMBINATION]', N'U'), N'IX_INVENTDIMCOMBINATION_DISTPRODUCTVARIANT', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTDIMCOMBINATION_DISTPRODUCTVARIANT'


CREATE NONCLUSTERED INDEX [IX_INVENTDIMCOMBINATION_DISTPRODUCTVARIANT] ON [ax].[INVENTDIMCOMBINATION] 
(
    [DISTINCTPRODUCTVARIANT] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTDIMCOMBINATION_DISTPRODUCTVARIANT'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTDIMCOMBINATION]', N'U'), N'IX_INVENTDIMCOMBINATION_DATAAREAID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTDIMCOMBINATION_DATAAREAID'


CREATE NONCLUSTERED INDEX [IX_INVENTDIMCOMBINATION_DATAAREAID] ON [ax].[INVENTDIMCOMBINATION]
(
    [DATAAREAID]
)
INCLUDE
(
    [DISTINCTPRODUCTVARIANT],
    [RETAILVARIANTID]
)


END
ELSE
    PRINT 'Existing index IX_INVENTDIMCOMBINATION_DATAAREAID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPERIODICDISCOUNT]', N'U'), N'IX_RETAILPERIODICDISCOUNT_PRICEDISCGROUP', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPERIODICDISCOUNT_PRICEDISCGROUP'


CREATE NONCLUSTERED INDEX [IX_RETAILPERIODICDISCOUNT_PRICEDISCGROUP] ON [ax].[RETAILPERIODICDISCOUNT]
(
    [PRICEDISCGROUP] ASC
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPERIODICDISCOUNT_PRICEDISCGROUP'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPERIODICDISCOUNT]', N'U'), N'IX_RETAILPERIODICDISCOUNT_OFFERID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPERIODICDISCOUNT_OFFERID'


CREATE NONCLUSTERED INDEX IX_RETAILPERIODICDISCOUNT_OFFERID ON [ax].[RETAILPERIODICDISCOUNT]
(
    [OFFERID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPERIODICDISCOUNT_OFFERID'




IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILPERIODICDISCOUNT]', N'U'), N'IX_RETAILPERIODICDISCOUNT_NAME_VALIDDATE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILPERIODICDISCOUNT_NAME_VALIDDATE'


CREATE NONCLUSTERED INDEX IX_RETAILPERIODICDISCOUNT_NAME_VALIDDATE ON [ax].[RETAILPERIODICDISCOUNT]
(
    [NAME],
    [VALIDFROM],
    [VALIDTO]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILPERIODICDISCOUNT_NAME_VALIDDATE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILDISCOUNTCODE]', N'U'), N'IX_RetailDiscountCode_DISCOUNTOFFERID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RetailDiscountCode_DISCOUNTOFFERID'


CREATE NONCLUSTERED INDEX IX_RetailDiscountCode_DISCOUNTOFFERID ON [ax].[RETAILDISCOUNTCODE]
(
    [DISCOUNTOFFERID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RetailDiscountCode_DISCOUNTOFFERID'



IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILDISCOUNTCODE]', N'U'), N'IX_RetailDiscountCode_DISCOUNTCODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RetailDiscountCode_DISCOUNTCODE'


CREATE NONCLUSTERED INDEX IX_RetailDiscountCode_DISCOUNTCODE ON [ax].[RETAILDISCOUNTCODE]
(
    [DISCOUNTCODE]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RetailDiscountCode_DISCOUNTCODE'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTITEMBARCODE]', N'U'), N'IX_INVENTITEMBARCODE_ITEMBARCODE', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTITEMBARCODE_ITEMBARCODE'


CREATE NONCLUSTERED INDEX [IX_INVENTITEMBARCODE_ITEMBARCODE] ON [ax].[INVENTITEMBARCODE] 
(
    [ITEMBARCODE] ASC,
[DATAAREAID] ASC
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTITEMBARCODE_ITEMBARCODE'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILINVENTTABLE]', N'U'), N'IX_RETAILINVENTTABLE_ITEM', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILINVENTTABLE_ITEM'


CREATE NONCLUSTERED INDEX [IX_RETAILINVENTTABLE_ITEM] ON [ax].[RETAILINVENTTABLE]
(
    [ITEMID] ASC
)
INCLUDE
(
    [NODISCOUNTALLOWED]
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index [IX_RETAILINVENTTABLE_ITEM]'


IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILSTORETABLE]', N'U'), N'IX_RETAILSTORETABLE_RECID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILSTORETABLE_RECID'


CREATE NONCLUSTERED INDEX IX_RETAILSTORETABLE_RECID ON [ax].[RETAILSTORETABLE] ([RECID]) 
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILSTORETABLE_RECID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[RETAILTRANSACTIONTAXTRANS_IN]', N'U'), N'IX_RETAILTRANSACTIONTAXTRANS_IN_TRANSACTIONID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_RETAILTRANSACTIONTAXTRANS_IN_TRANSACTIONID'


CREATE NONCLUSTERED INDEX IX_RETAILTRANSACTIONTAXTRANS_IN_TRANSACTIONID ON [ax].[RETAILTRANSACTIONTAXTRANS_IN]
(
    [TRANSACTIONID]
) ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_RETAILTRANSACTIONTAXTRANS_IN_TRANSACTIONID'

IF INDEXPROPERTY (OBJECT_ID (N'[ax].[INVENTDIM]', N'U'), N'IX_INVENTDIM_RECID', 'IndexID') is null
BEGIN
    PRINT 'Adding index IX_INVENTDIM_RECID'


CREATE NONCLUSTERED INDEX [IX_INVENTDIM_RECID] ON [ax].[INVENTDIM] 
(
    [RECID] ASC
)
INCLUDE
(
INVENTDIMID
)
ON [PRIMARY]


END
ELSE
    PRINT 'Existing index IX_INVENTDIM_RECID'


-- Creating table trigger [ax].[ECORESPRODUCTCATEGORY_MODIFIED]
PRINT N'Creating table trigger [ax].[ECORESPRODUCTCATEGORY_MODIFIED]';

GO
IF OBJECT_ID(N'[ax].[ECORESPRODUCTCATEGORY_MODIFIED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[ECORESPRODUCTCATEGORY_MODIFIED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[ECORESPRODUCTCATEGORY_MODIFIED].'
GO


CREATE TRIGGER [ax].ECORESPRODUCTCATEGORY_MODIFIED
ON [ax].[ECORESPRODUCTCATEGORY]
AFTER UPDATE, DELETE AS
BEGIN
    -- if record was changed, we need to insert it into tracking table because
    -- either the category or product changed, which can both result in new prices
    INSERT INTO [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]
        (CATEGORY, PRODUCT, RECID)
    SELECT deleted.CATEGORY, deleted.PRODUCT, deleted.RECID
    FROM deleted
    WHERE NOT EXISTS -- only insert if missing
        (SELECT TOP 1 RECID
            FROM [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING] AS tracking
            WHERE
                tracking.RECID = deleted.RECID
                AND tracking.CATEGORY = deleted.CATEGORY
                AND tracking.PRODUCT = deleted.PRODUCT)

    -- make sure records in tracking table are marked unprocessed
    UPDATE [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING]
    SET ISPROCESSED = 0
    FROM [crt].[ECORESPRODUCTCATEGORY_PRICETRACKING] AS tracking
    JOIN deleted
        ON tracking.RECID = deleted.RECID
        AND tracking.CATEGORY = deleted.CATEGORY
        AND tracking.PRODUCT = deleted.PRODUCT
END;


GO
PRINT N'Finished creating table trigger [ax].[ECORESPRODUCTCATEGORY_MODIFIED]'
-- End creating table trigger [ax].[ECORESPRODUCTCATEGORY_MODIFIED]

-- Creating table trigger [ax].[PRICEDISCTABLE_INSERTED]
PRINT N'Creating table trigger [ax].[PRICEDISCTABLE_INSERTED]';

GO
IF OBJECT_ID(N'[ax].[PRICEDISCTABLE_INSERTED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[PRICEDISCTABLE_INSERTED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[PRICEDISCTABLE_INSERTED].'
GO


CREATE TRIGGER [ax].[PRICEDISCTABLE_INSERTED]
ON [ax].[PRICEDISCTABLE]
AFTER INSERT AS
BEGIN
    DECLARE @fromType int = [crt].PRICEDATEEFFECTIVITYFROMTYPE();
    DECLARE @toType int = [crt].PRICEDATEEFFECTIVITYTOTYPE();
    DECLARE @tableId bigint = CHECKSUM('PRICEDISCTABLE');

    -- insert into price date effectivity tracking table for new trade agreements
    INSERT INTO [crt].RETAILLISTINGPRICEDATEEFFECTIVITY
        (TABLEID, RECID, DATE, DATETYPE)
    ((SELECT @tableId, i.RECID, i.FROMDATE, @fromType FROM INSERTED i WHERE i.RELATION = 4)
      UNION ALL
     (SELECT @tableId, i.RECID, i.TODATE, @toType FROM INSERTED i WHERE i.RELATION = 4));
END;


GO
PRINT N'Finished creating table trigger [ax].[PRICEDISCTABLE_INSERTED]'
-- End creating table trigger [ax].[PRICEDISCTABLE_INSERTED]




-- Creating table trigger [ax].[PRICEDISCTABLE_UPDATED]
PRINT N'Creating table trigger [ax].[PRICEDISCTABLE_UPDATED]';

GO
IF OBJECT_ID(N'[ax].[PRICEDISCTABLE_UPDATED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[PRICEDISCTABLE_UPDATED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[PRICEDISCTABLE_UPDATED].'
GO


CREATE TRIGGER [ax].[PRICEDISCTABLE_UPDATED]
ON [ax].[PRICEDISCTABLE]
AFTER UPDATE AS
BEGIN
    DECLARE @fromType int = [crt].PRICEDATEEFFECTIVITYFROMTYPE();
    DECLARE @toType int = [crt].PRICEDATEEFFECTIVITYTOTYPE();
    DECLARE @tableId bigint = CHECKSUM('PRICEDISCTABLE');

    -- create rows in date tracking format from inserted rows
    DECLARE @date_tracking TABLE (TABLEID bigint NOT NULL, RECID bigint NOT NULL, DATE date NOT NULL, DATETYPE int NOT NULL)
    INSERT INTO @date_tracking
    SELECT TABLEID, RECID, DATE, DATETYPE
    FROM
    ((SELECT @tableId AS TABLEID, i.RECID, i.FROMDATE AS DATE, @fromType AS DATETYPE
        FROM INSERTED i WHERE i.RELATION = 4) -- Relation = 4 means this is a Sales Price Trade Agreement
      UNION ALL
     (SELECT @tableId AS TABLEID, i.RECID, i.TODATE   AS DATE, @toType   AS DATETYPE
        FROM INSERTED i WHERE i.RELATION = 4)) AS UPDATED

    -- make sure we have these inserted before updating them
    INSERT INTO [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
        (TABLEID, RECID, DATE, DATETYPE)
    SELECT updated.TABLEID, updated.RECID, updated.DATE, updated.DATETYPE
    FROM @date_tracking AS UPDATED
    WHERE NOT EXISTS (
        SELECT rde.RECID
        FROM [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY] rde
        WHERE rde.DATETYPE = updated.DATETYPE AND rde.TABLEID = updated.TABLEID AND rde.RECID = updated.RECID)

    -- update price date effectivity tracking table for trade agreement
    UPDATE [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
    SET DATE = updated.DATE,
        ISPROCESSED = 0
    FROM [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY] rde
    INNER JOIN @date_tracking AS UPDATED
         ON rde.RECID = updated.RECID
         AND rde.TABLEID = updated.TABLEID
         AND rde.DATETYPE = updated.DATETYPE
         AND rde.DATE <> updated.DATE

    DECLARE @changedRecords TABLE (
        ACCOUNTCODE int NOT NULL,
        ACCOUNTRELATION nvarchar(20) NOT NULL,
        ITEMRELATION nvarchar(20) NOT NULL,
        INVENTDIMID nvarchar(20) NOT NULL,
        RECID bigint NOT NULL)

    INSERT INTO @changedRecords
        SELECT d.ACCOUNTCODE, d.ACCOUNTRELATION, d.ITEMRELATION, d.INVENTDIMID, d.RECID
        FROM deleted d
        INNER JOIN inserted i ON d.RECID = i.RECID AND i.RELATION = 4
        WHERE ((d.ITEMRELATION <> i.ITEMRELATION OR d.INVENTDIMID <> i.INVENTDIMID))
           OR (d.ACCOUNTCODE = 1 AND d.ACCOUNTRELATION <> i.ACCOUNTRELATION)

    -- insert previous record into price agreement shadow table if item or price group changed
    INSERT INTO [crt].[PRICEDISCTABLE_PRICETRACKING]
        (ACCOUNTCODE, ACCOUNTRELATION, ITEMRELATION, INVENTDIMID, RECID)
    SELECT ACCOUNTCODE, ACCOUNTRELATION, ITEMRELATION, INVENTDIMID, RECID
    FROM @changedRecords AS d
    WHERE NOT EXISTS (
        SELECT pdt.RECID
        FROM [crt].[PRICEDISCTABLE_PRICETRACKING] pdt
        WHERE pdt.RECID = d.RECID AND pdt.ITEMRELATION = d.ITEMRELATION AND pdt.INVENTDIMID = d.INVENTDIMID)

    -- make sure tracking table is marked as unprocessed
    UPDATE [crt].[PRICEDISCTABLE_PRICETRACKING]
    SET ISPROCESSED = 0
    FROM [crt].[PRICEDISCTABLE_PRICETRACKING] AS tracking
    INNER JOIN @changedRecords AS d
        ON d.ITEMRELATION = tracking.ITEMRELATION
        AND d.INVENTDIMID = tracking.INVENTDIMID
        AND d.RECID = tracking.RECID
END;


GO
PRINT N'Finished creating table trigger [ax].[PRICEDISCTABLE_UPDATED]'
-- End creating table trigger [ax].[PRICEDISCTABLE_UPDATED]




-- Creating table trigger [ax].[PRICEDISCTABLE_DELETED]
PRINT N'Creating table trigger [ax].[PRICEDISCTABLE_DELETED]';

GO
IF OBJECT_ID(N'[ax].[PRICEDISCTABLE_DELETED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[PRICEDISCTABLE_DELETED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[PRICEDISCTABLE_DELETED].'
GO


CREATE TRIGGER [ax].[PRICEDISCTABLE_DELETED]
ON [ax].[PRICEDISCTABLE]
AFTER DELETE AS
BEGIN
    DECLARE @tableId bigint = CHECKSUM('PRICEDISCTABLE');

    -- delete price date effectivity tracking table for trade agreement
    DELETE [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
    FROM [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY] pde
    JOIN deleted ON pde.RECID = deleted.RECID AND TABLEID = @tableId

    -- insert deleted records into price agreement shadow table if not already there
    INSERT INTO [crt].[PRICEDISCTABLE_PRICETRACKING]
        (ACCOUNTCODE, ACCOUNTRELATION, ITEMRELATION, INVENTDIMID, RECID)
    SELECT d.ACCOUNTCODE, d.ACCOUNTRELATION, d.ITEMRELATION, d.INVENTDIMID, d.RECID
    FROM deleted d WHERE d.RELATION = 4
    AND NOT EXISTS
        (SELECT pdt.RECID
            FROM [crt].[PRICEDISCTABLE_PRICETRACKING] pdt
            WHERE
                pdt.RECID = d.RECID
                AND pdt.ITEMRELATION = d.ITEMRELATION
                AND pdt.INVENTDIMID = d.INVENTDIMID)
END;


GO
PRINT N'Finished creating table trigger [ax].[PRICEDISCTABLE_DELETED]'
-- End creating table trigger [ax].[PRICEDISCTABLE_DELETED]

-- Creating table trigger [ax].[RETAILPERIODICDISCOUNT_INSERTED]
PRINT N'Creating table trigger [ax].[RETAILPERIODICDISCOUNT_INSERTED]';

GO
IF OBJECT_ID(N'[ax].[RETAILPERIODICDISCOUNT_INSERTED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[RETAILPERIODICDISCOUNT_INSERTED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[RETAILPERIODICDISCOUNT_INSERTED].'
GO


CREATE TRIGGER [ax].RETAILPERIODICDISCOUNT_INSERTED
ON [ax].[RETAILPERIODICDISCOUNT]
AFTER INSERT AS
BEGIN
    DECLARE @fromType int = [crt].PRICEDATEEFFECTIVITYFROMTYPE();
    DECLARE @toType int = [crt].PRICEDATEEFFECTIVITYTOTYPE();
    DECLARE @tableId bigint = CHECKSUM('RETAILPERIODICDISCOUNT');

    -- insert into price date effectivity tracking table for new price adjustments
    INSERT INTO [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
        (TABLEID, RECID, DATE, DATETYPE)
    ((SELECT @tableId, i.RECID, i.VALIDFROM, @fromType
        FROM inserted i WHERE i.PERIODICDISCOUNTTYPE = 3) -- Type = 3 indicates this is a price adjustment
      UNION ALL
     (SELECT @tableId, i.RECID, i.VALIDTO, @toType
        FROM inserted i WHERE i.PERIODICDISCOUNTTYPE = 3));
END;


GO
PRINT N'Finished creating table trigger [ax].[RETAILPERIODICDISCOUNT_INSERTED]'
-- End creating table trigger [ax].[RETAILPERIODICDISCOUNT_INSERTED]




-- Creating table trigger [ax].[RETAILPERIODICDISCOUNT_UPDATED]
PRINT N'Creating table trigger [ax].[RETAILPERIODICDISCOUNT_UPDATED]';

GO
IF OBJECT_ID(N'[ax].[RETAILPERIODICDISCOUNT_UPDATED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[RETAILPERIODICDISCOUNT_UPDATED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[RETAILPERIODICDISCOUNT_UPDATED].'
GO


CREATE TRIGGER [ax].RETAILPERIODICDISCOUNT_UPDATED
ON [ax].[RETAILPERIODICDISCOUNT]
AFTER UPDATE AS
BEGIN
    DECLARE @fromType int = [crt].PRICEDATEEFFECTIVITYFROMTYPE();
    DECLARE @toType int = [crt].PRICEDATEEFFECTIVITYTOTYPE();
    DECLARE @tableId bigint = CHECKSUM('RETAILPERIODICDISCOUNT');

    -- create rows in date tracking format from inserted rows
    DECLARE @date_tracking TABLE (TABLEID bigint NOT NULL, RECID bigint NOT NULL, DATE date NOT NULL, DATETYPE int NOT NULL)
    INSERT INTO @date_tracking
    SELECT TABLEID, RECID, DATE, DATETYPE
    FROM
    ((SELECT @tableId AS TABLEID, i.RECID, i.VALIDFROM as DATE, @fromType AS DATETYPE
        FROM inserted i WHERE i.PERIODICDISCOUNTTYPE = 3) -- Type = 3 indicates this is a price adjustment
      UNION ALL
     (SELECT @tableId AS TABLEID, i.RECID, i.VALIDTO   as DATE, @toType   as DATETYPE
        FROM inserted i WHERE i.PERIODICDISCOUNTTYPE = 3)) as updated

    -- make sure we have these inserted before updating them
    INSERT INTO [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
        (TABLEID, RECID, DATE, DATETYPE)
    SELECT updated.TABLEID, updated.RECID, updated.DATE, updated.DATETYPE
    FROM @date_tracking AS updated
    WHERE NOT EXISTS (
        SELECT rde.RECID
        FROM [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY] rde
        WHERE
            rde.DATETYPE = updated.DATETYPE
            AND rde.TABLEID = updated.TABLEID
            AND rde.RECID = updated.RECID)

    -- update price date effectivity tracking table for price adjustment
    UPDATE [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
    SET DATE = updated.DATE,
        ISPROCESSED = 0
    FROM [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY] rde
    INNER JOIN @date_tracking AS updated
         ON rde.RECID = updated.RECID
         AND rde.TABLEID = updated.TABLEID
         AND rde.DATETYPE = updated.DATETYPE
         AND rde.DATE <> updated.DATE
END;


GO
PRINT N'Finished creating table trigger [ax].[RETAILPERIODICDISCOUNT_UPDATED]'
-- End creating table trigger [ax].[RETAILPERIODICDISCOUNT_UPDATED]




-- Creating table trigger [ax].[RETAILPERIODICDISCOUNT_DELETED]
PRINT N'Creating table trigger [ax].[RETAILPERIODICDISCOUNT_DELETED]';

GO
IF OBJECT_ID(N'[ax].[RETAILPERIODICDISCOUNT_DELETED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[RETAILPERIODICDISCOUNT_DELETED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[RETAILPERIODICDISCOUNT_DELETED].'
GO


CREATE TRIGGER [ax].RETAILPERIODICDISCOUNT_DELETED
ON [ax].[RETAILPERIODICDISCOUNT]
AFTER DELETE AS
BEGIN
    DECLARE @tableId bigint = CHECKSUM('RETAILPERIODICDISCOUNT');

    -- delete price date effectivity tracking table for trade agreement
    DELETE [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY]
    FROM [crt].[RETAILLISTINGPRICEDATEEFFECTIVITY] pde
    INNER JOIN deleted ON pde.RECID = deleted.RECID AND TABLEID = @tableId
END;


GO
PRINT N'Finished creating table trigger [ax].[RETAILPERIODICDISCOUNT_DELETED]'
-- End creating table trigger [ax].[RETAILPERIODICDISCOUNT_DELETED]

-- Creating table trigger [ax].[RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED]
PRINT N'Creating table trigger [ax].[RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED]';

GO
IF OBJECT_ID(N'[ax].[RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED].'
GO


CREATE TRIGGER [ax].RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED
ON [ax].[RETAILCATEGORYCONTAINMENTLOOKUP]
AFTER UPDATE, DELETE AS
BEGIN
    -- if record was changed, we need to insert it into tracking table because
    --  retail category hierarchies have changed or new categories have been assigned to
    --  supplemental categories, which can both result in new prices for items in those categories
    INSERT INTO [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]
        (CATEGORY, CONTAINEDCATEGORY, RECID)
    SELECT deleted.CATEGORY, deleted.CONTAINEDCATEGORY, deleted.RECID
    FROM deleted
    WHERE NOT EXISTS -- only insert if missing
        (SELECT TOP 1 RECID
            FROM [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING] AS tracking
            WHERE
                tracking.RECID = deleted.RECID
                AND tracking.CATEGORY = deleted.CATEGORY
                AND tracking.CONTAINEDCATEGORY = deleted.CONTAINEDCATEGORY)

    -- make sure records in tracking table are marked unprocessed
    UPDATE [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING]
    SET ISPROCESSED = 0
    FROM [crt].[RETAILCATEGORYCONTAINMENTLOOKUP_PRICETRACKING] AS tracking
    JOIN deleted
        ON tracking.RECID = deleted.RECID
        AND tracking.CATEGORY = deleted.CATEGORY
        AND tracking.CONTAINEDCATEGORY = deleted.CONTAINEDCATEGORY
END;


GO
PRINT N'Finished creating table trigger [ax].[RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED]'
-- End creating table trigger [ax].[RETAILCATEGORYCONTAINMENTLOOKUP_MODIFIED]

-- Creating table trigger [ax].[RETAILCHANNELPRICEGROUP_MODIFIED]
PRINT N'Creating table trigger [ax].[RETAILCHANNELPRICEGROUP_MODIFIED]';

GO
IF OBJECT_ID(N'[ax].[RETAILCHANNELPRICEGROUP_MODIFIED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[RETAILCHANNELPRICEGROUP_MODIFIED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[RETAILCHANNELPRICEGROUP_MODIFIED].'
GO


CREATE TRIGGER [ax].RETAILCHANNELPRICEGROUP_MODIFIED
ON [ax].[RETAILCHANNELPRICEGROUP]
AFTER UPDATE, DELETE AS
BEGIN
    -- if record was changed, we need to insert it into tracking table because
    --   products in the channel (or former channel) have different price adjustments and
    --   sales price trade agreements applied
    INSERT INTO [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]
        (RETAILCHANNEL, PRICEGROUP, RECID)
    SELECT deleted.RETAILCHANNEL, deleted.PRICEGROUP, deleted.RECID
    FROM deleted
    WHERE NOT EXISTS -- only insert if missing
        (SELECT TOP 1 RECID
            FROM [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING] AS tracking
            WHERE
                tracking.RECID = deleted.RECID
                AND tracking.RETAILCHANNEL = deleted.RETAILCHANNEL
                AND tracking.PRICEGROUP = deleted.PRICEGROUP)

    -- make sure records in tracking table are marked unprocessed
    UPDATE [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING]
    SET ISPROCESSED = 0
    FROM [crt].[RETAILCHANNELPRICEGROUP_PRICETRACKING] AS tracking
    JOIN deleted
        ON tracking.RECID = deleted.RECID
        AND tracking.RETAILCHANNEL = deleted.RETAILCHANNEL
        AND tracking.PRICEGROUP = deleted.PRICEGROUP

END;


GO
PRINT N'Finished creating table trigger [ax].[RETAILCHANNELPRICEGROUP_MODIFIED]'
-- End creating table trigger [ax].[RETAILCHANNELPRICEGROUP_MODIFIED]

-- Creating table trigger [ax].[RETAILGROUPMEMBERLINE_MODIFIED]
PRINT N'Creating table trigger [ax].[RETAILGROUPMEMBERLINE_MODIFIED]';

GO
IF OBJECT_ID(N'[ax].[RETAILGROUPMEMBERLINE_MODIFIED]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[RETAILGROUPMEMBERLINE_MODIFIED]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[RETAILGROUPMEMBERLINE_MODIFIED].'
GO


CREATE TRIGGER [ax].RETAILGROUPMEMBERLINE_MODIFIED
ON [ax].[RETAILGROUPMEMBERLINE]
AFTER UPDATE, DELETE AS
BEGIN
    -- if record was changed, we need to insert it into tracking table because
    --   the category or item it used to point to will need to be updated as well
    --   as the item it is currently pointing to
    INSERT INTO [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]
        (CATEGORY, PRODUCT, VARIANT, RECID)
    SELECT deleted.CATEGORY, deleted.PRODUCT, deleted.VARIANT, deleted.RECID
    FROM deleted
    WHERE NOT EXISTS -- only insert if missing
        (SELECT TOP 1 RECID
            FROM [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING] AS tracking
            WHERE
                tracking.RECID = deleted.RECID
                AND tracking.CATEGORY = deleted.CATEGORY
                AND tracking.PRODUCT = deleted.PRODUCT
                AND tracking.VARIANT = deleted.VARIANT)

    -- make sure records in tracking table are marked unprocessed
    UPDATE [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING]
    SET ISPROCESSED = 0
    FROM [crt].[RETAILGROUPMEMBERLINE_PRICETRACKING] AS tracking
    JOIN deleted
        ON tracking.RECID = deleted.RECID
        AND tracking.CATEGORY = deleted.CATEGORY
        AND tracking.PRODUCT = deleted.PRODUCT
        AND tracking.VARIANT = deleted.VARIANT
END;


GO
PRINT N'Finished creating table trigger [ax].[RETAILGROUPMEMBERLINE_MODIFIED]'
-- End creating table trigger [ax].[RETAILGROUPMEMBERLINE_MODIFIED]

-- Creating table trigger [ax].[manualChanges_FISCALESTABLISHMENT_BR]
PRINT N'Creating table trigger [ax].[manualChanges_FISCALESTABLISHMENT_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_FISCALESTABLISHMENT_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_FISCALESTABLISHMENT_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_FISCALESTABLISHMENT_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_FISCALESTABLISHMENT_BR]
ON [ax].[FISCALESTABLISHMENT_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @RECIDIns BIGINT 
DECLARE @RECIDDel BIGINT 

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'FISCALESTABLISHMENT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'FISCALESTABLISHMENT_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'FISCALESTABLISHMENT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'FISCALESTABLISHMENT_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RECIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RECIDIns)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'FISCALESTABLISHMENT_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'FISCALESTABLISHMENT_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @RECIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RECIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT RECID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @RECIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RECIDIns)  

SET @primaryKeyDel = CONVERT(NVARCHAR, @RECIDDel)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'FISCALESTABLISHMENT_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'FISCALESTABLISHMENT_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'FISCALESTABLISHMENT_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @RECIDDel  
FETCH NEXT FROM insertedCursor INTO @RECIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_FISCALESTABLISHMENT_BR]'
-- End creating table trigger [ax].[manualChanges_FISCALESTABLISHMENT_BR]


-- Creating table trigger [ax].[manualChanges_INVENTTABLEMODULE]
PRINT N'Creating table trigger [ax].[manualChanges_INVENTTABLEMODULE]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_INVENTTABLEMODULE]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_INVENTTABLEMODULE]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_INVENTTABLEMODULE].'
GO

CREATE TRIGGER [ax].[manualChanges_INVENTTABLEMODULE]
ON [ax].[INVENTTABLEMODULE]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @ITEMIDIns NVARCHAR (20)
DECLARE @ITEMIDDel NVARCHAR (20)
DECLARE @MODULETYPEIns INT 
DECLARE @MODULETYPEDel INT 
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLEMODULE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLEMODULE', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLEMODULE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLEMODULE', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT ITEMID , MODULETYPE , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @ITEMIDIns , @MODULETYPEIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @ITEMIDIns + CONVERT(NVARCHAR, @MODULETYPEIns) + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLEMODULE' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLEMODULE', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @ITEMIDIns , @MODULETYPEIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT ITEMID , MODULETYPE , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @ITEMIDIns , @MODULETYPEIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT ITEMID , MODULETYPE , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @ITEMIDDel , @MODULETYPEDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @ITEMIDIns + CONVERT(NVARCHAR, @MODULETYPEIns) + @DATAAREAIDIns  

SET @primaryKeyDel = @ITEMIDDel + CONVERT(NVARCHAR, @MODULETYPEDel) + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLEMODULE' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLEMODULE', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'INVENTTABLEMODULE' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @ITEMIDDel , @MODULETYPEDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @ITEMIDIns , @MODULETYPEIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_INVENTTABLEMODULE]'
-- End creating table trigger [ax].[manualChanges_INVENTTABLEMODULE]


-- Creating table trigger [ax].[manualChanges_INVENTTABLE]
PRINT N'Creating table trigger [ax].[manualChanges_INVENTTABLE]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_INVENTTABLE]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_INVENTTABLE]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_INVENTTABLE].'
GO

CREATE TRIGGER [ax].[manualChanges_INVENTTABLE]
ON [ax].[INVENTTABLE]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @DATAAREAIDIns NVARCHAR (4)
DECLARE @DATAAREAIDDel NVARCHAR (4)
DECLARE @ITEMIDIns NVARCHAR (20
)
DECLARE @ITEMIDDel NVARCHAR (20
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLE', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLE', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT DATAAREAID , ITEMID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @ITEMIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @DATAAREAIDIns + @ITEMIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLE' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLE', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @ITEMIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT DATAAREAID , ITEMID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @ITEMIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT DATAAREAID , ITEMID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @DATAAREAIDDel , @ITEMIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @DATAAREAIDIns + @ITEMIDIns  

SET @primaryKeyDel = @DATAAREAIDDel + @ITEMIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'INVENTTABLE' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'INVENTTABLE', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'INVENTTABLE' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @DATAAREAIDDel , @ITEMIDDel  
FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @ITEMIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_INVENTTABLE]'
-- End creating table trigger [ax].[manualChanges_INVENTTABLE]


-- Creating table trigger [ax].[manualChanges_PRICEDISCTABLE]
PRINT N'Creating table trigger [ax].[manualChanges_PRICEDISCTABLE]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_PRICEDISCTABLE]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_PRICEDISCTABLE]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_PRICEDISCTABLE].'
GO

CREATE TRIGGER [ax].[manualChanges_PRICEDISCTABLE]
ON [ax].[PRICEDISCTABLE]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @RECIDIns BIGINT 
DECLARE @RECIDDel BIGINT 

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'PRICEDISCTABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'PRICEDISCTABLE', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'PRICEDISCTABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'PRICEDISCTABLE', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RECIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RECIDIns)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'PRICEDISCTABLE' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'PRICEDISCTABLE', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @RECIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RECIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT RECID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @RECIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RECIDIns)  

SET @primaryKeyDel = CONVERT(NVARCHAR, @RECIDDel)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'PRICEDISCTABLE' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'PRICEDISCTABLE', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'PRICEDISCTABLE' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @RECIDDel  
FETCH NEXT FROM insertedCursor INTO @RECIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_PRICEDISCTABLE]'
-- End creating table trigger [ax].[manualChanges_PRICEDISCTABLE]


-- Creating table trigger [ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR]
ON [ax].[RETAILFISCALPRINTERREPORT_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @RESTARTOPERATIONNUMBERIns INT 
DECLARE @RESTARTOPERATIONNUMBERDel INT 
DECLARE @RECEIPTNUMBERIns INT 
DECLARE @RECEIPTNUMBERDel INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXIns INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXDel INT 
DECLARE @FISCALPRINTERSERIALNUMBERIns NVARCHAR (20)
DECLARE @FISCALPRINTERSERIALNUMBERDel NVARCHAR (20)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTERREPORT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTERREPORT_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTERREPORT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTERREPORT_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , RECEIPTNUMBER , ADDITIONALFISCALMEMORYINDEX , FISCALPRINTERSERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @RECEIPTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERIns) + CONVERT(NVARCHAR, @RECEIPTNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @FISCALPRINTERSERIALNUMBERIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTERREPORT_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTERREPORT_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @RECEIPTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , RECEIPTNUMBER , ADDITIONALFISCALMEMORYINDEX , FISCALPRINTERSERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @RECEIPTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , RECEIPTNUMBER , ADDITIONALFISCALMEMORYINDEX , FISCALPRINTERSERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @RESTARTOPERATIONNUMBERDel , @RECEIPTNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @FISCALPRINTERSERIALNUMBERDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERIns) + CONVERT(NVARCHAR, @RECEIPTNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @FISCALPRINTERSERIALNUMBERIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERDel) + CONVERT(NVARCHAR, @RECEIPTNUMBERDel) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXDel) + @FISCALPRINTERSERIALNUMBERDel + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTERREPORT_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTERREPORT_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILFISCALPRINTERREPORT_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @RESTARTOPERATIONNUMBERDel , @RECEIPTNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @FISCALPRINTERSERIALNUMBERDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @RECEIPTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILFISCALPRINTERREPORT_BR]


-- Creating table trigger [ax].[manualChanges_RETAILFISCALPRINTER_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILFISCALPRINTER_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILFISCALPRINTER_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILFISCALPRINTER_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILFISCALPRINTER_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILFISCALPRINTER_BR]
ON [ax].[RETAILFISCALPRINTER_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @RESTARTOPERATIONNUMBERIns INT 
DECLARE @RESTARTOPERATIONNUMBERDel INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXIns INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXDel INT 
DECLARE @SERIALNUMBERIns NVARCHAR (20)
DECLARE @SERIALNUMBERDel NVARCHAR (20)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTER_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTER_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTER_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTER_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , ADDITIONALFISCALMEMORYINDEX , SERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @SERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @SERIALNUMBERIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTER_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTER_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @SERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , ADDITIONALFISCALMEMORYINDEX , SERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @SERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , ADDITIONALFISCALMEMORYINDEX , SERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @RESTARTOPERATIONNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @SERIALNUMBERDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @SERIALNUMBERIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERDel) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXDel) + @SERIALNUMBERDel + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALPRINTER_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALPRINTER_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILFISCALPRINTER_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @RESTARTOPERATIONNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @SERIALNUMBERDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @SERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILFISCALPRINTER_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILFISCALPRINTER_BR]


-- Creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR]
ON [ax].[RETAILFISCALRECEIPTLINE_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @LINENUMIns NUMERIC (32,16)
DECLARE @LINENUMDel NUMERIC (32,16)
DECLARE @TRANSACTIONIDIns NVARCHAR (44)
DECLARE @TRANSACTIONIDDel NVARCHAR (44)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTLINE_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTLINE_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTLINE_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTLINE_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = REPLACE(CONVERT(NVARCHAR, @LINENUMIns), ',', '.') + @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTLINE_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTLINE_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @LINENUMDel , @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = REPLACE(CONVERT(NVARCHAR, @LINENUMIns), ',', '.') + @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = REPLACE(CONVERT(NVARCHAR, @LINENUMDel), ',', '.') + @TRANSACTIONIDDel + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTLINE_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTLINE_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILFISCALRECEIPTLINE_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @LINENUMDel , @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTLINE_BR]


-- Creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR]
ON [ax].[RETAILFISCALRECEIPTTAXTRANS_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @TAXTYPEIns INT 
DECLARE @TAXTYPEDel INT 
DECLARE @LINENUMIns NUMERIC (32,16)
DECLARE @LINENUMDel NUMERIC (32,16)
DECLARE @TRANSACTIONIDIns NVARCHAR (44)
DECLARE @TRANSACTIONIDDel NVARCHAR (44)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTTAXTRANS_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTTAXTRANS_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTTAXTRANS_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTTAXTRANS_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT TAXTYPE , LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXTYPEIns , @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @TAXTYPEIns) + REPLACE(CONVERT(NVARCHAR, @LINENUMIns), ',', '.') + @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTTAXTRANS_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTTAXTRANS_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @TAXTYPEIns , @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT TAXTYPE , LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXTYPEIns , @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT TAXTYPE , LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @TAXTYPEDel , @LINENUMDel , @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @TAXTYPEIns) + REPLACE(CONVERT(NVARCHAR, @LINENUMIns), ',', '.') + @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = CONVERT(NVARCHAR, @TAXTYPEDel) + REPLACE(CONVERT(NVARCHAR, @LINENUMDel), ',', '.') + @TRANSACTIONIDDel + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPTTAXTRANS_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPTTAXTRANS_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILFISCALRECEIPTTAXTRANS_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @TAXTYPEDel , @LINENUMDel , @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @TAXTYPEIns , @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPTTAXTRANS_BR]


-- Creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPT_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPT_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILFISCALRECEIPT_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILFISCALRECEIPT_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILFISCALRECEIPT_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILFISCALRECEIPT_BR]
ON [ax].[RETAILFISCALRECEIPT_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @TRANSACTIONIDIns NVARCHAR (44)
DECLARE @TRANSACTIONIDDel NVARCHAR (44)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPT_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPT_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPT_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPT_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = @TRANSACTIONIDDel + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILFISCALRECEIPT_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILFISCALRECEIPT_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILFISCALRECEIPT_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPT_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILFISCALRECEIPT_BR]


-- Creating table trigger [ax].[manualChanges_RETAILSTORETABLE]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILSTORETABLE]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILSTORETABLE]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILSTORETABLE]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILSTORETABLE].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILSTORETABLE]
ON [ax].[RETAILSTORETABLE]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @RECIDIns BIGINT 
DECLARE @RECIDDel BIGINT 

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILSTORETABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILSTORETABLE', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILSTORETABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILSTORETABLE', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RECIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RECIDIns)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILSTORETABLE' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILSTORETABLE', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @RECIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RECIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT RECID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @RECIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RECIDIns)  

SET @primaryKeyDel = CONVERT(NVARCHAR, @RECIDDel)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILSTORETABLE' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILSTORETABLE', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILSTORETABLE' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @RECIDDel  
FETCH NEXT FROM insertedCursor INTO @RECIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILSTORETABLE]'
-- End creating table trigger [ax].[manualChanges_RETAILSTORETABLE]


-- Creating table trigger [ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR]
ON [ax].[RETAILTRANSACTIONPAYMENTTRANS_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @LINENUMIns NUMERIC (32,16)
DECLARE @LINENUMDel NUMERIC (32,16)
DECLARE @TRANSACTIONIDIns NVARCHAR (44)
DECLARE @TRANSACTIONIDDel NVARCHAR (44)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILTRANSACTIONPAYMENTTRANS_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILTRANSACTIONPAYMENTTRANS_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILTRANSACTIONPAYMENTTRANS_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILTRANSACTIONPAYMENTTRANS_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = REPLACE(CONVERT(NVARCHAR, @LINENUMIns), ',', '.') + @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILTRANSACTIONPAYMENTTRANS_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILTRANSACTIONPAYMENTTRANS_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT LINENUM , TRANSACTIONID , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @LINENUMDel , @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = REPLACE(CONVERT(NVARCHAR, @LINENUMIns), ',', '.') + @TRANSACTIONIDIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = REPLACE(CONVERT(NVARCHAR, @LINENUMDel), ',', '.') + @TRANSACTIONIDDel + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILTRANSACTIONPAYMENTTRANS_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILTRANSACTIONPAYMENTTRANS_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILTRANSACTIONPAYMENTTRANS_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @LINENUMDel , @TRANSACTIONIDDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @LINENUMIns , @TRANSACTIONIDIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILTRANSACTIONPAYMENTTRANS_BR]


-- Creating table trigger [ax].[manualChanges_RETAILZREPORTTOTALIZER_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILZREPORTTOTALIZER_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILZREPORTTOTALIZER_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILZREPORTTOTALIZER_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILZREPORTTOTALIZER_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILZREPORTTOTALIZER_BR]
ON [ax].[RETAILZREPORTTOTALIZER_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @FISCALPRINTERSERIALNUMBERIns NVARCHAR (20)
DECLARE @FISCALPRINTERSERIALNUMBERDel NVARCHAR (20)
DECLARE @TOTALIZERNAMEIns NVARCHAR (10)
DECLARE @TOTALIZERNAMEDel NVARCHAR (10)
DECLARE @ZREPORTNUMBERIns INT 
DECLARE @ZREPORTNUMBERDel INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXIns INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXDel INT 
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORTTOTALIZER_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORTTOTALIZER_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORTTOTALIZER_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORTTOTALIZER_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT FISCALPRINTERSERIALNUMBER , TOTALIZERNAME , ZREPORTNUMBER , ADDITIONALFISCALMEMORYINDEX , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @FISCALPRINTERSERIALNUMBERIns , @TOTALIZERNAMEIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @FISCALPRINTERSERIALNUMBERIns + @TOTALIZERNAMEIns + CONVERT(NVARCHAR, @ZREPORTNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORTTOTALIZER_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORTTOTALIZER_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @FISCALPRINTERSERIALNUMBERIns , @TOTALIZERNAMEIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT FISCALPRINTERSERIALNUMBER , TOTALIZERNAME , ZREPORTNUMBER , ADDITIONALFISCALMEMORYINDEX , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @FISCALPRINTERSERIALNUMBERIns , @TOTALIZERNAMEIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT FISCALPRINTERSERIALNUMBER , TOTALIZERNAME , ZREPORTNUMBER , ADDITIONALFISCALMEMORYINDEX , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @FISCALPRINTERSERIALNUMBERDel , @TOTALIZERNAMEDel , @ZREPORTNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @FISCALPRINTERSERIALNUMBERIns + @TOTALIZERNAMEIns + CONVERT(NVARCHAR, @ZREPORTNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = @FISCALPRINTERSERIALNUMBERDel + @TOTALIZERNAMEDel + CONVERT(NVARCHAR, @ZREPORTNUMBERDel) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXDel) + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORTTOTALIZER_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORTTOTALIZER_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILZREPORTTOTALIZER_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @FISCALPRINTERSERIALNUMBERDel , @TOTALIZERNAMEDel , @ZREPORTNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @FISCALPRINTERSERIALNUMBERIns , @TOTALIZERNAMEIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILZREPORTTOTALIZER_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILZREPORTTOTALIZER_BR]


-- Creating table trigger [ax].[manualChanges_RETAILZREPORT_BR]
PRINT N'Creating table trigger [ax].[manualChanges_RETAILZREPORT_BR]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_RETAILZREPORT_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_RETAILZREPORT_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_RETAILZREPORT_BR].'
GO

CREATE TRIGGER [ax].[manualChanges_RETAILZREPORT_BR]
ON [ax].[RETAILZREPORT_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @RESTARTOPERATIONNUMBERIns INT 
DECLARE @RESTARTOPERATIONNUMBERDel INT 
DECLARE @ZREPORTNUMBERIns INT 
DECLARE @ZREPORTNUMBERDel INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXIns INT 
DECLARE @ADDITIONALFISCALMEMORYINDEXDel INT 
DECLARE @FISCALPRINTERSERIALNUMBERIns NVARCHAR (20)
DECLARE @FISCALPRINTERSERIALNUMBERDel NVARCHAR (20)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORT_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORT_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORT_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , ZREPORTNUMBER , ADDITIONALFISCALMEMORYINDEX , FISCALPRINTERSERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERIns) + CONVERT(NVARCHAR, @ZREPORTNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @FISCALPRINTERSERIALNUMBERIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORT_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORT_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , ZREPORTNUMBER , ADDITIONALFISCALMEMORYINDEX , FISCALPRINTERSERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT RESTARTOPERATIONNUMBER , ZREPORTNUMBER , ADDITIONALFISCALMEMORYINDEX , FISCALPRINTERSERIALNUMBER , TERMINALID , STOREID , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @RESTARTOPERATIONNUMBERDel , @ZREPORTNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @FISCALPRINTERSERIALNUMBERDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERIns) + CONVERT(NVARCHAR, @ZREPORTNUMBERIns) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXIns) + @FISCALPRINTERSERIALNUMBERIns + @TERMINALIDIns + @STOREIDIns + @DATAAREAIDIns  

SET @primaryKeyDel = CONVERT(NVARCHAR, @RESTARTOPERATIONNUMBERDel) + CONVERT(NVARCHAR, @ZREPORTNUMBERDel) + CONVERT(NVARCHAR, @ADDITIONALFISCALMEMORYINDEXDel) + @FISCALPRINTERSERIALNUMBERDel + @TERMINALIDDel + @STOREIDDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILZREPORT_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILZREPORT_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILZREPORT_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @RESTARTOPERATIONNUMBERDel , @ZREPORTNUMBERDel , @ADDITIONALFISCALMEMORYINDEXDel , @FISCALPRINTERSERIALNUMBERDel , @TERMINALIDDel , @STOREIDDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @RESTARTOPERATIONNUMBERIns , @ZREPORTNUMBERIns , @ADDITIONALFISCALMEMORYINDEXIns , @FISCALPRINTERSERIALNUMBERIns , @TERMINALIDIns , @STOREIDIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_RETAILZREPORT_BR]'
-- End creating table trigger [ax].[manualChanges_RETAILZREPORT_BR]


-- Creating table trigger [ax].[manualChanges_TAXDATA]
PRINT N'Creating table trigger [ax].[manualChanges_TAXDATA]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_TAXDATA]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_TAXDATA]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_TAXDATA].'
GO

CREATE TRIGGER [ax].[manualChanges_TAXDATA]
ON [ax].[TAXDATA]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @TAXCODEIns NVARCHAR (10)
DECLARE @TAXCODEDel NVARCHAR (10)
DECLARE @TAXLIMITMINIns NUMERIC (32,16)
DECLARE @TAXLIMITMINDel NUMERIC (32,16)
DECLARE @TAXFROMDATEIns DATETIME 
DECLARE @TAXFROMDATEDel DATETIME 
DECLARE @TAXTODATEIns DATETIME 
DECLARE @TAXTODATEDel DATETIME 
DECLARE @DATAAREAIDIns NVARCHAR (4)
DECLARE @DATAAREAIDDel NVARCHAR (4)
DECLARE @RECIDIns BIGINT 
DECLARE @RECIDDel BIGINT 

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXDATA' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXDATA', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXDATA' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXDATA', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT TAXCODE , TAXLIMITMIN , TAXFROMDATE , TAXTODATE , DATAAREAID , RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @TAXLIMITMINIns , @TAXFROMDATEIns , @TAXTODATEIns , @DATAAREAIDIns , @RECIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TAXCODEIns + REPLACE(CONVERT(NVARCHAR, @TAXLIMITMINIns), ',', '.') + CONVERT(NVARCHAR, @TAXFROMDATEIns, 126) + CONVERT(NVARCHAR, @TAXTODATEIns, 126) + @DATAAREAIDIns + CONVERT(NVARCHAR, @RECIDIns)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXDATA' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXDATA', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @TAXLIMITMINIns , @TAXFROMDATEIns , @TAXTODATEIns , @DATAAREAIDIns , @RECIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT TAXCODE , TAXLIMITMIN , TAXFROMDATE , TAXTODATE , DATAAREAID , RECID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @TAXLIMITMINIns , @TAXFROMDATEIns , @TAXTODATEIns , @DATAAREAIDIns , @RECIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT TAXCODE , TAXLIMITMIN , TAXFROMDATE , TAXTODATE , DATAAREAID , RECID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @TAXCODEDel , @TAXLIMITMINDel , @TAXFROMDATEDel , @TAXTODATEDel , @DATAAREAIDDel , @RECIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TAXCODEIns + REPLACE(CONVERT(NVARCHAR, @TAXLIMITMINIns), ',', '.') + CONVERT(NVARCHAR, @TAXFROMDATEIns, 126) + CONVERT(NVARCHAR, @TAXTODATEIns, 126) + @DATAAREAIDIns + CONVERT(NVARCHAR, @RECIDIns)  

SET @primaryKeyDel = @TAXCODEDel + REPLACE(CONVERT(NVARCHAR, @TAXLIMITMINDel), ',', '.') + CONVERT(NVARCHAR, @TAXFROMDATEDel, 126) + CONVERT(NVARCHAR, @TAXTODATEDel, 126) + @DATAAREAIDDel + CONVERT(NVARCHAR, @RECIDDel)  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXDATA' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXDATA', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'TAXDATA' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @TAXCODEDel , @TAXLIMITMINDel , @TAXFROMDATEDel , @TAXTODATEDel , @DATAAREAIDDel , @RECIDDel  
FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @TAXLIMITMINIns , @TAXFROMDATEIns , @TAXTODATEIns , @DATAAREAIDIns , @RECIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_TAXDATA]'
-- End creating table trigger [ax].[manualChanges_TAXDATA]


-- Creating table trigger [ax].[manualChanges_TAXONITEM]
PRINT N'Creating table trigger [ax].[manualChanges_TAXONITEM]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_TAXONITEM]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_TAXONITEM]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_TAXONITEM].'
GO

CREATE TRIGGER [ax].[manualChanges_TAXONITEM]
ON [ax].[TAXONITEM]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @TAXITEMGROUPIns NVARCHAR (10)
DECLARE @TAXITEMGROUPDel NVARCHAR (10)
DECLARE @TAXCODEIns NVARCHAR (10)
DECLARE @TAXCODEDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXONITEM' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXONITEM', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXONITEM' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXONITEM', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT TAXITEMGROUP , TAXCODE , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXITEMGROUPIns , @TAXCODEIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TAXITEMGROUPIns + @TAXCODEIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXONITEM' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXONITEM', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @TAXITEMGROUPIns , @TAXCODEIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT TAXITEMGROUP , TAXCODE , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXITEMGROUPIns , @TAXCODEIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT TAXITEMGROUP , TAXCODE , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @TAXITEMGROUPDel , @TAXCODEDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TAXITEMGROUPIns + @TAXCODEIns + @DATAAREAIDIns  

SET @primaryKeyDel = @TAXITEMGROUPDel + @TAXCODEDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXONITEM' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXONITEM', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'TAXONITEM' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @TAXITEMGROUPDel , @TAXCODEDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @TAXITEMGROUPIns , @TAXCODEIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_TAXONITEM]'
-- End creating table trigger [ax].[manualChanges_TAXONITEM]


-- Creating table trigger [ax].[manualChanges_TAXTABLE]
PRINT N'Creating table trigger [ax].[manualChanges_TAXTABLE]';

GO
IF OBJECT_ID(N'[ax].[manualChanges_TAXTABLE]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [ax].[manualChanges_TAXTABLE]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [ax].[manualChanges_TAXTABLE].'
GO

CREATE TRIGGER [ax].[manualChanges_TAXTABLE]
ON [ax].[TAXTABLE]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @TAXCODEIns NVARCHAR (10)
DECLARE @TAXCODEDel NVARCHAR (10)
DECLARE @DATAAREAIDIns NVARCHAR (4
)
DECLARE @DATAAREAIDDel NVARCHAR (4
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXTABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXTABLE', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXTABLE' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXTABLE', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT TAXCODE , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @DATAAREAIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TAXCODEIns + @DATAAREAIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXTABLE' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXTABLE', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @DATAAREAIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT TAXCODE , DATAAREAID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @DATAAREAIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT TAXCODE , DATAAREAID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @TAXCODEDel , @DATAAREAIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @TAXCODEIns + @DATAAREAIDIns  

SET @primaryKeyDel = @TAXCODEDel + @DATAAREAIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'TAXTABLE' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'TAXTABLE', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'TAXTABLE' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @TAXCODEDel , @DATAAREAIDDel  
FETCH NEXT FROM insertedCursor INTO @TAXCODEIns , @DATAAREAIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [ax].[manualChanges_TAXTABLE]'
-- End creating table trigger [ax].[manualChanges_TAXTABLE]

-- This file contains the SQL artifacts used to shim EPOS inside the CRT store database.
-------------------------------------------------------------------------------
PRINT 'Creating table ADDRESSFORMATHEADING ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ADDRESSFORMATHEADING]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ADDRESSFORMATHEADING](
    [ADDRFORMAT] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_002ADDRFORMATIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ADDRFORMAT] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__ADDRF__0BB1B5A5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATHEADING] ADD  CONSTRAINT [DF__ADDRESSFO__ADDRF__0BB1B5A5]  DEFAULT ('') FOR [ADDRFORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFOR__NAME__0CA5D9DE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATHEADING] ADD  CONSTRAINT [DF__ADDRESSFOR__NAME__0CA5D9DE]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__DATAA__0D99FE17]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATHEADING] ADD  CONSTRAINT [DF__ADDRESSFO__DATAA__0D99FE17]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table ADDRESSFORMATLINES ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ADDRESSFORMATLINES]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ADDRESSFORMATLINES](
    [ADDRFORMAT] [nvarchar](10) NOT NULL,
    [INACTIVE] [int] NULL,
    [SEPARATOR] [nvarchar](10) NULL,
    [ELEMENT] [int] NULL,
    [SEPARATORCRLF] [int] NULL,
    [DEL_EXPAND] [int] NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [SPECIAL] [int] NULL,
    [NUMOFSPACES] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_003ADDRFORMATLINEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ADDRFORMAT] ASC,
    [LINENUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__ADDRF__116A8EFB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__ADDRF__116A8EFB]  DEFAULT ('') FOR [ADDRFORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__INACT__125EB334]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__INACT__125EB334]  DEFAULT ((0)) FOR [INACTIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__SEPAR__1352D76D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__SEPAR__1352D76D]  DEFAULT ('') FOR [SEPARATOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__ELEME__1446FBA6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__ELEME__1446FBA6]  DEFAULT ((0)) FOR [ELEMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__SEPAR__153B1FDF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__SEPAR__153B1FDF]  DEFAULT ((0)) FOR [SEPARATORCRLF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__DEL_E__162F4418]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__DEL_E__162F4418]  DEFAULT ((0)) FOR [DEL_EXPAND]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__LINEN__17236851]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__LINEN__17236851]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__SPECI__18178C8A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__SPECI__18178C8A]  DEFAULT ((0)) FOR [SPECIAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__NUMOF__190BB0C3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__NUMOF__190BB0C3]  DEFAULT ((0)) FOR [NUMOFSPACES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ADDRESSFO__DATAA__19FFD4FC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ADDRESSFORMATLINES] ADD  CONSTRAINT [DF__ADDRESSFO__DATAA__19FFD4FC]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table BARCODESETUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BARCODESETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[BARCODESETUP](
    [BARCODESETUPID] [nvarchar](10) NOT NULL,
    [BARCODETYPE] [int] NULL,
    [FONTNAME] [nvarchar](32) NULL,
    [FONTSIZE] [int] NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [MINIMUMLENGTH] [int] NULL,
    [MAXIMUMLENGTH] [int] NULL,
    [RETAILBARCODEMASK] [nvarchar](22) NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_1214BARCODESETUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [BARCODESETUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__BARCO__7579F271]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__BARCO__7579F271]  DEFAULT ('') FOR [BARCODESETUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__BARCO__766E16AA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__BARCO__766E16AA]  DEFAULT ((0)) FOR [BARCODETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__FONTN__77623AE3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__FONTN__77623AE3]  DEFAULT ('') FOR [FONTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__FONTS__78565F1C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__FONTS__78565F1C]  DEFAULT ((0)) FOR [FONTSIZE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__DESCR__794A8355]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__DESCR__794A8355]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__MINIM__7A3EA78E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__MINIM__7A3EA78E]  DEFAULT ((0)) FOR [MINIMUMLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__MAXIM__7B32CBC7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__MAXIM__7B32CBC7]  DEFAULT ((0)) FOR [MAXIMUMLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__RBOBA__7C26F000]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__RBOBA__7C26F000]  DEFAULT ('') FOR [RETAILBARCODEMASK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__MODIF__7D1B1439]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__MODIF__7D1B1439]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__MODIF__7E0F3872]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__MODIF__7E0F3872]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__MODIF__7F035CAB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__MODIF__7F035CAB]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__BARCODESE__DATAA__7FF780E4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BARCODESETUP] ADD  CONSTRAINT [DF__BARCODESE__DATAA__7FF780E4]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view BRAZILPARAMETERS ..'
GO
IF OBJECT_ID(N'[dbo].[BRAZILPARAMETERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].BRAZILPARAMETERS
GO
CREATE VIEW [dbo].BRAZILPARAMETERS AS
(
  SELECT
    [APPROXTAXVALUESOURCE],
    [DATAAREAID],
    [LINKEDFISCALDOCUMENTMODEL02COFINS],
    [LINKEDFISCALDOCUMENTMODEL02ICMS],
    [LINKEDFISCALDOCUMENTMODEL02PIS],
    [RECID],
    [ROWVERSION]
  FROM [ax].BRAZILPARAMETERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table CASHDISC ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CASHDISC]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CASHDISC](
    [CASHDISCCODE] [nvarchar](10) NOT NULL,
    [DISCMETHOD] [int] NULL,
    [NUMOFDAYS] [int] NULL,
    [PERCENT_] [numeric](28, 12) NULL,
    [ACCOUNTPAID] [nvarchar](10) NULL,
    [ACCOUNTRECEIVED] [nvarchar](10) NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [NUMOFMONTHS] [int] NULL,
    [CASHDISCCODENEXT] [nvarchar](10) NULL,
    [PARTPAYMENTCASHDISC] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_034CODEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [CASHDISCCODE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__CASHDI__3E082B48]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__CASHDI__3E082B48]  DEFAULT ('') FOR [CASHDISCCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__DISCME__3EFC4F81]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__DISCME__3EFC4F81]  DEFAULT ((0)) FOR [DISCMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__NUMOFD__3FF073BA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__NUMOFD__3FF073BA]  DEFAULT ((0)) FOR [NUMOFDAYS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__PERCEN__40E497F3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__PERCEN__40E497F3]  DEFAULT ((0)) FOR [PERCENT_]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__ACCOUN__41D8BC2C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__ACCOUN__41D8BC2C]  DEFAULT ('') FOR [ACCOUNTPAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__ACCOUN__42CCE065]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__ACCOUN__42CCE065]  DEFAULT ('') FOR [ACCOUNTRECEIVED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__DESCRI__43C1049E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__DESCRI__43C1049E]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__NUMOFM__44B528D7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__NUMOFM__44B528D7]  DEFAULT ((0)) FOR [NUMOFMONTHS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__CASHDI__45A94D10]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__CASHDI__45A94D10]  DEFAULT ('') FOR [CASHDISCCODENEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__PARTPA__469D7149]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__PARTPA__469D7149]  DEFAULT ((0)) FOR [PARTPAYMENTCASHDISC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__CASHDISC__DATAAR__47919582]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[CASHDISC] ADD  CONSTRAINT [DF__CASHDISC__DATAAR__47919582]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view COMPANYINFO ..'
GO
IF OBJECT_ID(N'[dbo].[COMPANYINFO]', N'V') IS NOT NULL
    DROP VIEW [dbo].[COMPANYINFO]
GO
CREATE VIEW [dbo].COMPANYINFO AS
(
  SELECT
    [DATAAREA],
    [RECID]
  FROM [ax].COMPANYINFO
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table COUNTRY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[COUNTRY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[COUNTRY](
    [COUNTRYID] [nvarchar](10) NOT NULL,
    [TYPE] [int] NULL,
    [ISOCODE] [nvarchar](3) NULL,
    [ADDRFORMAT] [nvarchar](10) NULL,
    [NAME] [nvarchar](30) NULL,
    [GIROACCOUNTVALIDATIONMETHOD] [int] NULL,
    [BANKACCOUNTNUMVALIDATION] [int] NULL,
    [EUROZONECOUNTRY] [int] NULL,
    [CURRENCYCODE] [nvarchar](3) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_045COUNTRYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [COUNTRYID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__COUNTRY__764C846B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__COUNTRY__764C846B]  DEFAULT ('') FOR [COUNTRYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__TYPE__7740A8A4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__TYPE__7740A8A4]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__ISOCODE__7834CCDD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__ISOCODE__7834CCDD]  DEFAULT ('') FOR [ISOCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__ADDRFOR__7928F116]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__ADDRFOR__7928F116]  DEFAULT ('') FOR [ADDRFORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__NAME__7A1D154F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__NAME__7A1D154F]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__GIROACC__7B113988]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__GIROACC__7B113988]  DEFAULT ((0)) FOR [GIROACCOUNTVALIDATIONMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__BANKACC__7C055DC1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__BANKACC__7C055DC1]  DEFAULT ((0)) FOR [BANKACCOUNTNUMVALIDATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__EUROZON__7CF981FA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__EUROZON__7CF981FA]  DEFAULT ((0)) FOR [EUROZONECOUNTRY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__CURRENC__7DEDA633]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__CURRENC__7DEDA633]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTRY__DATAARE__7EE1CA6C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTRY] ADD  CONSTRAINT [DF__COUNTRY__DATAARE__7EE1CA6C]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table COUNTY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[COUNTY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[COUNTY](
    [COUNTRYID] [nvarchar](10) NOT NULL,
    [COUNTYID] [nvarchar](10) NOT NULL,
    [STATEID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_046COUNTRYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [COUNTRYID] ASC,
    [STATEID] ASC,
    [COUNTYID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTY__COUNTRYI__02B25B50]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTY] ADD  CONSTRAINT [DF__COUNTY__COUNTRYI__02B25B50]  DEFAULT ('') FOR [COUNTRYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTY__COUNTYID__03A67F89]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTY] ADD  CONSTRAINT [DF__COUNTY__COUNTYID__03A67F89]  DEFAULT ('') FOR [COUNTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTY__STATEID__049AA3C2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTY] ADD  CONSTRAINT [DF__COUNTY__STATEID__049AA3C2]  DEFAULT ('') FOR [STATEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTY__NAME__058EC7FB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTY] ADD  CONSTRAINT [DF__COUNTY__NAME__058EC7FB]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__COUNTY__DATAAREA__0682EC34]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[COUNTY] ADD  CONSTRAINT [DF__COUNTY__DATAAREA__0682EC34]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view CURRENCY ..'
GO
IF OBJECT_ID(N'[dbo].[CURRENCY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[CURRENCY]
GO
CREATE VIEW [dbo].CURRENCY AS
(
  SELECT
    [CURRENCYCODE],
    [TXT],
    CONVERT([nvarchar](10), '') AS 'LEDGERACCOUNTPROFIT',
    CONVERT([nvarchar](10), '') AS 'LEDGERACCOUNTLOSS',
    [ROUNDOFFSALES],
    [ROUNDOFFPURCH],
    CONVERT([numeric](32, 16), 0) AS 'ROUNDOFFAMOUNT',
    CONVERT([numeric](32, 16), 0) AS 'CONSEXCHRATEMONETARY',
    CONVERT([numeric](32, 16), 0) AS 'CONSEXCHRATENONMONETARY',
    CONVERT([nvarchar](10), '') AS 'LEDGERACCOUNTNONREALLOSS',
    CONVERT([nvarchar](10), '') AS 'LEDGERACCOUNTNONREALPROFIT',
    [ROUNDOFFTYPEPURCH],
    [ROUNDOFFTYPESALES],
    CONVERT([int], 0) AS 'ROUNDOFFTYPEAMOUNT',
    CONVERT([numeric](32, 16), 0) AS 'ROUNDOFFPROJECT',
    CONVERT([int], 0) AS 'ROUNDOFFTYPEPROJECT',
    [ROUNDOFFTYPEPRICE],
    [ROUNDOFFPRICE],
    [SYMBOL],
    CONVERT([nvarchar](10), '') AS 'CURRENCYPREFIX',
    CONVERT([nvarchar](10), '') AS 'CURRENCYSUFFIX',
    CONVERT([int], 0) AS 'ONLINECONVERSIONTOOL',
    [CURRENCYCODEISO],
    CONVERT([int], 0) AS 'GENDERMALEFEMALE',
    [RECID]
  FROM [ax].CURRENCY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view CUSTGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[CUSTGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[CUSTGROUP]
GO
CREATE VIEW [dbo].CUSTGROUP AS
(
  SELECT
    [CUSTGROUP],
    [NAME],
    [DATAAREAID],
    [RECID]
  FROM [ax].CUSTGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view CUSTTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[CUSTTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[CUSTTABLE]
GO
CREATE VIEW [dbo].CUSTTABLE AS
(
  SELECT
    [ACCOUNTNUM],
    [INVOICEACCOUNT],
    [CUSTGROUP],
    [PAYMDAYID] AS 'PAYMTERMID',
    [CASHDISC],
    [CURRENCY],
    [BLOCKED],
    [ONETIMECUSTOMER],
    [ACCOUNTSTATEMENT],
    [CREDITMAX],
    [MANDATORYCREDITLIMIT],
    [VENDACCOUNT],
    [INVENTLOCATION],
    [DLVTERM],
    [DLVMODE],
    [CLEARINGPERIOD],
    [FREIGHTZONE],
    [CREDITRATING],
    [STATISTICSGROUP],
    [PAYMMODE],
    [BANKACCOUNT],
    [CONTACTPERSONID],
    [INVOICEADDRESS],
    [OURACCOUNTNUM],
    [SALESPOOLID],
    [INCLTAX],
    [CUSTITEMGROUPID],
    [NUMBERSEQUENCEGROUP],
    [PAYMDAYID],
    [LINEOFBUSINESSID],
    [DESTINATIONCODEID],
    [WEBSALESORDERDISPLAY],
    [PAYMSPEC],
    [BANKCENTRALBANKPURPOSETEXT],
    [BANKCENTRALBANKPURPOSECODE],
    [PBACUSTGROUPID],
    [DATAAREAID],
    [RECID],
    [VATNUM],
    [TAXGROUP],
    [TAXLICENSENUM],
    [FORECASTDMPINCLUDE],
    [LINEDISC],
    [SALESGROUP],
    [PRICEGROUP],
    [MULTILINEDISC],
    [ENDDISC],
    [MARKUPGROUP],
    [COMMISSIONGROUP],
    CONVERT([int], 0) AS 'DEL_QUOTATIONCOPIES',
    CONVERT([int], 0) AS 'DEL_QUOTATIONORIGINALS',
    CONVERT([int], 0) AS 'DEL_CONFIRMATIONORIGINALS',
    CONVERT([int], 0) AS 'DEL_INVOICECOPIES',
    CONVERT([int], 0) AS 'DEL_INVOICEORIGINALS',
    CONVERT([int], 0) AS 'DEL_PACKINGSLIPCOPIES',
    CONVERT([int], 0) AS 'DEL_PACKINGSLIPORIGINALS',
    CONVERT([int], 0) AS 'DEL_CONFIRMATIONCOPIES',
    [SUPPITEMGROUPID],
    [PACKMATERIALFEELICENSENUM],
    [ORGID],
    [USEPURCHREQUEST],
    CONVERT([int], 0) AS 'NONCHARGABLEACCOUNT',
    [IDENTIFICATIONNUMBER],
    [PARTY],
    [IENUM_BR],
    [SUFRAMANUMBER_BR],
    [SUFRAMA_BR],
    [CNPJCPFNUM_BR]
  FROM [ax].CUSTTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table DATAAREA ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DATAAREA]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DATAAREA](
    [ID] [nvarchar](3) NOT NULL,
    [NAME] [nvarchar](40) NOT NULL,
    [ISVIRTUAL] [int] NOT NULL,
    [ALWAYSNATIVE] [int] NOT NULL,
    [RECID] [bigint] NOT NULL
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATAAREA]') AND name = N'I_65533ID')
CREATE UNIQUE CLUSTERED INDEX [I_65533ID] ON [dbo].[DATAAREA]
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DATAAREA__ID__3DE82FB7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DATAAREA] ADD  CONSTRAINT [DF__DATAAREA__ID__3DE82FB7] DEFAULT ('') FOR [ID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DATAAREA__NAME__3EDC53F0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DATAAREA] ADD CONSTRAINT [DF__DATAAREA__NAME__3EDC53F0] DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DATAAREA__ISVIRT__3FD07829]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DATAAREA] ADD CONSTRAINT [DF__DATAAREA__ISVIRT__3FD07829] DEFAULT ((0)) FOR [ISVIRTUAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DATAAREA__ALWAYS__40C49C62]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DATAAREA] ADD CONSTRAINT [DF__DATAAREA__ALWAYS__40C49C62] DEFAULT ((0)) FOR [ALWAYSNATIVE]
END

-------------------------------------------------------------------------------
PRINT 'Creating table DATADIRTYPEMAP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DATADIRTYPEMAP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DATADIRTYPEMAP](
    [MSTYPE] [int] NOT NULL,
    [DDTYPE] [int] NULL,
    [DESCRIPTION] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
    [MSTYPE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table DBCAPACITY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DBCAPACITY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DBCAPACITY](
    [DBNAME] [nvarchar](60) NOT NULL,
    [DATESTAMP] [datetime] NOT NULL,
    [SIZEINGB] [decimal](18, 2) NULL,
 CONSTRAINT [PK_DBCAPACITY] PRIMARY KEY CLUSTERED
(
    [DBNAME] ASC,
    [DATESTAMP] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DBCAPACIT__DATES__382F5661]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DBCAPACITY] ADD  CONSTRAINT [DF__DBCAPACIT__DATES__382F5661] DEFAULT (getdate()) FOR [DATESTAMP]
END

-------------------------------------------------------------------------------
PRINT 'Creating table DBTABLESIZES ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DBTABLESIZES]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DBTABLESIZES](
    [name] [nvarchar](128) NOT NULL,
    [rows] [nvarchar](11) NULL,
    [reserved] [nvarchar](18) NULL,
    [data] [decimal](18, 0) NULL,
    [index_size] [nvarchar](18) NULL,
    [unused] [nvarchar](18) NULL,
    [DateStamp] [datetime] NULL,
 CONSTRAINT [PK_DBTABLESIZES] PRIMARY KEY CLUSTERED
(
    [name] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DBTABLESI__DateS__3552E9B6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DBTABLESIZES] ADD  CONSTRAINT [DF__DBTABLESI__DateS__3552E9B6] DEFAULT (getdate()) FOR [DateStamp]
END

-------------------------------------------------------------------------------
PRINT 'Creating table DETAILTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DETAILTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DETAILTABLE](
    [ID] [int] NOT NULL,
    [TRANSID] [int] NOT NULL,
    [AMOUNT] [decimal](18, 0) NULL,
 CONSTRAINT [PK_DETAILTABLE] PRIMARY KEY CLUSTERED
(
    [ID] ASC,
    [TRANSID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table DIMENSIONS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DIMENSIONS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DIMENSIONS](
    [DESCRIPTION] [nvarchar](30) NULL,
    [NUM] [nvarchar](10) NULL,
    [DIMENSIONCODE] [int] NULL,
    [INCHARGE] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIMENSION__DESCR__75435199]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIMENSIONS] ADD  CONSTRAINT [DF__DIMENSION__DESCR__75435199]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIMENSIONS__NUM__763775D2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIMENSIONS] ADD  CONSTRAINT [DF__DIMENSIONS__NUM__763775D2]  DEFAULT ('') FOR [NUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIMENSION__DIMEN__772B9A0B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIMENSIONS] ADD  CONSTRAINT [DF__DIMENSION__DIMEN__772B9A0B]  DEFAULT ((0)) FOR [DIMENSIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIMENSION__INCHA__781FBE44]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIMENSIONS] ADD  CONSTRAINT [DF__DIMENSION__INCHA__781FBE44]  DEFAULT ('') FOR [INCHARGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIMENSION__DATAA__7913E27D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIMENSIONS] ADD  CONSTRAINT [DF__DIMENSION__DATAA__7913E27D]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view DIRADDRESSBOOK ..'
GO
IF OBJECT_ID(N'[dbo].[DIRADDRESSBOOK]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DIRADDRESSBOOK]
GO
CREATE VIEW [dbo].DIRADDRESSBOOK AS
(
  SELECT
    [NAME],
    [DESCRIPTION],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].DIRADDRESSBOOK
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view DIRADDRESSBOOKPARTY ..'
GO
IF OBJECT_ID(N'[dbo].[DIRADDRESSBOOKPARTY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DIRADDRESSBOOKPARTY]
GO
CREATE VIEW [dbo].DIRADDRESSBOOKPARTY AS
(
  SELECT
    [PARTY],
    [ADDRESSBOOK],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'VALIDFROM',
    CONVERT([int], 0) AS 'VALIDFROMTZID',
    CONVERT([datetime], '2154-12-31T23:59:59.000') AS 'VALIDTO',
    CONVERT([int], 0) AS 'VALIDTOTZID',
    [RECID]
  FROM [ax].DIRADDRESSBOOKPARTY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table DIRPARTYADDRESSRELATIONSHI1066 ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DIRPARTYADDRESSRELATIONSHI1066]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DIRPARTYADDRESSRELATIONSHI1066](
    [ADDRESSRECID] [bigint] NOT NULL,
    [REFCOMPANYID] [nvarchar](4) NOT NULL,
    [PARTYADDRESSRELATIONSHIPRECID] [bigint] NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NOT NULL,
 CONSTRAINT [I_1066KEYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PARTYADDRESSRELATIONSHIPRECID] ASC,
    [REFCOMPANYID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__ADDRE__2610A626]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHI1066] ADD  CONSTRAINT [DF__DIRPARTYA__ADDRE__2610A626] DEFAULT ((0)) FOR [ADDRESSRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__REFCO__2704CA5F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHI1066] ADD CONSTRAINT [DF__DIRPARTYA__REFCO__2704CA5F] DEFAULT ('') FOR [REFCOMPANYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__PARTY__27F8EE98]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHI1066] ADD CONSTRAINT [DF__DIRPARTYA__PARTY__27F8EE98] DEFAULT ((0)) FOR [PARTYADDRESSRELATIONSHIPRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__DATAA__28ED12D1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHI1066] ADD CONSTRAINT [DF__DIRPARTYA__DATAA__28ED12D1] DEFAULT ('dat') FOR [DATAAREAID]
END


-------------------------------------------------------------------------------
PRINT 'Creating table DIRPARTYADDRESSRELATIONSHIP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DIRPARTYADDRESSRELATIONSHIP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP](
    [PARTYID] [nvarchar](20) NOT NULL,
    [ISPRIMARY] [int] NOT NULL,
    [STATUS] [int] NOT NULL,
    [VALIDTODATETIME] [datetime] NOT NULL,
    [VALIDTODATETIMETZID] [int] NOT NULL,
    [VALIDFROMDATETIME] [datetime] NOT NULL,
    [VALIDFROMDATETIMETZID] [int] NOT NULL,
    [SHARED] [int] NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NOT NULL,
 CONSTRAINT [I_2596RECID] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [RECID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__PARTY__19AACF41]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD  CONSTRAINT [DF__DIRPARTYA__PARTY__19AACF41] DEFAULT ('') FOR [PARTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__ISPRI__1A9EF37A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__ISPRI__1A9EF37A] DEFAULT ((0)) FOR [ISPRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__STATU__1B9317B3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__STATU__1B9317B3] DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__VALID__1C873BEC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__VALID__1C873BEC] DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDTODATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__VALID__1D7B6025]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__VALID__1D7B6025] DEFAULT ((37001)) FOR [VALIDTODATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__VALID__1E6F845E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__VALID__1E6F845E] DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDFROMDATETIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__VALID__1F63A897]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__VALID__1F63A897] DEFAULT ((37001)) FOR [VALIDFROMDATETIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__SHARE__2057CCD0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__SHARE__2057CCD0] DEFAULT ((0)) FOR [SHARED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DIRPARTYA__DATAA__214BF109]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DIRPARTYADDRESSRELATIONSHIP] ADD CONSTRAINT [DF__DIRPARTYA__DATAA__214BF109] DEFAULT ('dat') FOR [DATAAREAID]
END


-------------------------------------------------------------------------------
PRINT 'Creating view DIRPARTYLOCATION ..'
GO
IF OBJECT_ID(N'[dbo].[DIRPARTYLOCATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DIRPARTYLOCATION]
GO
CREATE VIEW [dbo].DIRPARTYLOCATION AS
(
  SELECT
    [PARTY],
    [LOCATION],
    CONVERT([bigint], 0) AS 'LOCATIONROLE',
    [ATTENTIONTOADDRESSLINE],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'VALIDFROM',
    CONVERT([int], 0) AS 'VALIDFROMTZID',
    CONVERT([datetime], '2154-12-31T23:59:59.000') AS 'VALIDTO',
    CONVERT([int], 0) AS 'VALIDTOTZID',
    CONVERT([bigint], 0) AS 'PRIVACYGROUP',
    [ISPOSTALADDRESS],
    [ISPRIMARY],
    [ISPRIVATE],
    [ISLOCATIONOWNER],
    [RECID]
  FROM [ax].DIRPARTYLOCATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view DIRPARTYLOCATIONROLE ..'
GO
IF OBJECT_ID(N'[dbo].[DIRPARTYLOCATIONROLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DIRPARTYLOCATIONROLE]
GO
CREATE VIEW [dbo].DIRPARTYLOCATIONROLE AS
(
  SELECT
    [PARTYLOCATION],
    [LOCATIONROLE],
    [RECID]
  FROM [ax].DIRPARTYLOCATIONROLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view DIRPARTYTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[DIRPARTYTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DIRPARTYTABLE]
GO
CREATE VIEW [dbo].DIRPARTYTABLE AS
(
  SELECT
    [NAME],
    [LANGUAGEID],
    [NAMEALIAS],
    CONVERT([nvarchar](max), NULL) AS 'MEMO',
    [PARTYNUMBER],
    [INSTANCERELATIONTYPE],
    [KNOWNAS],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].DIRPARTYTABLE
)
GO
-------------------------------------------------------------------------------
PRINT N'Creating view [DIRPERSONNAME] ..';

IF OBJECT_ID(N'[dbo].[DIRPERSONNAME]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DIRPERSONNAME]
GO

CREATE VIEW [dbo].[DIRPERSONNAME] AS
(
SELECT
       [FIRSTNAME]
      ,[LASTNAME]
      ,[MIDDLENAME]
      ,[PERSON]
      ,[VALIDFROM]
      ,[VALIDFROMTZID]
      ,[VALIDTO]
      ,[VALIDTOTZID]
      ,[RECID]
  FROM [ax].[DIRPERSONNAME]
  )
GO
-------------------------------------------------------------------------------
PRINT 'Creating view DLVMODE ..'
GO
IF OBJECT_ID(N'[dbo].[DLVMODE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DLVMODE]
GO
CREATE VIEW [dbo].DLVMODE AS
(
  SELECT
    [CODE],
    [TXT],
    [SHIPCARRIERDLVTYPE],
    [SHIPCARRIERID],
    [SHIPCARRIERACCOUNTCODE],
    [SHIPCARRIERNAME],
    [DATAAREAID],
    [RECID],
    [MARKUPGROUP]
  FROM [ax].DLVMODE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table DOMAININFO ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOMAININFO]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[DOMAININFO](
    [ID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](40) NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_DOMAININFO] PRIMARY KEY NONCLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DOMAININFO]') AND name = N'I_65510ID')
CREATE UNIQUE CLUSTERED INDEX [I_65510ID] ON [dbo].[DOMAININFO]
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DOMAININFO__ID__26068485]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DOMAININFO] ADD  CONSTRAINT [DF__DOMAININFO__ID__26068485]  DEFAULT ('') FOR [ID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__DOMAININFO__NAME__26FAA8BE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[DOMAININFO] ADD  CONSTRAINT [DF__DOMAININFO__NAME__26FAA8BE]  DEFAULT ('') FOR [NAME]
END

-------------------------------------------------------------------------------
PRINT 'Creating view ECORESATTRIBUTE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESATTRIBUTE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESATTRIBUTE]
GO
CREATE VIEW [dbo].ECORESATTRIBUTE AS
(
  SELECT
    [NAME],
    [ATTRIBUTETYPE],
    [ATTRIBUTEMODIFIER],
    [RECID]
  FROM [ax].ECORESATTRIBUTE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESATTRIBUTEDEFAULTVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESATTRIBUTEDEFAULTVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESATTRIBUTEDEFAULTVALUE]
GO
CREATE VIEW [dbo].ECORESATTRIBUTEDEFAULTVALUE AS
(
  SELECT
    [VALUE],
    [ATTRIBUTE],
    [RECID]
  FROM [ax].ECORESATTRIBUTEDEFAULTVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESATTRIBUTETRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESATTRIBUTETRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESATTRIBUTETRANSLATION]
GO
CREATE VIEW [dbo].ECORESATTRIBUTETRANSLATION AS
(
  SELECT
    [DESCRIPTION],
    [LANGUAGE],
    [ATTRIBUTE],
    [FRIENDLYNAME],
    [HELPTEXT],
    [RECID]
  FROM [ax].ECORESATTRIBUTETRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESATTRIBUTETYPE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESATTRIBUTETYPE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESATTRIBUTETYPE]
GO
CREATE VIEW [dbo].ECORESATTRIBUTETYPE AS
(
  SELECT
    [NAME],
    [DATATYPE],
    [ISENUMERATION],
    [ISHIDDEN],
    [RECID]
  FROM [ax].ECORESATTRIBUTETYPE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESATTRIBUTEVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESATTRIBUTEVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESATTRIBUTEVALUE]
GO
CREATE VIEW [dbo].ECORESATTRIBUTEVALUE AS
(
  SELECT
    [VALUE],
    [INSTANCEVALUE],
    [ATTRIBUTE],
    [RECID]
  FROM [ax].ECORESATTRIBUTEVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESBOOLEANVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESBOOLEANVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESBOOLEANVALUE]
GO
CREATE VIEW [dbo].ECORESBOOLEANVALUE AS
(
  SELECT
    [BOOLEANVALUE],
    [RECID]
  FROM [ax].ECORESBOOLEANVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESCATEGORY ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESCATEGORY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCATEGORY]
GO
CREATE VIEW [dbo].ECORESCATEGORY AS
(
  SELECT
    [CATEGORYHIERARCHY],
    [PARENTCATEGORY],
    [NAME],
    [CODE],
    [ISACTIVE],
    [CHANGESTATUS],
    [LEVEL] AS 'LEVEL_',
    [NESTEDSETRIGHT],
    [NESTEDSETLEFT],
    [ISCATEGORYATTRIBUTESINHERITED],
    [INSTANCERELATIONTYPE],
    [ISTANGIBLE],
    [DEFAULTPROJECTGLOBALCATEGORY],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RELATIONTYPE],
    [RECID]
  FROM [ax].ECORESCATEGORY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESCATEGORYHIERARCHY ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESCATEGORYHIERARCHY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCATEGORYHIERARCHY]
GO
CREATE VIEW [dbo].ECORESCATEGORYHIERARCHY AS
(
  SELECT
    [NAME],
    [HIERARCHYMODIFIER],
    [RECID]
  FROM [ax].ECORESCATEGORYHIERARCHY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESCATEGORYHIERARCHYROLE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESCATEGORYHIERARCHYROLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCATEGORYHIERARCHYROLE]
GO
CREATE VIEW [dbo].ECORESCATEGORYHIERARCHYROLE AS
(
  SELECT
    [NAMEDCATEGORYHIERARCHYROLE],
    [CATEGORYHIERARCHY],
    [RECID]
  FROM [ax].ECORESCATEGORYHIERARCHYROLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESCATEGORYTRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESCATEGORYTRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCATEGORYTRANSLATION]
GO
CREATE VIEW [dbo].ECORESCATEGORYTRANSLATION AS
(
  SELECT
    [SEARCHTEXT],
    [DESCRIPTION],
    [FRIENDLYNAME],
    [CATEGORY],
    [LANGUAGEID],
    [RECID]
  FROM [ax].ECORESCATEGORYTRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESCOLOR ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESCOLOR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCOLOR]
GO
CREATE VIEW [dbo].ECORESCOLOR AS
(
  SELECT
    [NAME],
    [RECID]
  FROM [ax].ECORESCOLOR
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESCONFIGURATION ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESCONFIGURATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCONFIGURATION]
GO
CREATE VIEW [dbo].ECORESCONFIGURATION AS
(
  SELECT
    [NAME],
    [RECID]
  FROM [ax].ECORESCONFIGURATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESCURRENCYVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESCURRENCYVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCURRENCYVALUE]
GO
CREATE VIEW [dbo].ECORESCURRENCYVALUE AS
(
  SELECT
    [CURRENCYVALUE],
    [CURRENCYCODE],
    [RECID]
  FROM [ax].ECORESCURRENCYVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESDATETIMEVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESDATETIMEVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESDATETIMEVALUE]
GO
CREATE VIEW [dbo].ECORESDATETIMEVALUE AS
(
  SELECT
    [DATETIMEVALUE],
    [RECID]
  FROM [ax].ECORESDATETIMEVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESFLOATVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESFLOATVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESFLOATVALUE]
GO
CREATE VIEW [dbo].ECORESFLOATVALUE AS
(
  SELECT
    [FLOATVALUE],
    [FLOATUNITOFMEASURE],
    [RECID]
  FROM [ax].ECORESFLOATVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESINSTANCEVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESINSTANCEVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESINSTANCEVALUE]
GO
CREATE VIEW [dbo].ECORESINSTANCEVALUE AS
(
  SELECT
    [INSTANCERELATIONTYPE],
    [RELATIONTYPE],
    [RECID]
  FROM [ax].ECORESINSTANCEVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESINTVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESINTVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESINTVALUE]
GO
CREATE VIEW [dbo].ECORESINTVALUE AS
(
  SELECT
    [INTVALUE],
    [INTUNITOFMEASURE],
    [RECID]
  FROM [ax].ECORESINTVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCT ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCT]
GO
CREATE VIEW [dbo].ECORESPRODUCT AS
(
  SELECT
    [INSTANCERELATIONTYPE],
    [DISPLAYPRODUCTNUMBER],
    [SEARCHNAME],
    [PRODUCTTYPE],
    [RELATIONTYPE],
    [RECID]
  FROM [ax].ECORESPRODUCT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTCATEGORY ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTCATEGORY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTCATEGORY]
GO
CREATE VIEW [dbo].ECORESPRODUCTCATEGORY AS
(
  SELECT
    [CATEGORYHIERARCHY],
    [CATEGORY],
    [PRODUCT],
    [MODIFIEDDATETIME],
    [RECID]
  FROM [ax].ECORESPRODUCTCATEGORY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTIMAGE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTIMAGE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTIMAGE]
GO
CREATE VIEW [dbo].ECORESPRODUCTIMAGE AS
(
  SELECT
    [DEFAULTIMAGE],
    [REFRECORD],
    [MEDIUMSIZE],
    [RECID]
  FROM [ax].ECORESPRODUCTIMAGE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTINSTANCEVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTINSTANCEVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTINSTANCEVALUE]
GO
CREATE VIEW [dbo].ECORESPRODUCTINSTANCEVALUE AS
(
  SELECT
    [PRODUCT],
    [RECID]
  FROM [ax].ECORESPRODUCTINSTANCEVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTMASTERCOLOR ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTMASTERCOLOR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTMASTERCOLOR]
GO
CREATE VIEW [dbo].ECORESPRODUCTMASTERCOLOR AS
(
  SELECT
    [COLORPRODUCTMASTER],
    [COLORPRODUCTDIMENSIONATTRIBUTE],
    [COLOR],
    [RECID]
  FROM [ax].ECORESPRODUCTMASTERCOLOR
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTMASTERCONFIGURATION ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTMASTERCONFIGURATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTMASTERCONFIGURATION]
GO
CREATE VIEW [dbo].ECORESPRODUCTMASTERCONFIGURATION AS
(
  SELECT
    [CONFIGPRODUCTMASTER],
    [CONFIGPRODUCTDIMENSIONATTRIBUTE],
    [CONFIGURATION],
    [RECID]
  FROM [ax].ECORESPRODUCTMASTERCONFIGURATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTMASTERDIMENSIONVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTMASTERDIMENSIONVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTMASTERDIMENSIONVALUE]
GO
CREATE VIEW [dbo].ECORESPRODUCTMASTERDIMENSIONVALUE AS
(
  SELECT
    [INSTANCERELATIONTYPE],
    [RELATIONTYPE],
    [RECID],
    [RETAILWEIGHT],
    [RETAILDISPLAYORDER]
  FROM [ax].ECORESPRODUCTMASTERDIMENSIONVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTMASTERDIMVALUETRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTMASTERDIMVALUETRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTMASTERDIMVALUETRANSLATION]
GO
CREATE VIEW [dbo].ECORESPRODUCTMASTERDIMVALUETRANSLATION AS
(
  SELECT
    [PRODUCTMASTERDIMENSIONVALUE],
    [LANGUAGEID],
    [NAME],
    [DESCRIPTION],
    [RECID]
  FROM [ax].ECORESPRODUCTMASTERDIMVALUETRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTMASTERSIZE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTMASTERSIZE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTMASTERSIZE]
GO
CREATE VIEW [dbo].ECORESPRODUCTMASTERSIZE AS
(
  SELECT
    [SIZEPRODUCTMASTER],
    [SIZEPRODUCTDIMENSIONATTRIBUTE],
    [SIZE] AS 'SIZE_',
    [RECID]
  FROM [ax].ECORESPRODUCTMASTERSIZE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTMASTERSTYLE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTMASTERSTYLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTMASTERSTYLE]
GO
CREATE VIEW [dbo].ECORESPRODUCTMASTERSTYLE AS
(
  SELECT
    [STYLE],
    [STYLEPRODUCTDIMENSIONATTRIBUTE],
    [STYLEPRODUCTMASTER],
    [RECID]
  FROM [ax].ECORESPRODUCTMASTERSTYLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESPRODUCTTRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESPRODUCTTRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESPRODUCTTRANSLATION]
GO
CREATE VIEW [dbo].ECORESPRODUCTTRANSLATION AS
(
  SELECT
    [DESCRIPTION],
    [NAME],
    [PRODUCT],
    [LANGUAGEID],
    [RECID]
  FROM [ax].ECORESPRODUCTTRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESREFERENCEVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESREFERENCEVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESREFERENCEVALUE]
GO
CREATE VIEW [dbo].ECORESREFERENCEVALUE AS
(
  SELECT
    [REFFIELDID],
    [REFRECID],
    [REFTABLEID],
    [RECID]
  FROM [ax].ECORESREFERENCEVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESSIZE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESSIZE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESSIZE]
GO
CREATE VIEW [dbo].ECORESSIZE AS
(
  SELECT
    [NAME],
    [RECID]
  FROM [ax].ECORESSIZE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESSTYLE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESSTYLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESSTYLE]
GO
CREATE VIEW [dbo].ECORESSTYLE AS
(
  SELECT
    [NAME],
    [RECID]
  FROM [ax].ECORESSTYLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESTEXTVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESTEXTVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESTEXTVALUE]
GO
CREATE VIEW [dbo].ECORESTEXTVALUE AS
(
  SELECT
    [TEXTVALUE],
    [RECID]
  FROM [ax].ECORESTEXTVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESTEXTVALUETRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESTEXTVALUETRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESTEXTVALUETRANSLATION]
GO
CREATE VIEW [dbo].ECORESTEXTVALUETRANSLATION AS
(
  SELECT
    [TEXTVALUE],
    [TEXTVALUETABLE],
    [LANGUAGE],
    [RECID]
  FROM [ax].ECORESTEXTVALUETRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESTRACKINGDIMENSIONGROUPFLDSETUP ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESTRACKINGDIMENSIONGROUPFLDSETUP]
GO
CREATE VIEW [dbo].ECORESTRACKINGDIMENSIONGROUPFLDSETUP AS
(
  SELECT
    [TRACKINGDIMENSIONGROUP],
    [DIMENSIONFIELDID],
    [ISACTIVE],
    [ISALLOWBLANKISSUEENABLED],
    [ISSALESPROCESSACTIVATED],
    [RECID]
  FROM [ax].ECORESTRACKINGDIMENSIONGROUPFLDSETUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESTRACKINGDIMENSIONGROUPITEM ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESTRACKINGDIMENSIONGROUPITEM]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESTRACKINGDIMENSIONGROUPITEM]
GO
CREATE VIEW [dbo].ECORESTRACKINGDIMENSIONGROUPITEM AS
(
  SELECT
    [TRACKINGDIMENSIONGROUP],
    [ITEMID],
    [ITEMDATAAREAID],
    [RECID]
  FROM [ax].ECORESTRACKINGDIMENSIONGROUPITEM
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESTRACKINGDIMENSIONGROUPPRODUCT ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESTRACKINGDIMENSIONGROUPPRODUCT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESTRACKINGDIMENSIONGROUPPRODUCT]
GO
CREATE VIEW [dbo].ECORESTRACKINGDIMENSIONGROUPPRODUCT AS
(
  SELECT
    [PRODUCT],
    [TRACKINGDIMENSIONGROUP],
    [RECID]
  FROM [ax].ECORESTRACKINGDIMENSIONGROUPPRODUCT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view ECORESVALUE ..'
GO
IF OBJECT_ID(N'[dbo].[ECORESVALUE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESVALUE]
GO
CREATE VIEW [dbo].ECORESVALUE AS
(
  SELECT
    [INSTANCERELATIONTYPE],
    [RELATIONTYPE],
    [RECID]
  FROM [ax].ECORESVALUE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table EMPLOYEE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EMPLOYEE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EMPLOYEE](
    [OID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [OCCUPATION] [uniqueidentifier] NULL,
    [TITLEOFCOURTESY] [int] NULL,
    [PHOTO] [image] NULL,
 CONSTRAINT [PK_EMPLOYEE] PRIMARY KEY CLUSTERED
(
    [OID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table EMPLTASK ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EMPLTASK]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EMPLTASK](
    [EMPLID] [nvarchar](10) NOT NULL,
    [TASKID] [nvarchar](20) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_105WORKEMPLOYEEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [TASKID] ASC,
    [EMPLID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EMPLTASK__EMPLID__7D78A4E7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EMPLTASK] ADD  CONSTRAINT [DF__EMPLTASK__EMPLID__7D78A4E7]  DEFAULT ('') FOR [EMPLID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EMPLTASK__TASKID__7E6CC920]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EMPLTASK] ADD  CONSTRAINT [DF__EMPLTASK__TASKID__7E6CC920]  DEFAULT ('') FOR [TASKID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EMPLTASK__DATAAR__7F60ED59]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EMPLTASK] ADD  CONSTRAINT [DF__EMPLTASK__DATAAR__7F60ED59]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table EMPLWORKTASK ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EMPLWORKTASK]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EMPLWORKTASK](
    [TASKID] [nvarchar](20) NOT NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NOT NULL,
 CONSTRAINT [I_423TASKIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [TASKID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EMPLWORKT__TASKI__300FDD03]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EMPLWORKTASK] ADD  CONSTRAINT [DF__EMPLWORKT__TASKI__300FDD03]  DEFAULT ('') FOR [TASKID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EMPLWORKT__DESCR__3104013C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EMPLWORKTASK] ADD  CONSTRAINT [DF__EMPLWORKT__DESCR__3104013C]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EMPLWORKT__DATAA__31F82575]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EMPLWORKTASK] ADD  CONSTRAINT [DF__EMPLWORKT__DATAA__31F82575]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table EPMYINFO ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EPMYINFO]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EPMYINFO](
    [REFTABLEID] [int] NOT NULL,
    [REFRECID] [bigint] NOT NULL,
    [WEBUSER] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_1477REFIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [REFTABLEID] ASC,
    [WEBUSER] ASC,
    [REFRECID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPMYINFO__REFTAB__46FEFAAA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPMYINFO] ADD  CONSTRAINT [DF__EPMYINFO__REFTAB__46FEFAAA]  DEFAULT ((0)) FOR [REFTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPMYINFO__REFREC__47F31EE3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPMYINFO] ADD  CONSTRAINT [DF__EPMYINFO__REFREC__47F31EE3]  DEFAULT ((0)) FOR [REFRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPMYINFO__WEBUSE__48E7431C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPMYINFO] ADD  CONSTRAINT [DF__EPMYINFO__WEBUSE__48E7431C]  DEFAULT ('') FOR [WEBUSER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPMYINFO__DATAAR__49DB6755]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPMYINFO] ADD  CONSTRAINT [DF__EPMYINFO__DATAAR__49DB6755]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table EPTRANSACTIONSUMTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EPTRANSACTIONSUMTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EPTRANSACTIONSUMTRANS](
    [REFTABLEID] [int] NOT NULL,
    [REFRECID] [bigint] NOT NULL,
    [AMOUNTMST] [image] NULL,
    [AMOUNTCUR] [image] NULL,
    [CURRENCYCODE] [image] NULL,
    [REALBASE] [image] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_1591REFIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [REFTABLEID] ASC,
    [REFRECID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPTRANSAC__REFTA__27A64AE2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPTRANSACTIONSUMTRANS] ADD  CONSTRAINT [DF__EPTRANSAC__REFTA__27A64AE2]  DEFAULT ((0)) FOR [REFTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPTRANSAC__REFRE__289A6F1B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPTRANSACTIONSUMTRANS] ADD  CONSTRAINT [DF__EPTRANSAC__REFRE__289A6F1B]  DEFAULT ((0)) FOR [REFRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPTRANSAC__AMOUN__298E9354]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPTRANSACTIONSUMTRANS] ADD  CONSTRAINT [DF__EPTRANSAC__AMOUN__298E9354]  DEFAULT (NULL) FOR [AMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPTRANSAC__AMOUN__2A82B78D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPTRANSACTIONSUMTRANS] ADD  CONSTRAINT [DF__EPTRANSAC__AMOUN__2A82B78D]  DEFAULT (NULL) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPTRANSAC__CURRE__2B76DBC6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPTRANSACTIONSUMTRANS] ADD  CONSTRAINT [DF__EPTRANSAC__CURRE__2B76DBC6]  DEFAULT (NULL) FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPTRANSAC__REALB__2C6AFFFF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPTRANSACTIONSUMTRANS] ADD  CONSTRAINT [DF__EPTRANSAC__REALB__2C6AFFFF]  DEFAULT (NULL) FOR [REALBASE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EPTRANSAC__DATAA__2D5F2438]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EPTRANSACTIONSUMTRANS] ADD  CONSTRAINT [DF__EPTRANSAC__DATAA__2D5F2438]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view EXCEPTIONCODETABLE_BR ..'
GO
IF OBJECT_ID(N'[dbo].[EXCEPTIONCODETABLE_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].EXCEPTIONCODETABLE_BR
GO
CREATE VIEW [dbo].EXCEPTIONCODETABLE_BR AS
(
  SELECT
    [APPROXTAXVALUEIMPORTED],
    [APPROXTAXVALUENATIONAL],
    [DATAAREAID],
    [EXCEPTIONCODE],
    [RECID],
    [ROWVERSION],
    [TAXFISCALCLASSIFICATIONID]
  FROM [ax].EXCEPTIONCODETABLE_BR
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view EXCHANGERATE ..'
GO
IF OBJECT_ID(N'[dbo].[EXCHANGERATE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[EXCHANGERATE]
GO
CREATE VIEW [dbo].EXCHANGERATE AS
(
  SELECT
    [EXCHANGERATECURRENCYPAIR],
    [EXCHANGERATE],
    [VALIDTO],
    [VALIDFROM],
    [MODIFIEDDATETIME],
    [RECID]
  FROM [ax].EXCHANGERATE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view EXCHANGERATECURRENCYPAIR ..'
GO
IF OBJECT_ID(N'[dbo].[EXCHANGERATECURRENCYPAIR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[EXCHANGERATECURRENCYPAIR]
GO
CREATE VIEW [dbo].EXCHANGERATECURRENCYPAIR AS
(
  SELECT
    [FROMCURRENCYCODE],
    [TOCURRENCYCODE],
    [EXCHANGERATETYPE],
    [EXCHANGERATEDISPLAYFACTOR],
    [MODIFIEDDATETIME],
    [RECID]
  FROM [ax].EXCHANGERATECURRENCYPAIR
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view EXCHANGERATETYPE ..'
GO
IF OBJECT_ID(N'[dbo].[EXCHANGERATETYPE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[EXCHANGERATETYPE]
GO
CREATE VIEW [dbo].EXCHANGERATETYPE AS
(
  SELECT
    [NAME],
    [DESCRIPTION],
    [RECID]
  FROM [ax].EXCHANGERATETYPE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table EXTCODETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EXTCODETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EXTCODETABLE](
    [EXTCODETABLEID] [int] NOT NULL,
    [EXTCODEID] [nvarchar](10) NOT NULL,
    [EXTCODECODE] [nvarchar](50) NULL,
    [EXTCODECODEALIAS] [nvarchar](50) NULL,
    [STANDARDCODE] [int] NULL,
    [EXTCODEDESCRIPTION] [nvarchar](80) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_1340EXTCODEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [EXTCODETABLEID] ASC,
    [EXTCODEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODETA__EXTCO__58098B1B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODETABLE] ADD  CONSTRAINT [DF__EXTCODETA__EXTCO__58098B1B]  DEFAULT ((0)) FOR [EXTCODETABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODETA__EXTCO__58FDAF54]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODETABLE] ADD  CONSTRAINT [DF__EXTCODETA__EXTCO__58FDAF54]  DEFAULT ('') FOR [EXTCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODETA__EXTCO__59F1D38D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODETABLE] ADD  CONSTRAINT [DF__EXTCODETA__EXTCO__59F1D38D]  DEFAULT ('') FOR [EXTCODECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODETA__EXTCO__5AE5F7C6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODETABLE] ADD  CONSTRAINT [DF__EXTCODETA__EXTCO__5AE5F7C6]  DEFAULT ('') FOR [EXTCODECODEALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODETA__STAND__5BDA1BFF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODETABLE] ADD  CONSTRAINT [DF__EXTCODETA__STAND__5BDA1BFF]  DEFAULT ((0)) FOR [STANDARDCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODETA__EXTCO__5CCE4038]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODETABLE] ADD  CONSTRAINT [DF__EXTCODETA__EXTCO__5CCE4038]  DEFAULT ('') FOR [EXTCODEDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODETA__DATAA__5DC26471]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODETABLE] ADD  CONSTRAINT [DF__EXTCODETA__DATAA__5DC26471]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table EXTCODEVALUETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EXTCODEVALUETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EXTCODEVALUETABLE](
    [EXTCODERELATIONTABLEID] [int] NOT NULL,
    [EXTCODERELATIONRECID] [bigint] NOT NULL,
    [EXTCODEID] [nvarchar](10) NOT NULL,
    [EXTCODEVALUE] [nvarchar](50) NULL,
    [EXTCODEVALUEALIAS] [nvarchar](50) NULL,
    [EXTCODETABLETABLEID] [int] NULL,
    [EXTCODESUBMODULE] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_1341EXTCODEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [EXTCODERELATIONTABLEID] ASC,
    [EXTCODERELATIONRECID] ASC,
    [EXTCODEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__EXTCO__31CD3CEC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__EXTCO__31CD3CEC]  DEFAULT ((0)) FOR [EXTCODERELATIONTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__EXTCO__32C16125]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__EXTCO__32C16125]  DEFAULT ((0)) FOR [EXTCODERELATIONRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__EXTCO__33B5855E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__EXTCO__33B5855E]  DEFAULT ('') FOR [EXTCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__EXTCO__34A9A997]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__EXTCO__34A9A997]  DEFAULT ('') FOR [EXTCODEVALUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__EXTCO__359DCDD0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__EXTCO__359DCDD0]  DEFAULT ('') FOR [EXTCODEVALUEALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__EXTCO__3691F209]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__EXTCO__3691F209]  DEFAULT ((0)) FOR [EXTCODETABLETABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__EXTCO__37861642]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__EXTCO__37861642]  DEFAULT ((0)) FOR [EXTCODESUBMODULE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__EXTCODEVA__DATAA__387A3A7B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[EXTCODEVALUETABLE] ADD  CONSTRAINT [DF__EXTCODEVA__DATAA__387A3A7B]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view HCMJOB ..'
GO
IF OBJECT_ID(N'[dbo].[HCMJOB]', N'V') IS NOT NULL
    DROP VIEW [dbo].[HCMJOB]
GO
CREATE VIEW [dbo].HCMJOB AS
(
  SELECT
    [JOBID],
    [MAXIMUMPOSITIONS],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].HCMJOB
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view HCMPOSITION ..'
GO
IF OBJECT_ID(N'[dbo].[HCMPOSITION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[HCMPOSITION]
GO
CREATE VIEW [dbo].HCMPOSITION AS
(
  SELECT
    [POSITIONID],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].HCMPOSITION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view HCMPOSITIONDETAIL ..'
GO
IF OBJECT_ID(N'[dbo].[HCMPOSITIONDETAIL]', N'V') IS NOT NULL
    DROP VIEW [dbo].[HCMPOSITIONDETAIL]
GO
CREATE VIEW [dbo].HCMPOSITIONDETAIL AS
(
  SELECT
    [POSITION],
    [VALIDTO],
    [VALIDTOTZID],
    [VALIDFROM],
    [VALIDFROMTZID],
    [JOB],
    [DEPARTMENT],
    [DESCRIPTION],
    [FULLTIMEEQUIVALENCY],
    [TITLE],
    [POSITIONTYPE],
    [COMPLOCATION],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].HCMPOSITIONDETAIL
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view HCMPOSITIONWORKERASSIGNMENT ..'
GO
IF OBJECT_ID(N'[dbo].[HCMPOSITIONWORKERASSIGNMENT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[HCMPOSITIONWORKERASSIGNMENT]
GO
CREATE VIEW [dbo].HCMPOSITIONWORKERASSIGNMENT AS
(
  SELECT
    [POSITION],
    [VALIDFROM],
    [VALIDFROMTZID],
    [VALIDTO],
    [VALIDTOTZID],
    [ASSIGNMENTREASONCODE],
    [WORKER],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].HCMPOSITIONWORKERASSIGNMENT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view HCMWORKER ..'
GO
IF OBJECT_ID(N'[dbo].[HCMWORKER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[HCMWORKER]
GO
CREATE VIEW [dbo].HCMWORKER AS
(
  SELECT
    [PERSON],
    [PERSONNELNUMBER],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID],
    CONVERT([int], 0) AS 'RETAILSTAFFMEMBER'
  FROM [ax].HCMWORKER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INFOCODEVIEW ..'
GO
IF OBJECT_ID(N'[dbo].[INFOCODEVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INFOCODEVIEW]
GO
CREATE VIEW [dbo].INFOCODEVIEW AS
(
  SELECT
        icv.[RECID],
        icv.[INFOCODEID],
        icv.[PRIORITY],
        icv.[MINIMUMVALUE],
        icv.[MAXIMUMVALUE],
        icv.[MINIMUMLENGTH],
        icv.[MAXIMUMLENGTH],
        icv.[INPUTREQUIRED],
        icv.[ONCEPERTRANSACTION],
        icv.[PRINTPROMPTONRECEIPT],
        icv.[PRINTINPUTONRECEIPT],
        icv.[PRINTINPUTNAMEONRECEIPT],
        icv.[LINKEDINFOCODEID],
        icv.[RANDOMFACTOR],
        icv.[INPUTTYPE],
        icv.[DATAAREAID],
        icv.[GROUPID],
        icv.[RETAILUSEINFOCODE],
        0 AS 'ADDITIONALCHECK'
    FROM [crt].[INFOCODEVIEW] icv
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INFOCODESPECIFICVIEW ..'
GO
IF OBJECT_ID(N'[dbo].[INFOCODESPECIFICVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INFOCODESPECIFICVIEW]
GO
CREATE VIEW [dbo].INFOCODESPECIFICVIEW AS
(
  SELECT
        ic.[RECID],
        ic.[INFOCODEID],
        ic.[DATAAREAID],
        ic.[PRIORITY],
        ic.[ONCEPERTRANSACTION],
        ic.[PRINTPROMPTONRECEIPT],
        ic.[PRINTINPUTONRECEIPT],
        ic.[PRINTINPUTNAMEONRECEIPT],
        ic.[INPUTTYPE],
        ic.[MINIMUMVALUE],
        ic.[MAXIMUMVALUE],
        ic.[MINIMUMLENGTH],
        ic.[MAXIMUMLENGTH],
        ic.[INPUTREQUIRED],
        ic.[LINKEDINFOCODEID],
        ic.[RANDOMFACTOR],
        ic.[INPUTREQUIREDSPECIFIC],
        ic.[WHENREQUIRED],
        ic.[SEQUENCE],
        0 AS 'ADDITIONALCHECK',
        ic.[REFRELATION],
        ic.[REFRELATION2],
        ic.[REFRELATION3],
        ic.[REFTABLEID]
     FROM [crt].[INFOCODESPECIFICVIEW] ic
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table INVENTBATCH ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTBATCH]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTBATCH](
    [INVENTBATCHID] [nvarchar](20) NOT NULL,
    [EXPDATE] [datetime] NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [PRODDATE] [datetime] NOT NULL,
    [DESCRIPTION] [ntext] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NOT NULL,
 CONSTRAINT [I_752ITEMBATCHIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [INVENTBATCHID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTBAT__INVEN__2AC04CAA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTBATCH] ADD  CONSTRAINT [DF__INVENTBAT__INVEN__2AC04CAA] DEFAULT ('') FOR [INVENTBATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTBAT__EXPDA__2BB470E3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTBATCH] ADD CONSTRAINT [DF__INVENTBAT__EXPDA__2BB470E3] DEFAULT ('1900-01-01 00:00:00.000') FOR [EXPDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTBAT__ITEMI__2CA8951C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTBATCH] ADD CONSTRAINT [DF__INVENTBAT__ITEMI__2CA8951C] DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTBAT__PRODD__2D9CB955]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTBATCH] ADD CONSTRAINT [DF__INVENTBAT__PRODD__2D9CB955] DEFAULT ('1900-01-01 00:00:00.000') FOR [PRODDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTBAT__DESCR__2E90DD8E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTBATCH] ADD CONSTRAINT [DF__INVENTBAT__DESCR__2E90DD8E] DEFAULT (NULL) FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTBAT__DATAA__2F8501C7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTBATCH] ADD CONSTRAINT [DF__INVENTBAT__DATAA__2F8501C7] DEFAULT ('DAT') FOR [DATAAREAID]
END


-------------------------------------------------------------------------------
PRINT 'Creating view INVENTDIM ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTDIM]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTDIM]
GO
CREATE VIEW [dbo].INVENTDIM AS
(
  SELECT
    [INVENTDIMID],
    [INVENTBATCHID],
    [WMSLOCATIONID],
    [WMSPALLETID],
    [INVENTSERIALID],
    [INVENTLOCATIONID],
    [CONFIGID],
    [INVENTSIZEID],
    [INVENTCOLORID],
    [INVENTSTYLEID],
    [INVENTSITEID],
    [DATAAREAID],
    [RECID]
  FROM [ax].INVENTDIM
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INVENTDIMCOMBINATION ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTDIMCOMBINATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTDIMCOMBINATION]
GO
CREATE VIEW [dbo].INVENTDIMCOMBINATION AS
(
  SELECT
    [ITEMID],
    [INVENTDIMID],
    [DISTINCTPRODUCTVARIANT],
    [CREATEDDATETIME],
    [DATAAREAID],
    [RECID],
    [RETAILVARIANTID]
  FROM [ax].INVENTDIMCOMBINATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table INVENTDIMGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTDIMGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTDIMGROUP](
    [DIMGROUPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_701DIMGROUPIDIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [DIMGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__DIMGR__40712D55]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMGROUP] ADD  CONSTRAINT [DF__INVENTDIM__DIMGR__40712D55]  DEFAULT ('') FOR [DIMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIMG__NAME__4165518E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMGROUP] ADD  CONSTRAINT [DF__INVENTDIMG__NAME__4165518E]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__DATAA__425975C7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMGROUP] ADD  CONSTRAINT [DF__INVENTDIM__DATAA__425975C7]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table INVENTDIMSETUPGRID ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTDIMSETUPGRID]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTDIMSETUPGRID](
    [DIMFIELDID] [int] NOT NULL,
    [SHOWGRIDINVENTCOUNTING] [int] NULL,
    [SHOWGRIDINVENTLOSSPROFIT] [int] NULL,
    [SHOWGRIDINVENTTRANSFER] [int] NULL,
    [SHOWGRIDPRODLINE] [int] NULL,
    [SHOWGRIDPRODUCTION] [int] NULL,
    [SHOWGRIDINVENTTRANSACTION] [int] NULL,
    [SHOWGRIDPURCHLINE] [int] NULL,
    [SHOWGRIDSALESLINE] [int] NULL,
    [SHOWGRIDWMSRECEPTION] [int] NULL,
    [SHOWGRIDPRODJOURNALBOM] [int] NULL,
    [SALESFORMLETTERINVOICE] [int] NULL,
    [SALESFORMLETTERPACKINGSLIP] [int] NULL,
    [SALESFORMLETTERPICKINGLIST] [int] NULL,
    [SALESFORMLETTERQUOTATION] [int] NULL,
    [SALESFORMLETTERCONFIRM] [int] NULL,
    [PURCHFORMLETTERINVOICE] [int] NULL,
    [PURCHFORMLETTERRECEIPTSLIST] [int] NULL,
    [PURCHFORMLETTERPACKINGSLIP] [int] NULL,
    [PURCHFORMLETTERORDER] [int] NULL,
    [SHOWGRIDWMSSHIPMENTBASIS] [int] NULL,
    [SHOWGRIDPRODJOURNALPROD] [int] NULL,
    [SHOWGRIDWMSRECEPTIONPROD] [int] NULL,
    [SHOWGRIDWMSPICKINGLINES] [int] NULL,
    [SHOWGRIDINVENTQUARANTINEORDER] [int] NULL,
    [SHOWGRIDPROJECT] [int] NULL,
    [SHOWGRIDINVENTTRANS] [int] NULL,
    [SHOWGRIDASSET] [int] NULL,
    [SHOWGRIDSMMQUOTATIONLINE] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_758DIMFIELDIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [DIMFIELDID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__DIMFI__2F119729]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__DIMFI__2F119729]  DEFAULT ((0)) FOR [DIMFIELDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__3005BB62]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__3005BB62]  DEFAULT ((0)) FOR [SHOWGRIDINVENTCOUNTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__30F9DF9B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__30F9DF9B]  DEFAULT ((0)) FOR [SHOWGRIDINVENTLOSSPROFIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__31EE03D4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__31EE03D4]  DEFAULT ((0)) FOR [SHOWGRIDINVENTTRANSFER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__32E2280D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__32E2280D]  DEFAULT ((0)) FOR [SHOWGRIDPRODLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__33D64C46]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__33D64C46]  DEFAULT ((0)) FOR [SHOWGRIDPRODUCTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__34CA707F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__34CA707F]  DEFAULT ((0)) FOR [SHOWGRIDINVENTTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__35BE94B8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__35BE94B8]  DEFAULT ((0)) FOR [SHOWGRIDPURCHLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__36B2B8F1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__36B2B8F1]  DEFAULT ((0)) FOR [SHOWGRIDSALESLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__37A6DD2A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__37A6DD2A]  DEFAULT ((0)) FOR [SHOWGRIDWMSRECEPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__389B0163]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__389B0163]  DEFAULT ((0)) FOR [SHOWGRIDPRODJOURNALBOM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SALES__398F259C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SALES__398F259C]  DEFAULT ((0)) FOR [SALESFORMLETTERINVOICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SALES__3A8349D5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SALES__3A8349D5]  DEFAULT ((0)) FOR [SALESFORMLETTERPACKINGSLIP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SALES__3B776E0E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SALES__3B776E0E]  DEFAULT ((0)) FOR [SALESFORMLETTERPICKINGLIST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SALES__3C6B9247]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SALES__3C6B9247]  DEFAULT ((0)) FOR [SALESFORMLETTERQUOTATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SALES__3D5FB680]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SALES__3D5FB680]  DEFAULT ((0)) FOR [SALESFORMLETTERCONFIRM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__PURCH__3E53DAB9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__PURCH__3E53DAB9]  DEFAULT ((0)) FOR [PURCHFORMLETTERINVOICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__PURCH__3F47FEF2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__PURCH__3F47FEF2]  DEFAULT ((0)) FOR [PURCHFORMLETTERRECEIPTSLIST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__PURCH__403C232B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__PURCH__403C232B]  DEFAULT ((0)) FOR [PURCHFORMLETTERPACKINGSLIP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__PURCH__41304764]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__PURCH__41304764]  DEFAULT ((0)) FOR [PURCHFORMLETTERORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__42246B9D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__42246B9D]  DEFAULT ((0)) FOR [SHOWGRIDWMSSHIPMENTBASIS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__43188FD6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__43188FD6]  DEFAULT ((0)) FOR [SHOWGRIDPRODJOURNALPROD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__440CB40F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__440CB40F]  DEFAULT ((0)) FOR [SHOWGRIDWMSRECEPTIONPROD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__4500D848]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__4500D848]  DEFAULT ((0)) FOR [SHOWGRIDWMSPICKINGLINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__45F4FC81]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__45F4FC81]  DEFAULT ((0)) FOR [SHOWGRIDINVENTQUARANTINEORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__46E920BA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__46E920BA]  DEFAULT ((0)) FOR [SHOWGRIDPROJECT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__47DD44F3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__47DD44F3]  DEFAULT ((0)) FOR [SHOWGRIDINVENTTRANS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__48D1692C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__48D1692C]  DEFAULT ((0)) FOR [SHOWGRIDASSET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__SHOWG__49C58D65]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__SHOWG__49C58D65]  DEFAULT ((0)) FOR [SHOWGRIDSMMQUOTATIONLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTDIM__DATAA__4AB9B19E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTDIMSETUPGRID] ADD  CONSTRAINT [DF__INVENTDIM__DATAA__4AB9B19E]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view INVENTITEMBARCODE ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTITEMBARCODE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTITEMBARCODE]
GO
CREATE VIEW [dbo].INVENTITEMBARCODE AS
(
  SELECT
    [ITEMBARCODE],
    [ITEMID],
    [INVENTDIMID],
    [BARCODESETUPID],
    [USEFORPRINTING],
    [USEFORINPUT],
    [DESCRIPTION],
    [QTY],
    [UNITID],
    [RETAILVARIANTID] AS 'RBOVARIANTID',
    [RETAILSHOWFORITEM] AS 'RBOSHOWFORITEM',
    [BLOCKED],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATETIME',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID]
  FROM [ax].INVENTITEMBARCODE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INVENTITEMGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTITEMGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTITEMGROUP]
GO
CREATE VIEW [dbo].INVENTITEMGROUP AS
(
  SELECT
    [ITEMGROUPID],
    [NAME],
    [DATAAREAID],
    [RECID]
  FROM [ax].INVENTITEMGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INVENTITEMGROUPITEM ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTITEMGROUPITEM]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTITEMGROUPITEM]
GO
CREATE VIEW [dbo].INVENTITEMGROUPITEM AS
(
  SELECT
    [ITEMID],
    [ITEMDATAAREAID],
    [ITEMGROUPID],
    [ITEMGROUPDATAAREAID],
    [RECID]
  FROM [ax].INVENTITEMGROUPITEM
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INVENTITEMGTIN ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTITEMGTIN]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTITEMGTIN]
GO
CREATE VIEW [dbo].INVENTITEMGTIN AS
(
  SELECT
    [ITEMID],
    [INVENTDIMID],
    [DESCRIPTION],
    [GLOBALTRADEITEMNUMBER],
    [GTINSETUP],
    [UNITID],
    [DATAAREAID],
    [RECID]
  FROM [ax].INVENTITEMGTIN
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table INVENTITEMLOCATION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTITEMLOCATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTITEMLOCATION](
    [ITEMID] [nvarchar](20) NOT NULL,
    [COUNTGROUPID] [nvarchar](10) NULL,
    [WMSSTOREZONEID] [nvarchar](10) NULL,
    [WMSPICKINGLOCATION] [nvarchar](10) NULL,
    [COUNTINGSTARTED] [int] NULL,
    [COUNTINGJOURNALID] [nvarchar](10) NULL,
    [WMSLOCATIONIDDEFAULTISSUE] [nvarchar](10) NULL,
    [WMSLOCATIONIDDEFAULTRECEIPT] [nvarchar](10) NULL,
    [INVENTDIMID] [nvarchar](20) NOT NULL,
    [USEWMSORDER] [int] NULL,
    [PICKINGLOCATIONREFILLMIN] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_659ITEMDIMIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [INVENTDIMID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__ITEMI__3751D76F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__ITEMI__3751D76F]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__COUNT__3845FBA8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__COUNT__3845FBA8]  DEFAULT ('') FOR [COUNTGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__WMSST__393A1FE1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__WMSST__393A1FE1]  DEFAULT ('') FOR [WMSSTOREZONEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__WMSPI__3A2E441A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__WMSPI__3A2E441A]  DEFAULT ('') FOR [WMSPICKINGLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__COUNT__3B226853]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__COUNT__3B226853]  DEFAULT ((0)) FOR [COUNTINGSTARTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__COUNT__3C168C8C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__COUNT__3C168C8C]  DEFAULT ('') FOR [COUNTINGJOURNALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__WMSLO__3D0AB0C5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__WMSLO__3D0AB0C5]  DEFAULT ('') FOR [WMSLOCATIONIDDEFAULTISSUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__WMSLO__3DFED4FE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__WMSLO__3DFED4FE]  DEFAULT ('') FOR [WMSLOCATIONIDDEFAULTRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__INVEN__3EF2F937]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__INVEN__3EF2F937]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__USEWM__3FE71D70]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__USEWM__3FE71D70]  DEFAULT ((0)) FOR [USEWMSORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__PICKI__40DB41A9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__PICKI__40DB41A9]  DEFAULT ((0)) FOR [PICKINGLOCATIONREFILLMIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTITE__DATAA__41CF65E2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTITEMLOCATION] ADD  CONSTRAINT [DF__INVENTITE__DATAA__41CF65E2]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view INVENTLOCATION ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTLOCATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTLOCATION]
GO
CREATE VIEW [dbo].INVENTLOCATION AS
(
  SELECT
    [INVENTLOCATIONID],
    [NAME],
    [INVENTLOCATIONTYPE],
    [INVENTSITEID],
    [DATAAREAID],
    [RECID]
  FROM [ax].INVENTLOCATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INVENTLOCATIONLOGISTICSLOCATION ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTLOCATIONLOGISTICSLOCATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTLOCATIONLOGISTICSLOCATION]
GO
CREATE VIEW [dbo].INVENTLOCATIONLOGISTICSLOCATION AS
(
  SELECT
    [INVENTLOCATION],
    [LOCATION],
    [ISPRIMARY],
    [RECID]
  FROM [ax].INVENTLOCATIONLOGISTICSLOCATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table INVENTMODELGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTMODELGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTMODELGROUP](
    [MODELGROUPID] [nvarchar](10) NOT NULL,
    [NEGATIVEFINANCIAL] [int] NULL,
    [NEGATIVEPHYSICAL] [int] NULL,
    [NAME] [nvarchar](30) NULL,
    [INVENTMODEL] [int] NULL,
    [MANDATORYWMSORDER] [int] NULL,
    [MANDATORYPICK] [int] NULL,
    [STANDARDCOST] [int] NULL,
    [POSTONHANDPHYSICAL] [int] NULL,
    [POSTONHANDFINANCIAL] [int] NULL,
    [INCLPHYSICALVALUEINCOST] [int] NULL,
    [QUARANTINECONTROL] [int] NULL,
    [POSTPHYSICALREVENUE] [int] NULL,
    [RESERVEREVERSED] [int] NULL,
    [RESERVEBYDATE] [int] NULL,
    [DEL_POSTPHYSICALPURCHASE] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_709GROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [MODELGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__MODEL__60DDFCE7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__MODEL__60DDFCE7]  DEFAULT ('') FOR [MODELGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__NEGAT__61D22120]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__NEGAT__61D22120]  DEFAULT ((0)) FOR [NEGATIVEFINANCIAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__NEGAT__62C64559]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__NEGAT__62C64559]  DEFAULT ((0)) FOR [NEGATIVEPHYSICAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMODE__NAME__63BA6992]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMODE__NAME__63BA6992]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__INVEN__64AE8DCB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__INVEN__64AE8DCB]  DEFAULT ((0)) FOR [INVENTMODEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__MANDA__65A2B204]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__MANDA__65A2B204]  DEFAULT ((0)) FOR [MANDATORYWMSORDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__MANDA__6696D63D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__MANDA__6696D63D]  DEFAULT ((0)) FOR [MANDATORYPICK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__STAND__678AFA76]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__STAND__678AFA76]  DEFAULT ((0)) FOR [STANDARDCOST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__POSTO__687F1EAF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__POSTO__687F1EAF]  DEFAULT ((0)) FOR [POSTONHANDPHYSICAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__POSTO__697342E8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__POSTO__697342E8]  DEFAULT ((0)) FOR [POSTONHANDFINANCIAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__INCLP__6A676721]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__INCLP__6A676721]  DEFAULT ((0)) FOR [INCLPHYSICALVALUEINCOST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__QUARA__6B5B8B5A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__QUARA__6B5B8B5A]  DEFAULT ((0)) FOR [QUARANTINECONTROL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__POSTP__6C4FAF93]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__POSTP__6C4FAF93]  DEFAULT ((0)) FOR [POSTPHYSICALREVENUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__RESER__6D43D3CC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__RESER__6D43D3CC]  DEFAULT ((0)) FOR [RESERVEREVERSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__RESER__6E37F805]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__RESER__6E37F805]  DEFAULT ((0)) FOR [RESERVEBYDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__DEL_P__6F2C1C3E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__DEL_P__6F2C1C3E]  DEFAULT ((0)) FOR [DEL_POSTPHYSICALPURCHASE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTMOD__DATAA__70204077]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTMODELGROUP] ADD  CONSTRAINT [DF__INVENTMOD__DATAA__70204077]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table INVENTNUMGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTNUMGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTNUMGROUP](
    [NUMGROUPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [SALESACTIVATION] [int] NULL,
    [PURCHACTIVATION] [int] NULL,
    [INVENTACTIVATION] [int] NULL,
    [PRODACTIVATION] [int] NULL,
    [NUMBERSEQUENCEID] [nvarchar](10) NULL,
    [PHYSICALUPDATE] [int] NULL,
    [ONLYINVENTTRANSACTION] [int] NULL,
    [INCLNUMBER] [int] NULL,
    [INCLINVENTTRANSID] [int] NULL,
    [INCLREFERENCEID] [int] NULL,
    [PERQTY] [numeric](28, 12) NULL,
    [INCLEXPECTEDDATE] [int] NULL,
    [MANUALALLOCATION] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_159NUMGROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [NUMGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__NUMGR__3B6BB5BF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__NUMGR__3B6BB5BF]  DEFAULT ('') FOR [NUMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUMG__NAME__3C5FD9F8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUMG__NAME__3C5FD9F8]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__SALES__3D53FE31]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__SALES__3D53FE31]  DEFAULT ((0)) FOR [SALESACTIVATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__PURCH__3E48226A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__PURCH__3E48226A]  DEFAULT ((0)) FOR [PURCHACTIVATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__INVEN__3F3C46A3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__INVEN__3F3C46A3]  DEFAULT ((0)) FOR [INVENTACTIVATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__PRODA__40306ADC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__PRODA__40306ADC]  DEFAULT ((0)) FOR [PRODACTIVATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__NUMBE__41248F15]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__NUMBE__41248F15]  DEFAULT ('') FOR [NUMBERSEQUENCEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__PHYSI__4218B34E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__PHYSI__4218B34E]  DEFAULT ((0)) FOR [PHYSICALUPDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__ONLYI__430CD787]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__ONLYI__430CD787]  DEFAULT ((0)) FOR [ONLYINVENTTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__INCLN__4400FBC0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__INCLN__4400FBC0]  DEFAULT ((0)) FOR [INCLNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__INCLI__44F51FF9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__INCLI__44F51FF9]  DEFAULT ((0)) FOR [INCLINVENTTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__INCLR__45E94432]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__INCLR__45E94432]  DEFAULT ((0)) FOR [INCLREFERENCEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__PERQT__46DD686B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__PERQT__46DD686B]  DEFAULT ((0)) FOR [PERQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__INCLE__47D18CA4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__INCLE__47D18CA4]  DEFAULT ((0)) FOR [INCLEXPECTEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__MANUA__48C5B0DD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__MANUA__48C5B0DD]  DEFAULT ((0)) FOR [MANUALALLOCATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTNUM__DATAA__49B9D516]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTNUMGROUP] ADD  CONSTRAINT [DF__INVENTNUM__DATAA__49B9D516]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table INVENTPRODUCTGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTPRODUCTGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTPRODUCTGROUP](
    [NAME] [nvarchar](30) NULL,
    [PRODUCTGROUPTYPE] [int] NOT NULL,
    [PRODUCTGROUPID] [nvarchar](20) NOT NULL,
    [PACKEDQUERY] [image] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_935PRODUCTGROUPTYPEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PRODUCTGROUPID] ASC,
    [PRODUCTGROUPTYPE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPROD__NAME__68D4246A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUP] ADD  CONSTRAINT [DF__INVENTPROD__NAME__68D4246A]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPRO__PRODU__69C848A3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUP] ADD  CONSTRAINT [DF__INVENTPRO__PRODU__69C848A3]  DEFAULT ((0)) FOR [PRODUCTGROUPTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPRO__PRODU__6ABC6CDC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUP] ADD  CONSTRAINT [DF__INVENTPRO__PRODU__6ABC6CDC]  DEFAULT ('') FOR [PRODUCTGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPRO__PACKE__6BB09115]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUP] ADD  CONSTRAINT [DF__INVENTPRO__PACKE__6BB09115]  DEFAULT (NULL) FOR [PACKEDQUERY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPRO__DATAA__6CA4B54E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUP] ADD  CONSTRAINT [DF__INVENTPRO__DATAA__6CA4B54E]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table INVENTPRODUCTGROUPITEM ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTPRODUCTGROUPITEM]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTPRODUCTGROUPITEM](
    [ITEMID] [nvarchar](20) NOT NULL,
    [PRODUCTGROUPID] [nvarchar](20) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_939PRODUCTGROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PRODUCTGROUPID] ASC,
    [ITEMID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPRO__ITEMI__762E1F88]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUPITEM] ADD  CONSTRAINT [DF__INVENTPRO__ITEMI__762E1F88]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPRO__PRODU__772243C1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUPITEM] ADD  CONSTRAINT [DF__INVENTPRO__PRODU__772243C1]  DEFAULT ('') FOR [PRODUCTGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTPRO__DATAA__781667FA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTPRODUCTGROUPITEM] ADD  CONSTRAINT [DF__INVENTPRO__DATAA__781667FA]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view INVENTSERIAL ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTSERIAL]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTSERIAL]
GO
CREATE VIEW [dbo].INVENTSERIAL AS
(
  SELECT
    [INVENTSERIALID],
    [ITEMID],
    [PRODDATE],
    [DATAAREAID],
    [RECID],
    [RFIDTAGID],
    [DESCRIPTION]
  FROM [ax].INVENTSERIAL
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view INVENTTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTTABLE]
GO
CREATE VIEW [dbo].INVENTTABLE AS
(
  SELECT
    [ITEMID],
    CONVERT([nvarchar](60), '') AS 'ITEMNAME',
    [ITEMTYPE],
    [PURCHMODEL],
    [HEIGHT],
    [WIDTH],
    [SALESMODEL],
    [REQGROUPID],
    [PRIMARYVENDORID],
    [NETWEIGHT],
    [DEPTH],
    [UNITVOLUME],
    [DENSITY],
    CONVERT([nvarchar](10), '') AS 'DIMENSION',
    CONVERT([nvarchar](10), '') AS 'DIMENSION2_',
    CONVERT([nvarchar](10), '') AS 'DIMENSION3_',
    [COSTMODEL],
    [USEALTITEMID],
    [ALTITEMID],
    CONVERT([int], 0) AS 'BOMMANUALCONSUMP',
    CONVERT([int], 0) AS 'BOMMANUALRECEIPT',
    CONVERT([int], 0) AS 'STOPEXPLODE',
    [BATCHNUMGROUPID],
    [PRODPOOLID],
    [PROPERTYID],
    [ABCTIEUP],
    [ABCREVENUE],
    [ABCVALUE],
    [ABCCONTRIBUTIONMARGIN],
    [SALESPERCENTMARKUP],
    [SALESCONTRIBUTIONRATIO],
    [SALESPRICEMODELBASIC],
    CONVERT([numeric](28, 12), 0) AS 'MINAVERAGESETTLE',
    [NAMEALIAS],
    [PRODGROUPID],
    [PROJCATEGORYID],
    [GROSSDEPTH],
    [GROSSWIDTH],
    [GROSSHEIGHT],
    [SORTCODE],
    [SERIALNUMGROUPID],
    CONVERT([nvarchar](10), '') AS 'DIMGROUPID',
    [ITEMBUYERGROUPID],
    [WMSPICKINGQTYTIME],
    [TARAWEIGHT],
    CONVERT([int], 0) AS 'ITEMDIMCOMBINATIONAUTOCREATE',
    [ITEMDIMCOSTPRICE],
    CONVERT([nvarchar](20), '') AS 'ITEMIDCOMPANY',
    [PBAITEMCONFIGURABLE],
    [PBAINVENTITEMGROUPID],
    [PRODUCT],
    [DATAAREAID],
    [RECID],
    [TAXFISCALCLASSIFICATION_BR],
    [EXCEPTIONCODE_BR],
    [TAXSERVICECODE_BR],
    [INVENTPRODUCTTYPE_BR],
    [TAXATIONORIGIN_BR],
    [APPROXTAXVALUE_BR]
  FROM [ax].INVENTTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table INVENTTABLECOMPANY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTTABLECOMPANY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTTABLECOMPANY](
    [ITEMID] [nvarchar](20) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_1665ITEMIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTAB__ITEMI__09ABD3A7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTABLECOMPANY] ADD  CONSTRAINT [DF__INVENTTAB__ITEMI__09ABD3A7]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTABL__NAME__0A9FF7E0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTABLECOMPANY] ADD  CONSTRAINT [DF__INVENTTABL__NAME__0A9FF7E0]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTAB__DATAA__0B941C19]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTABLECOMPANY] ADD  CONSTRAINT [DF__INVENTTAB__DATAA__0B941C19]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view INVENTTABLEMODULE ..'
GO
IF OBJECT_ID(N'[dbo].[INVENTTABLEMODULE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[INVENTTABLEMODULE]
GO
CREATE VIEW [dbo].INVENTTABLEMODULE AS
(
  SELECT
    [ITEMID],
    [MODULETYPE],
    [UNITID],
    [PRICE],
    [PRICEUNIT],
    [MARKUP],
    CONVERT([numeric](28, 12), 0) AS 'QUANTITY',
    CONVERT([numeric](28, 12), 0) AS 'LOWESTQTY',
    CONVERT([numeric](28, 12), 0) AS 'HIGHESTQTY',
    CONVERT([int], 0) AS 'BLOCKED',
    CONVERT([int], 0) AS 'DELIVERYTIME',
    CONVERT([nvarchar](10), '') AS 'INVENTLOCATIONID',
    CONVERT([int], 0) AS 'MANDATORYINVENTLOCATION',
    CONVERT([numeric](28, 12), 0) AS 'STANDARDQTY',
    [PRICEDATE],
    [PRICEQTY],
    [ALLOCATEMARKUP],
    CONVERT([int], 0) AS 'CALENDARDAYS',
    [INTERCOMPANYBLOCKED],
    [DATAAREAID],
    [RECID],
    [TAXITEMGROUPID],
    [LINEDISC],
    [MULTILINEDISC],
    [ENDDISC],
    [MARKUPGROUPID],
    [OVERDELIVERYPCT],
    [UNDERDELIVERYPCT],
    [SUPPITEMGROUPID],
    [MAXIMUMRETAILPRICE_IN]
  FROM [ax].INVENTTABLEMODULE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table INVENTTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INVENTTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[INVENTTRANS](
    [ITEMID] [nvarchar](20) NULL,
    [STATUSISSUE] [int] NULL,
    [DATEPHYSICAL] [datetime] NULL,
    [QTY] [numeric](28, 12) NULL,
    [COSTAMOUNTPOSTED] [numeric](28, 12) NULL,
    [CURRENCYCODE] [nvarchar](3) NULL,
    [TRANSTYPE] [int] NULL,
    [TRANSREFID] [nvarchar](20) NULL,
    [INVOICEID] [nvarchar](20) NULL,
    [VOUCHER] [nvarchar](20) NULL,
    [DATEEXPECTED] [datetime] NULL,
    [DATEFINANCIAL] [datetime] NULL,
    [COSTAMOUNTPHYSICAL] [numeric](28, 12) NULL,
    [INVENTTRANSID] [nvarchar](20) NULL,
    [STATUSRECEIPT] [int] NULL,
    [PACKINGSLIPRETURNED] [int] NULL,
    [INVOICERETURNED] [int] NULL,
    [PACKINGSLIPID] [nvarchar](20) NULL,
    [VOUCHERPHYSICAL] [nvarchar](20) NULL,
    [COSTAMOUNTADJUSTMENT] [numeric](28, 12) NULL,
    [QTYSETTLED] [numeric](28, 12) NULL,
    [COSTAMOUNTSETTLED] [numeric](28, 12) NULL,
    [VALUEOPEN] [int] NULL,
    [DIRECTION] [int] NULL,
    [DATESTATUS] [datetime] NULL,
    [COSTAMOUNTSTD] [numeric](28, 12) NULL,
    [DATECLOSED] [datetime] NULL,
    [INVENTTRANSIDFATHER] [nvarchar](20) NULL,
    [COSTAMOUNTOPERATIONS] [numeric](28, 12) NULL,
    [INVENTTRANSIDRETURN] [nvarchar](20) NULL,
    [PROJID] [nvarchar](10) NULL,
    [PROJCATEGORYID] [nvarchar](10) NULL,
    [INVENTDIMID] [nvarchar](20) NULL,
    [INVENTDIMFIXED] [int] NULL,
    [DATEINVENT] [datetime] NULL,
    [CUSTVENDAC] [nvarchar](10) NULL,
    [TRANSCHILDREFID] [nvarchar](20) NULL,
    [TRANSCHILDTYPE] [int] NULL,
    [TIMEEXPECTED] [int] NULL,
    [REVENUEAMOUNTPHYSICAL] [numeric](28, 12) NULL,
    [ASSETID] [nvarchar](10) NULL,
    [PROJADJUSTREFID] [nvarchar](20) NULL,
    [ASSETBOOKID] [nvarchar](10) NULL,
    [INVENTREFTRANSID] [nvarchar](20) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__ITEMI__37F02A96]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__ITEMI__37F02A96]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__STATU__38E44ECF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__STATU__38E44ECF]  DEFAULT ((0)) FOR [STATUSISSUE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DATEP__39D87308]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DATEP__39D87308]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DATEPHYSICAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRANS__QTY__3ACC9741]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRANS__QTY__3ACC9741]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__COSTA__3BC0BB7A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__COSTA__3BC0BB7A]  DEFAULT ((0)) FOR [COSTAMOUNTPOSTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__CURRE__3CB4DFB3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__CURRE__3CB4DFB3]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__TRANS__3DA903EC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__TRANS__3DA903EC]  DEFAULT ((0)) FOR [TRANSTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__TRANS__3E9D2825]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__TRANS__3E9D2825]  DEFAULT ('') FOR [TRANSREFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVOI__3F914C5E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVOI__3F914C5E]  DEFAULT ('') FOR [INVOICEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__VOUCH__40857097]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__VOUCH__40857097]  DEFAULT ('') FOR [VOUCHER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DATEE__417994D0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DATEE__417994D0]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DATEEXPECTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DATEF__426DB909]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DATEF__426DB909]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DATEFINANCIAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__COSTA__4361DD42]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__COSTA__4361DD42]  DEFAULT ((0)) FOR [COSTAMOUNTPHYSICAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVEN__4456017B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVEN__4456017B]  DEFAULT ('') FOR [INVENTTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__STATU__454A25B4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__STATU__454A25B4]  DEFAULT ((0)) FOR [STATUSRECEIPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__PACKI__463E49ED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__PACKI__463E49ED]  DEFAULT ((0)) FOR [PACKINGSLIPRETURNED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVOI__47326E26]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVOI__47326E26]  DEFAULT ((0)) FOR [INVOICERETURNED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__PACKI__4826925F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__PACKI__4826925F]  DEFAULT ('') FOR [PACKINGSLIPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__VOUCH__491AB698]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__VOUCH__491AB698]  DEFAULT ('') FOR [VOUCHERPHYSICAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__COSTA__4A0EDAD1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__COSTA__4A0EDAD1]  DEFAULT ((0)) FOR [COSTAMOUNTADJUSTMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__QTYSE__4B02FF0A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__QTYSE__4B02FF0A]  DEFAULT ((0)) FOR [QTYSETTLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__COSTA__4BF72343]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__COSTA__4BF72343]  DEFAULT ((0)) FOR [COSTAMOUNTSETTLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__VALUE__4CEB477C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__VALUE__4CEB477C]  DEFAULT ((0)) FOR [VALUEOPEN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DIREC__4DDF6BB5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DIREC__4DDF6BB5]  DEFAULT ((0)) FOR [DIRECTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DATES__4ED38FEE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DATES__4ED38FEE]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DATESTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__COSTA__4FC7B427]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__COSTA__4FC7B427]  DEFAULT ((0)) FOR [COSTAMOUNTSTD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DATEC__50BBD860]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DATEC__50BBD860]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DATECLOSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVEN__51AFFC99]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVEN__51AFFC99]  DEFAULT ('') FOR [INVENTTRANSIDFATHER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__COSTA__52A420D2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__COSTA__52A420D2]  DEFAULT ((0)) FOR [COSTAMOUNTOPERATIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVEN__5398450B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVEN__5398450B]  DEFAULT ('') FOR [INVENTTRANSIDRETURN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__PROJI__548C6944]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__PROJI__548C6944]  DEFAULT ('') FOR [PROJID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__PROJC__55808D7D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__PROJC__55808D7D]  DEFAULT ('') FOR [PROJCATEGORYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVEN__5674B1B6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVEN__5674B1B6]  DEFAULT ('') FOR [INVENTDIMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVEN__5768D5EF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVEN__5768D5EF]  DEFAULT ((0)) FOR [INVENTDIMFIXED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DATEI__585CFA28]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DATEI__585CFA28]  DEFAULT ('1900-01-01 00:00:00.000') FOR [DATEINVENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__CUSTV__59511E61]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__CUSTV__59511E61]  DEFAULT ('') FOR [CUSTVENDAC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__TRANS__5A45429A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__TRANS__5A45429A]  DEFAULT ('') FOR [TRANSCHILDREFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__TRANS__5B3966D3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__TRANS__5B3966D3]  DEFAULT ((0)) FOR [TRANSCHILDTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__TIMEE__5C2D8B0C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__TIMEE__5C2D8B0C]  DEFAULT ((0)) FOR [TIMEEXPECTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__REVEN__5D21AF45]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__REVEN__5D21AF45]  DEFAULT ((0)) FOR [REVENUEAMOUNTPHYSICAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__ASSET__5E15D37E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__ASSET__5E15D37E]  DEFAULT ('') FOR [ASSETID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__PROJA__5F09F7B7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__PROJA__5F09F7B7]  DEFAULT ('') FOR [PROJADJUSTREFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__ASSET__5FFE1BF0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__ASSET__5FFE1BF0]  DEFAULT ('') FOR [ASSETBOOKID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__INVEN__60F24029]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__INVEN__60F24029]  DEFAULT ('') FOR [INVENTREFTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__INVENTTRA__DATAA__61E66462]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[INVENTTRANS] ADD  CONSTRAINT [DF__INVENTTRA__DATAA__61E66462]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view JMGIPCACTIVITY ..'
GO
IF OBJECT_ID(N'[dbo].[JMGIPCACTIVITY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[JMGIPCACTIVITY]
GO
CREATE VIEW [dbo].JMGIPCACTIVITY AS
(
  SELECT
    [ACTIVITY],
    [CATEGORY],
    [JOBID],
    [SIGNIN],
    [BREAKDROP],
    [SIGNINOUT],
    [TYPE],
    [DATAAREAID],
    [RECID]
  FROM [ax].JMGIPCACTIVITY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LANGUAGETABLE ..'
GO
IF OBJECT_ID(N'[dbo].[LANGUAGETABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LANGUAGETABLE]
GO
CREATE VIEW [dbo].LANGUAGETABLE AS
(
  SELECT
    [LANGUAGEID],
    [LABELFILE],
    [USERDEFINEDLANGUAGE],
    [RECID]
  FROM [ax].LANGUAGETABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table LANGUAGETXT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LANGUAGETXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[LANGUAGETXT](
    [TXTTABLEID] [int] NOT NULL,
    [TXTRECID] [bigint] NOT NULL,
    [LANGUAGEID] [nvarchar](7) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
    [TXT] [ntext] NULL,
 CONSTRAINT [I_185TXTIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [TXTTABLEID] ASC,
    [TXTRECID] ASC,
    [LANGUAGEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LANGUAGET__TXTTA__6C63F2D5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LANGUAGETXT] ADD  CONSTRAINT [DF__LANGUAGET__TXTTA__6C63F2D5]  DEFAULT ((0)) FOR [TXTTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LANGUAGET__TXTRE__6D58170E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LANGUAGETXT] ADD  CONSTRAINT [DF__LANGUAGET__TXTRE__6D58170E]  DEFAULT ((0)) FOR [TXTRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LANGUAGET__LANGU__6E4C3B47]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LANGUAGETXT] ADD  CONSTRAINT [DF__LANGUAGET__LANGU__6E4C3B47]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LANGUAGET__DATAA__6F405F80]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LANGUAGETXT] ADD  CONSTRAINT [DF__LANGUAGET__DATAA__6F405F80]  DEFAULT ('DAT') FOR [DATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LANGUAGETXT__TXT__6B6FCE9C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LANGUAGETXT] ADD  CONSTRAINT [DF__LANGUAGETXT__TXT__6B6FCE9C]  DEFAULT (NULL) FOR [TXT]
END

-------------------------------------------------------------------------------
PRINT 'Creating view LEDGER ..'
GO
IF OBJECT_ID(N'[dbo].[LEDGER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LEDGER]
GO
CREATE VIEW [dbo].LEDGER AS
(
  SELECT
    [CHARTOFACCOUNTS],
    [NAME],
    [DESCRIPTION],
    [PRIMARYFORLEGALENTITY],
    [FISCALCALENDAR],
    [DEFAULTEXCHANGERATETYPE],
    [BUDGETEXCHANGERATETYPE],
    [ACCOUNTINGCURRENCY],
    [REPORTINGCURRENCY],
    [ISBUDGETCONTROLENABLED],
    [RECID]
  FROM [ax].LEDGER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table LINEOFBUSINESS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LINEOFBUSINESS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[LINEOFBUSINESS](
    [LINEOFBUSINESSID] [nvarchar](10) NOT NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_928CODEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [LINEOFBUSINESSID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LINEOFBUS__LINEO__467F0C66]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LINEOFBUSINESS] ADD  CONSTRAINT [DF__LINEOFBUS__LINEO__467F0C66]  DEFAULT ('') FOR [LINEOFBUSINESSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LINEOFBUS__DESCR__4773309F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LINEOFBUSINESS] ADD  CONSTRAINT [DF__LINEOFBUS__DESCR__4773309F]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LINEOFBUS__DATAA__486754D8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LINEOFBUSINESS] ADD  CONSTRAINT [DF__LINEOFBUS__DATAA__486754D8]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSCOUNTRYREGION ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSCOUNTRYREGION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSCOUNTRYREGION]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSCOUNTRYREGION AS
(
  SELECT
    [COUNTRYREGIONID],
    [ISOCODE],
    [ADDRFORMAT],
    CONVERT([nvarchar](60), '') AS 'NAME',
    [CURRENCYCODE],
    [TIMEZONE],
    [ADDRESSUSEZIPPLUS4],
    [ISIMMUTABLE],
    [RECID],
    [BACENCODE_BR]
  FROM [ax].LOGISTICSADDRESSCOUNTRYREGION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION AS
(
  SELECT
    [LONGNAME],
    [SHORTNAME],
    [COUNTRYREGIONID],
    [LANGUAGEID],
    [RECID]
  FROM [ax].LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSCOUNTY ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSCOUNTY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSCOUNTY]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSCOUNTY AS
(
  SELECT
    [COUNTRYREGIONID],
    [COUNTYID],
    [STATEID],
    [NAME],
    [COUNTYCODE_SP],
    [RECID]
  FROM [ax].LOGISTICSADDRESSCOUNTY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSDISTRICT ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSDISTRICT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSDISTRICT]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSDISTRICT AS
(
  SELECT
    [NAME],
    [DESCRIPTION],
    [CITY],
    [RECID],
    [COUNTRYREGIONID_RU],
    [COUNTYID_RU],
    [STATEID_RU]
  FROM [ax].LOGISTICSADDRESSDISTRICT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSFORMATHEADING ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSFORMATHEADING]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSFORMATHEADING]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSFORMATHEADING AS
(
  SELECT
    [ADDRFORMAT],
    [NAME],
    [UPDATETOADDRESS],
    [RECID]
  FROM [ax].LOGISTICSADDRESSFORMATHEADING
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSFORMATLINES ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSFORMATLINES]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSFORMATLINES]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSFORMATLINES AS
(
  SELECT
    [ADDRFORMAT],
    [INACTIVE],
    [ELEMENT],
    [LINENUM],
    [DATAENTRYONLY],
    [RECID],
    [SEPARATOR],
    [SEPARATORCRLF]
  FROM [ax].LOGISTICSADDRESSFORMATLINES
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSSCITY ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSSCITY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSSCITY]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSSCITY AS
(
  SELECT
    [NAME],
    [DESCRIPTION],
    [COUNTRYREGIONID],
    [STATEID],
    [COUNTYID],
    [RECID],
    [IBGECODE_BR]
  FROM [ax].LOGISTICSADDRESSSCITY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSSTATE ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSSTATE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSSTATE]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSSTATE AS
(
  SELECT
    [NAME],
    [STATEID],
    [COUNTRYREGIONID],
    [INTRASTATCODE],
    [TIMEZONE],
    [RECID]
  FROM [ax].LOGISTICSADDRESSSTATE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSADDRESSZIPCODE ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSADDRESSZIPCODE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSADDRESSZIPCODE]
GO
CREATE VIEW [dbo].LOGISTICSADDRESSZIPCODE AS
(
  SELECT
    [ZIPCODE],
    [CITY],
    [STREETNAME],
    [FROMNUM],
    [TONUM],
    [EVENODD],
    [COUNTY],
    [COUNTRYREGIONID],
    [STATE],
    [CITYALIAS],
    [TIMEZONE],
    [DISTRICT],
    [CITYRECID],
    [DISTRICTNAME],
    [RECID]
  FROM [ax].LOGISTICSADDRESSZIPCODE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSELECTRONICADDRESS ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSELECTRONICADDRESS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSELECTRONICADDRESS]
GO
CREATE VIEW [dbo].LOGISTICSELECTRONICADDRESS AS
(
  SELECT
    [LOCATOR],
    CONVERT([bigint], 0) AS 'ELECTRONICADDRESSTYPE',
    [LOCATOREXTENSION],
    [LOCATION],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'VALIDFROM',
    CONVERT([int], 0) AS 'VALIDFROMTZID',
    CONVERT([datetime], '2154-12-31T23:59:59.000') AS 'VALIDTO',
    CONVERT([int], 0) AS 'VALIDTOTZID',
    [COUNTRYREGIONCODE],
    [TYPE],
    [RECID],
    [DESCRIPTION],
    [ISPRIMARY],
    [ISPRIVATE]
  FROM [ax].LOGISTICSELECTRONICADDRESS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table LOGISTICSELECTRONICADDRESSTRANSL ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LOGISTICSELECTRONICADDRESSTRANSL]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[LOGISTICSELECTRONICADDRESSTRANSL](
    [ELECTRONICADDRESSTYPE] [bigint] NOT NULL,
    [LANGUAGEID] [nvarchar](7) NOT NULL,
    [DESCRIPTION] [nvarchar](255) NOT NULL,
    [RECID] [bigint] NOT NULL,
 CONSTRAINT [I_4406RECID] PRIMARY KEY CLUSTERED
(
    [RECID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICS__ELECT__17E34DB7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTRANSL] ADD  CONSTRAINT [DF__LOGISTICS__ELECT__17E34DB7] DEFAULT ((0)) FOR [ELECTRONICADDRESSTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICS__LANGU__18D771F0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTRANSL] ADD CONSTRAINT [DF__LOGISTICS__LANGU__18D771F0] DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICS__DESCR__19CB9629]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTRANSL] ADD CONSTRAINT [DF__LOGISTICS__DESCR__19CB9629] DEFAULT ('') FOR [DESCRIPTION]
END

-------------------------------------------------------------------------------
PRINT 'Creating table LOGISTICSELECTRONICADDRESSTYPE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LOGISTICSELECTRONICADDRESSTYPE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[LOGISTICSELECTRONICADDRESSTYPE](
    [DESCRIPTION] [nvarchar](60) NOT NULL,
    [METHODTYPE] [int] NOT NULL,
    [TYPEID] [nvarchar](20) NOT NULL,
    [TYPE] [int] NOT NULL,
    [ISIMMUTABLE] [int] NOT NULL,
    [RECID] [bigint] NOT NULL,
 CONSTRAINT [I_2955RECID] PRIMARY KEY CLUSTERED
(
    [RECID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICS__DESCR__1E904B46]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTYPE] ADD  CONSTRAINT [DF__LOGISTICS__DESCR__1E904B46] DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICS__METHO__1F846F7F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTYPE] ADD CONSTRAINT [DF__LOGISTICS__METHO__1F846F7F] DEFAULT ((0)) FOR [METHODTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICS__TYPEI__207893B8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTYPE] ADD CONSTRAINT [DF__LOGISTICS__TYPEI__207893B8] DEFAULT ('') FOR [TYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICSE__TYPE__216CB7F1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTYPE] ADD CONSTRAINT [DF__LOGISTICSE__TYPE__216CB7F1] DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__LOGISTICS__ISIMM__2260DC2A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LOGISTICSELECTRONICADDRESSTYPE] ADD CONSTRAINT [DF__LOGISTICS__ISIMM__2260DC2A] DEFAULT ((0)) FOR [ISIMMUTABLE]
END

-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSLOCATION ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSLOCATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSLOCATION]
GO
CREATE VIEW [dbo].LOGISTICSLOCATION AS
(
  SELECT
    [LOCATIONID],
    [DESCRIPTION],
    CONVERT([nvarchar](9), '') AS 'DUNSNUMBER',
    [ISPOSTALADDRESS],
    [PARENTLOCATION],
    [DUNSNUMBERRECID],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].LOGISTICSLOCATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSLOCATIONEXT ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSLOCATIONEXT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSLOCATIONEXT]
GO
CREATE VIEW [dbo].LOGISTICSLOCATIONEXT AS
(
  SELECT
    [LOCATION],
    [SALESCALENDARID],
    [TAXGROUP],
    [DATAAREAID],
    [RECID]
  FROM [ax].LOGISTICSLOCATIONEXT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSLOCATIONROLE ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSLOCATIONROLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSLOCATIONROLE]
GO
CREATE VIEW [dbo].LOGISTICSLOCATIONROLE AS
(
  SELECT
    [NAME],
    [TYPE],
    [ISPOSTALADDRESS],
    [ISCONTACTINFO],
    [RECID]
  FROM [ax].LOGISTICSLOCATIONROLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSLOCATIONROLETRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSLOCATIONROLETRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSLOCATIONROLETRANSLATION]
GO
CREATE VIEW [dbo].LOGISTICSLOCATIONROLETRANSLATION AS
(
  SELECT
    [LOCATIONROLE],
    [LANGUAGEID],
    [DESCRIPTION],
    [RECID]
  FROM [ax].LOGISTICSLOCATIONROLETRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view LOGISTICSPOSTALADDRESS ..'
GO
IF OBJECT_ID(N'[dbo].[LOGISTICSPOSTALADDRESS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSPOSTALADDRESS]
GO
CREATE VIEW [dbo].LOGISTICSPOSTALADDRESS AS
(
  SELECT
    [ADDRESS],
    [COUNTRYREGIONID],
    [ZIPCODE],
    [STATE],
    [COUNTY],
    [CITY],
    [STREET],
    [LATITUDE],
    [LONGITUDE],
    [TIMEZONE],
    [STREETNUMBER],
    [BUILDINGCOMPLIMENT],
    [POSTBOX],
    [CITYRECID],
    [DISTRICT],
    [LOCATION],
    [ZIPCODERECID],
    [VALIDTO],
    [VALIDTOTZID],
    [VALIDFROM],
    [VALIDFROMTZID],
    [DISTRICTNAME],
    [MODIFIEDDATETIME],
    [RECID],
    [ISPRIVATE]
  FROM [ax].LOGISTICSPOSTALADDRESS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view MARKUPAUTOLINE ..'
GO
IF OBJECT_ID(N'[dbo].[MARKUPAUTOLINE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[MARKUPAUTOLINE]
GO
CREATE VIEW [dbo].MARKUPAUTOLINE AS
(
  SELECT
    [TABLETABLEID],
    [TABLERECID],
    [LINENUM],
    [MARKUPCODE],
    [CURRENCYCODE],
    [VALUE],
    [TXT],
    [TAXGROUP],
    [TAXITEMGROUP],
    [MARKUPCATEGORY],
    [MODULECATEGORY],
    [MODULETYPE],
    [KEEP],
    [MARKUPCURRENCYCODE],
    [NOTIONALCHARGES_IN],
    [NOTIONALPCT_IN],
    [CUSTOMSASSESSABLEVALUE_IN],
    [FROMAMOUNT],
    [TOAMOUNT],
    [DATAAREAID],
    [RECID]
  FROM [ax].MARKUPAUTOLINE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view MARKUPAUTOTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[MARKUPAUTOTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[MARKUPAUTOTABLE]
GO
CREATE VIEW [dbo].MARKUPAUTOTABLE AS
(
  SELECT
    [MODULETYPE],
    [ACCOUNTRELATION],
    [ITEMRELATION],
    [ACCOUNTCODE],
    [ITEMCODE],
    [MODULECATEGORY],
    [RETURNRELATION],
    [MARKUPRETURN],
    [RETAILCONCESSIONFEE],
    [DLVMODECODE],
    [DLVMODERELATION],
    [DATAAREAID],
    [RECID]
  FROM [ax].MARKUPAUTOTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view MARKUPTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[MARKUPTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[MARKUPTABLE]
GO
CREATE VIEW [dbo].MARKUPTABLE AS
(
  SELECT
    [TXT],
    [CUSTPOSTING],
    [VENDPOSTING],
    [TAXITEMGROUP],
    [CUSTTYPE],
    [VENDTYPE],
    [MODULETYPE],
    [MARKUPCODE],
    [INTRASTAT_FI],
    [USEINMATCHING],
    [MAXAMOUNT],
    [CUSTOMERLEDGERDIMENSION],
    [VENDORLEDGERDIMENSION],
    [ISLETTEROFCREDIT_SA],
    [DATAAREAID],
    [RECID],
    [RETAILCONCESSIONFEE]
  FROM [ax].MARKUPTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table MASTERTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MASTERTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[MASTERTABLE](
    [ID] [int] NOT NULL,
    [NAME] [nchar](10) NULL,
 CONSTRAINT [PK_MASTERTABLE] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table MODULEINFO ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MODULEINFO]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[MODULEINFO](
    [ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [VERSION] [nvarchar](100) NULL,
    [NAME] [nvarchar](100) NULL,
    [ISMAIN] [bit] NULL,
    [OPTIMISTICLOCKFIELD] [int] NULL,
 CONSTRAINT [PK_MODULEINFO] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table NUMBERSEQUENCEGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NUMBERSEQUENCEGROUP](
    [NUMBERSEQUENCEGROUPID] [nvarchar](10) NOT NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_772GROUPID] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [NUMBERSEQUENCEGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NUMBE__6A325CF7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEGROUP] ADD  CONSTRAINT [DF__NUMBERSEQ__NUMBE__6A325CF7]  DEFAULT ('') FOR [NUMBERSEQUENCEGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DESCR__6B268130]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEGROUP] ADD  CONSTRAINT [DF__NUMBERSEQ__DESCR__6B268130]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAA__6C1AA569]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEGROUP] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAA__6C1AA569]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table NUMBERSEQUENCEGROUPREF ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCEGROUPREF]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NUMBERSEQUENCEGROUPREF](
    [NUMBERSEQUENCEGROUPID] [nvarchar](10) NOT NULL,
    [DATATYPEID] [int] NOT NULL,
    [NUMBERSEQUENCECODE] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_793GROUPIDDATATYPE] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [DATATYPEID] ASC,
    [NUMBERSEQUENCEGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NUMBE__0C8774FB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEGROUPREF] ADD  CONSTRAINT [DF__NUMBERSEQ__NUMBE__0C8774FB]  DEFAULT ('') FOR [NUMBERSEQUENCEGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAT__0D7B9934]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEGROUPREF] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAT__0D7B9934]  DEFAULT ((0)) FOR [DATATYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NUMBE__0E6FBD6D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEGROUPREF] ADD  CONSTRAINT [DF__NUMBERSEQ__NUMBE__0E6FBD6D]  DEFAULT ('') FOR [NUMBERSEQUENCECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAA__0F63E1A6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEGROUPREF] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAA__0F63E1A6]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table NUMBERSEQUENCEHISTORY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCEHISTORY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NUMBERSEQUENCEHISTORY](
    [NUMBERSEQUENCE] [nvarchar](10) NOT NULL,
    [LOWEST] [int] NULL,
    [HIGHEST] [int] NULL,
    [NEXTREC] [int] NULL,
    [BLOCKED] [int] NULL,
    [CYCLIC] [int] NULL,
    [CONTINUOUS] [int] NULL,
    [FORMAT] [nvarchar](20) NULL,
    [CLEANATACCESS] [int] NULL,
    [INUSE] [int] NULL,
    [NOINCREMENT] [int] NULL,
    [ACTION] [int] NULL,
    [NEXTRECBEFORE] [int] NULL,
    [HIGHESTBEFORE] [int] NULL,
    [LOWESTBEFORE] [int] NULL,
    [CLEANINTERVAL] [numeric](28, 12) NULL,
    [ALLOWCHANGEUP] [int] NULL,
    [ALLOWCHANGEDOWN] [int] NULL,
    [MANUAL] [int] NULL,
    [FETCHAHEAD] [int] NULL,
    [FETCHAHEADQTY] [int] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [CREATEDDATE] [datetime] NULL,
    [CREATEDTIME] [int] NULL,
    [CREATEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCEHISTORY]') AND name = N'I_521NUMBERSEQIDX')
CREATE UNIQUE CLUSTERED INDEX [I_521NUMBERSEQIDX] ON [dbo].[NUMBERSEQUENCEHISTORY]
(
    [DATAAREAID] ASC,
    [NUMBERSEQUENCE] ASC,
    [MODIFIEDDATE] ASC,
    [MODIFIEDTIME] ASC,
    [RECID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NUMBE__2B36194D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__NUMBE__2B36194D]  DEFAULT ('') FOR [NUMBERSEQUENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__LOWES__2C2A3D86]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__LOWES__2C2A3D86]  DEFAULT ((0)) FOR [LOWEST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__HIGHE__2D1E61BF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__HIGHE__2D1E61BF]  DEFAULT ((0)) FOR [HIGHEST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NEXTR__2E1285F8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__NEXTR__2E1285F8]  DEFAULT ((0)) FOR [NEXTREC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__BLOCK__2F06AA31]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__BLOCK__2F06AA31]  DEFAULT ((0)) FOR [BLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CYCLI__2FFACE6A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__CYCLI__2FFACE6A]  DEFAULT ((0)) FOR [CYCLIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CONTI__30EEF2A3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__CONTI__30EEF2A3]  DEFAULT ((0)) FOR [CONTINUOUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__FORMA__31E316DC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__FORMA__31E316DC]  DEFAULT ('') FOR [FORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CLEAN__32D73B15]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__CLEAN__32D73B15]  DEFAULT ((0)) FOR [CLEANATACCESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__INUSE__33CB5F4E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__INUSE__33CB5F4E]  DEFAULT ((0)) FOR [INUSE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NOINC__34BF8387]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__NOINC__34BF8387]  DEFAULT ((0)) FOR [NOINCREMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__ACTIO__35B3A7C0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__ACTIO__35B3A7C0]  DEFAULT ((0)) FOR [ACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NEXTR__36A7CBF9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__NEXTR__36A7CBF9]  DEFAULT ((0)) FOR [NEXTRECBEFORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__HIGHE__379BF032]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__HIGHE__379BF032]  DEFAULT ((0)) FOR [HIGHESTBEFORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__LOWES__3890146B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__LOWES__3890146B]  DEFAULT ((0)) FOR [LOWESTBEFORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CLEAN__398438A4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__CLEAN__398438A4]  DEFAULT ((0)) FOR [CLEANINTERVAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__ALLOW__3A785CDD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__ALLOW__3A785CDD]  DEFAULT ((0)) FOR [ALLOWCHANGEUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__ALLOW__3B6C8116]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__ALLOW__3B6C8116]  DEFAULT ((0)) FOR [ALLOWCHANGEDOWN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MANUA__3C60A54F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__MANUA__3C60A54F]  DEFAULT ((0)) FOR [MANUAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__FETCH__3D54C988]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__FETCH__3D54C988]  DEFAULT ((0)) FOR [FETCHAHEAD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__FETCH__3E48EDC1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__FETCH__3E48EDC1]  DEFAULT ((0)) FOR [FETCHAHEADQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__3F3D11FA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__3F3D11FA]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__40313633]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__40313633]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__41255A6C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__41255A6C]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CREAT__42197EA5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__CREAT__42197EA5]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CREATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CREAT__430DA2DE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__CREAT__430DA2DE]  DEFAULT ((0)) FOR [CREATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CREAT__4401C717]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__CREAT__4401C717]  DEFAULT ('?') FOR [CREATEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAA__44F5EB50]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEHISTORY] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAA__44F5EB50]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table NUMBERSEQUENCELIST ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCELIST]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NUMBERSEQUENCELIST](
    [NUM] [nvarchar](20) NOT NULL,
    [SESSIONLOGINDATE] [datetime] NULL,
    [USERID] [nvarchar](5) NULL,
    [NUMBERSEQUENCE] [nvarchar](10) NOT NULL,
    [STATUS] [int] NOT NULL,
    [SESSIONLOGINTIME] [int] NULL,
    [SESSIONID] [int] NULL,
    [TRANSID] [bigint] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [MODIFIEDTRANSACTIONID] [bigint] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_271NUMIDX] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [NUMBERSEQUENCE] ASC,
    [STATUS] ASC,
    [NUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQUE__NUM__6680FC4D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQUE__NUM__6680FC4D]  DEFAULT ('') FOR [NUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__SESSI__67752086]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__SESSI__67752086]  DEFAULT ('1900-01-01 00:00:00.000') FOR [SESSIONLOGINDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__USERI__686944BF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__USERI__686944BF]  DEFAULT ('') FOR [USERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NUMBE__695D68F8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__NUMBE__695D68F8]  DEFAULT ('') FOR [NUMBERSEQUENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__STATU__6A518D31]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__STATU__6A518D31]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__SESSI__6B45B16A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__SESSI__6B45B16A]  DEFAULT ((0)) FOR [SESSIONLOGINTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__SESSI__6C39D5A3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__SESSI__6C39D5A3]  DEFAULT ((0)) FOR [SESSIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__TRANS__6D2DF9DC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__TRANS__6D2DF9DC]  DEFAULT ((0)) FOR [TRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__6E221E15]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__6E221E15]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__6F16424E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__6F16424E]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__700A6687]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__700A6687]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__70FE8AC0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__70FE8AC0]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAA__71F2AEF9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCELIST] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAA__71F2AEF9]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table NUMBERSEQUENCEREFERENCE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCEREFERENCE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NUMBERSEQUENCEREFERENCE](
    [NUMBERSEQUENCE] [nvarchar](10) NULL,
    [DATATYPEID] [int] NULL,
    [CONFIGURATIONKEYID] [int] NULL,
    [MODULE] [int] NULL,
    [REFERENCEHELP] [nvarchar](255) NULL,
    [REFERENCELABEL] [nvarchar](30) NULL,
    [DATATYPESAMEASID] [int] NULL,
    [WIZARDCONTINUOUS] [int] NULL,
    [ALLOWSAMEAS] [int] NULL,
    [SORTFIELD] [int] NULL,
    [GROUPENABLED] [int] NULL,
    [WIZARDHIGHEST] [int] NULL,
    [WIZARDLOWEST] [int] NULL,
    [WIZARDALLOWCHANGEDOWN] [int] NULL,
    [WIZARDALLOWCHANGEUP] [int] NULL,
    [WIZARDMANUAL] [int] NULL,
    [WIZARDFETCHAHEADQTY] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NUMBE__462A06AB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__NUMBE__462A06AB]  DEFAULT ('') FOR [NUMBERSEQUENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAT__471E2AE4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAT__471E2AE4]  DEFAULT ((0)) FOR [DATATYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CONFI__48124F1D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__CONFI__48124F1D]  DEFAULT ((0)) FOR [CONFIGURATIONKEYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODUL__49067356]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__MODUL__49067356]  DEFAULT ((0)) FOR [MODULE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__REFER__49FA978F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__REFER__49FA978F]  DEFAULT ('') FOR [REFERENCEHELP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__REFER__4AEEBBC8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__REFER__4AEEBBC8]  DEFAULT ('') FOR [REFERENCELABEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAT__4BE2E001]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAT__4BE2E001]  DEFAULT ((0)) FOR [DATATYPESAMEASID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__WIZAR__4CD7043A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__WIZAR__4CD7043A]  DEFAULT ((0)) FOR [WIZARDCONTINUOUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__ALLOW__4DCB2873]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__ALLOW__4DCB2873]  DEFAULT ((0)) FOR [ALLOWSAMEAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__SORTF__4EBF4CAC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__SORTF__4EBF4CAC]  DEFAULT ((0)) FOR [SORTFIELD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__GROUP__4FB370E5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__GROUP__4FB370E5]  DEFAULT ((0)) FOR [GROUPENABLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__WIZAR__50A7951E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__WIZAR__50A7951E]  DEFAULT ((0)) FOR [WIZARDHIGHEST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__WIZAR__519BB957]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__WIZAR__519BB957]  DEFAULT ((0)) FOR [WIZARDLOWEST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__WIZAR__528FDD90]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__WIZAR__528FDD90]  DEFAULT ((0)) FOR [WIZARDALLOWCHANGEDOWN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__WIZAR__538401C9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__WIZAR__538401C9]  DEFAULT ((0)) FOR [WIZARDALLOWCHANGEUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__WIZAR__54782602]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__WIZAR__54782602]  DEFAULT ((0)) FOR [WIZARDMANUAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__WIZAR__556C4A3B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__WIZAR__556C4A3B]  DEFAULT ((0)) FOR [WIZARDFETCHAHEADQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAA__56606E74]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCEREFERENCE] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAA__56606E74]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table NUMBERSEQUENCETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NUMBERSEQUENCETABLE](
    [NUMBERSEQUENCE] [nvarchar](10) NOT NULL,
    [TXT] [nvarchar](30) NULL,
    [LOWEST] [int] NULL,
    [HIGHEST] [int] NULL,
    [NEXTREC] [int] NULL,
    [BLOCKED] [int] NULL,
    [FORMAT] [nvarchar](20) NULL,
    [CONTINUOUS] [int] NULL,
    [CYCLIC] [int] NULL,
    [CLEANATACCESS] [int] NULL,
    [INUSE] [int] NULL,
    [NOINCREMENT] [int] NULL,
    [CLEANINTERVAL] [numeric](28, 12) NULL,
    [LATESTCLEANDATE] [datetime] NULL,
    [LATESTCLEANTIME] [int] NULL,
    [ALLOWCHANGEUP] [int] NULL,
    [ALLOWCHANGEDOWN] [int] NULL,
    [MANUAL] [int] NULL,
    [FETCHAHEADQTY] [int] NULL,
    [FETCHAHEAD] [int] NULL,
    [MODIFIEDTRANSACTIONID] [bigint] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_273SERIESIDX] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [NUMBERSEQUENCE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NUMBE__75C33FDD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__NUMBE__75C33FDD]  DEFAULT ('') FOR [NUMBERSEQUENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQUE__TXT__76B76416]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQUE__TXT__76B76416]  DEFAULT ('') FOR [TXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__LOWES__77AB884F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__LOWES__77AB884F]  DEFAULT ((0)) FOR [LOWEST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__HIGHE__789FAC88]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__HIGHE__789FAC88]  DEFAULT ((0)) FOR [HIGHEST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NEXTR__7993D0C1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__NEXTR__7993D0C1]  DEFAULT ((0)) FOR [NEXTREC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__BLOCK__7A87F4FA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__BLOCK__7A87F4FA]  DEFAULT ((0)) FOR [BLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__FORMA__7B7C1933]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__FORMA__7B7C1933]  DEFAULT ('') FOR [FORMAT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CONTI__7C703D6C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__CONTI__7C703D6C]  DEFAULT ((0)) FOR [CONTINUOUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CYCLI__7D6461A5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__CYCLI__7D6461A5]  DEFAULT ((0)) FOR [CYCLIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CLEAN__7E5885DE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__CLEAN__7E5885DE]  DEFAULT ((0)) FOR [CLEANATACCESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__INUSE__7F4CAA17]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__INUSE__7F4CAA17]  DEFAULT ((0)) FOR [INUSE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__NOINC__0040CE50]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__NOINC__0040CE50]  DEFAULT ((0)) FOR [NOINCREMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__CLEAN__0134F289]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__CLEAN__0134F289]  DEFAULT ((0)) FOR [CLEANINTERVAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__LATES__022916C2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__LATES__022916C2]  DEFAULT ('1900-01-01 00:00:00.000') FOR [LATESTCLEANDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__LATES__031D3AFB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__LATES__031D3AFB]  DEFAULT ((0)) FOR [LATESTCLEANTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__ALLOW__04115F34]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__ALLOW__04115F34]  DEFAULT ((0)) FOR [ALLOWCHANGEUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__ALLOW__0505836D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__ALLOW__0505836D]  DEFAULT ((0)) FOR [ALLOWCHANGEDOWN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MANUA__05F9A7A6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__MANUA__05F9A7A6]  DEFAULT ((0)) FOR [MANUAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__FETCH__06EDCBDF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__FETCH__06EDCBDF]  DEFAULT ((0)) FOR [FETCHAHEADQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__FETCH__07E1F018]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__FETCH__07E1F018]  DEFAULT ((0)) FOR [FETCHAHEAD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__MODIF__08D61451]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__MODIF__08D61451]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAA__09CA388A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETABLE] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAA__09CA388A]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table NUMBERSEQUENCETTS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NUMBERSEQUENCETTS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NUMBERSEQUENCETTS](
    [TRANSID] [bigint] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__TRANS__62B06B69]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETTS] ADD  CONSTRAINT [DF__NUMBERSEQ__TRANS__62B06B69]  DEFAULT ((0)) FOR [TRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__NUMBERSEQ__DATAA__63A48FA2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NUMBERSEQUENCETTS] ADD  CONSTRAINT [DF__NUMBERSEQ__DATAA__63A48FA2]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table OCCUPATION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OCCUPATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OCCUPATION](
    [GCRECORD] [int] NULL,
    [OID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [TITLE] [nvarchar](100) NULL,
    [OPTIMISTICLOCKFIELD] [int] NULL,
 CONSTRAINT [PK_OCCUPATION] PRIMARY KEY CLUSTERED
(
    [OID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating view OMOPERATINGUNIT ..'
GO
IF OBJECT_ID(N'[dbo].[OMOPERATINGUNIT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[OMOPERATINGUNIT]
GO
CREATE VIEW [dbo].OMOPERATINGUNIT AS
(
  SELECT
    [OMOPERATINGUNITTYPE],
    [HCMWORKER],
    [OMOPERATINGUNITNUMBER],
    [RECID]
  FROM [ax].OMOPERATINGUNIT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table PERSONINFO ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PERSONINFO]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PERSONINFO](
    [GCRECORD] [int] NULL,
    [OID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [FIRSTNAME] [nvarchar](100) NULL,
    [LASTNAME] [nvarchar](100) NULL,
    [BIRTHDAY] [datetime] NULL,
    [ISFEMALE] [bit] NULL,
    [PARENT] [uniqueidentifier] NULL,
    [OPTIMISTICLOCKFIELD] [int] NULL,
    [OBJECTTYPE] [int] NULL,
 CONSTRAINT [PK_PERSONINFO] PRIMARY KEY CLUSTERED
(
    [OID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSCARDTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSCARDTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSCARDTRANS](
    [STOREID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [DELCARDTRANSID] [nvarchar](10) NULL,
    [TRANSACTIONID] [nvarchar](10) NULL,
    [LINENUM] [numeric](28, 12) NULL,
    [RECEIPTID] [nvarchar](18) NULL,
    [EFTTERMINALID] [nvarchar](10) NULL,
    [TENDERTYPEID] [nvarchar](10) NULL,
    [TRANSACTIONTYPE] [int] NULL,
    [MSRINPUT] [int] NULL,
    [TRANSDATE] [datetime] NULL,
    [TRANSTIME] [int] NULL,
    [AUTHORIZATIONOK] [int] NULL,
    [VOIDED] [int] NULL,
    [CARDNUMBER] [nvarchar](30) NULL,
    [CARDTYPEID] [nvarchar](10) NULL,
    [CARDTYPENAME] [nvarchar](30) NULL,
    [EXPIRYDATE] [nvarchar](10) NULL,
    [AUTHORIZATIONCODE] [nvarchar](9) NULL,
    [RESULTCODE] [nvarchar](2) NULL,
    [MESSAGE] [nvarchar](80) NULL,
    [CARDCLASS] [nvarchar](2) NULL,
    [CARDTRANSID] [int] NULL,
    [EXTRADATA] [nvarchar](30) NULL,
    [AMOUNT] [numeric](28, 12) NULL,
    [VOIDEDRECEIPTID] [nvarchar](18) NULL,
    [VOIDEDCARDTRANSID] [int] NULL,
    [VOIDEDEFTCARDTRANSID] [nvarchar](10) NULL,
    [EFTMECHANTID] [nvarchar](10) NULL,
    [EFTCARDTRANSID] [nvarchar](10) NULL,
    [EFTSTOREID] [nvarchar](10) NULL,
    [AUTHORIZATIONSOURCECODE] [nvarchar](10) NULL,
    [REPLICATED] [int] NULL,
    [EFTBATCHID] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__STORE__50F40FE6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__STORE__50F40FE6]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__TERMI__51E8341F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__TERMI__51E8341F]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__DELCA__52DC5858]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__DELCA__52DC5858]  DEFAULT ('') FOR [DELCARDTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__TRANS__53D07C91]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__TRANS__53D07C91]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__LINEN__54C4A0CA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__LINEN__54C4A0CA]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__RECEI__55B8C503]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__RECEI__55B8C503]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__EFTTE__56ACE93C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__EFTTE__56ACE93C]  DEFAULT ('') FOR [EFTTERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__TENDE__57A10D75]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__TENDE__57A10D75]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__TRANS__589531AE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__TRANS__589531AE]  DEFAULT ((0)) FOR [TRANSACTIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__MSRIN__598955E7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__MSRIN__598955E7]  DEFAULT ((0)) FOR [MSRINPUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__TRANS__5A7D7A20]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__TRANS__5A7D7A20]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__TRANS__5B719E59]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__TRANS__5B719E59]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__AUTHO__5C65C292]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__AUTHO__5C65C292]  DEFAULT ((0)) FOR [AUTHORIZATIONOK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__VOIDE__5D59E6CB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__VOIDE__5D59E6CB]  DEFAULT ((0)) FOR [VOIDED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__CARDN__5E4E0B04]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__CARDN__5E4E0B04]  DEFAULT ('') FOR [CARDNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__CARDT__5F422F3D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__CARDT__5F422F3D]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__CARDT__60365376]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__CARDT__60365376]  DEFAULT ('') FOR [CARDTYPENAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__EXPIR__612A77AF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__EXPIR__612A77AF]  DEFAULT ('') FOR [EXPIRYDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__AUTHO__621E9BE8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__AUTHO__621E9BE8]  DEFAULT ('') FOR [AUTHORIZATIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__RESUL__6312C021]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__RESUL__6312C021]  DEFAULT ('') FOR [RESULTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__MESSA__6406E45A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__MESSA__6406E45A]  DEFAULT ('') FOR [MESSAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__CARDC__64FB0893]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__CARDC__64FB0893]  DEFAULT ('') FOR [CARDCLASS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__CARDT__65EF2CCC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__CARDT__65EF2CCC]  DEFAULT ((0)) FOR [CARDTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__EXTRA__66E35105]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__EXTRA__66E35105]  DEFAULT ('') FOR [EXTRADATA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__AMOUN__67D7753E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__AMOUN__67D7753E]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__VOIDE__68CB9977]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__VOIDE__68CB9977]  DEFAULT ('') FOR [VOIDEDRECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__VOIDE__69BFBDB0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__VOIDE__69BFBDB0]  DEFAULT ((0)) FOR [VOIDEDCARDTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__VOIDE__6AB3E1E9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__VOIDE__6AB3E1E9]  DEFAULT ('') FOR [VOIDEDEFTCARDTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__EFTME__6BA80622]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__EFTME__6BA80622]  DEFAULT ('') FOR [EFTMECHANTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__EFTCA__6C9C2A5B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__EFTCA__6C9C2A5B]  DEFAULT ('') FOR [EFTCARDTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__EFTST__6D904E94]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__EFTST__6D904E94]  DEFAULT ('') FOR [EFTSTOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__AUTHO__6E8472CD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__AUTHO__6E8472CD]  DEFAULT ('') FOR [AUTHORIZATIONSOURCECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__REPLI__6F789706]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__REPLI__6F789706]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__EFTBA__706CBB3F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__EFTBA__706CBB3F]  DEFAULT ('') FOR [EFTBATCHID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCARDTR__DATAA__7160DF78]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCARDTRANS] ADD  CONSTRAINT [DF__POSCARDTR__DATAA__7160DF78]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSCOMMAND ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSCOMMAND]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSCOMMAND](
    [COMMANDID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [PROMPT] [nvarchar](30) NULL,
    [MENUFUNCTION] [int] NULL,
    [PARAMETERTYPE] [int] NULL,
    [MANAGERKEY] [int] NULL,
    [SCANNERACTION] [int] NULL,
    [MSRACTION] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20052COMMANDIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [COMMANDID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__COMMA__7DC6B65D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__COMMA__7DC6B65D]  DEFAULT ('') FOR [COMMANDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAND__NAME__7EBADA96]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAND__NAME__7EBADA96]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__PROMP__7FAEFECF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__PROMP__7FAEFECF]  DEFAULT ('') FOR [PROMPT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__MENUF__00A32308]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__MENUF__00A32308]  DEFAULT ((0)) FOR [MENUFUNCTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__PARAM__01974741]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__PARAM__01974741]  DEFAULT ((0)) FOR [PARAMETERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__MANAG__028B6B7A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__MANAG__028B6B7A]  DEFAULT ((0)) FOR [MANAGERKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__SCANN__037F8FB3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__SCANN__037F8FB3]  DEFAULT ((0)) FOR [SCANNERACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__MSRAC__0473B3EC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__MSRAC__0473B3EC]  DEFAULT ((0)) FOR [MSRACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOMMAN__DATAA__0567D825]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSCOMMAND] ADD  CONSTRAINT [DF__POSCOMMAN__DATAA__0567D825]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view POSDISCVALIDATIONPERIOD ..'
GO
IF OBJECT_ID(N'[dbo].[POSDISCVALIDATIONPERIOD]', N'V') IS NOT NULL
    DROP VIEW [dbo].[POSDISCVALIDATIONPERIOD]
GO
CREATE VIEW [dbo].POSDISCVALIDATIONPERIOD AS
(
  SELECT
    [PERIODID] AS 'ID',
    [NAME] AS 'DESCRIPTION',
    [VALIDFROM],
    [VALIDTO],
    [STARTINGTIME],
    [ENDINGTIME],
    [TIMEWITHINBOUNDS],
    [MONDAYSTARTINGTIME] AS 'MONSTARTINGTIME',
    [MONDAYENDINGTIME] AS 'MONENDINGTIME',
    [MONDAYTIMEWITHINBOUNDS] AS 'MONWITHINBOUNDS',
    [THUESDAYSTARTINGTIME] AS 'TUESTARTINGTIME',
    [THUESDAYENDINGTIME] AS 'TUEENDINGTIME',
    [THUESDAYTIMEWITHINBOUNDS] AS 'TUEWITHINBOUNDS',
    [WEDNESDAYSTARTINGTIME] AS 'WEDSTARTINGTIME',
    [WEDNESDAYENDINGTIME] AS 'WEDENDINGTIME',
    [WEDNESDAYTIMEWITHINBOUNDS] AS 'WEDWITHINBOUNDS',
    [THURSDAYSTARTINGTIME] AS 'THUSTARTINGTIME',
    [THURSDAYENDINGTIME] AS 'THUENDINGTIME',
    [THURSDAYTIMEWITHINBOUNDS] AS 'THUWITHINBOUNDS',
    [FRIDAYSTARTINGTIME] AS 'FRISTARTINGTIME',
    [FRIDAYENDINGTIME] AS 'FRIENDINGTIME',
    [FRIDAYTIMEWITHINBOUNDS] AS 'FRIWITHINBOUNDS',
    [SATURDAYSTARTINGTIME] AS 'SATSTARTINGTIME',
    [SATURDAYENDINGTIME] AS 'SATENDINGTIME',
    [SATURDAYTIMEWITHINBOUNDS] AS 'SATWITHINBOUNDS',
    [SUNDAYSTARTINGTIME] AS 'SUNSTARTINGTIME',
    [SUNDAYENDINGTIME] AS 'SUNENDINGTIME',
    [SUNDAYTIMEWITHINBOUNDS] AS 'SUNWITHINBOUNDS',
    [ENDINGTIMEAFTERMIDNIGHT] AS 'ENDTIMEAFTERMID',
    [MONDAYENDINGTIMEAFTERMIDNIGHT] AS 'MONAFTERMIDNIGHT',
    [THUESDAYENDINGTIMEAFTERMIDNIGHT] AS 'TUEAFTERMIDNIGHT',
    [WEDNESDAYENDINGTIMEAFTERMIDNIGHT] AS 'WEDAFTERMIDNIGHT',
    [THURSDAYENDINGTIMEAFTERMIDNIGHT] AS 'THUAFTERMIDNIGHT',
    [FRIDAYENDINGTIMEAFTERMIDNIGHT] AS 'FRIAFTERMIDNIGHT',
    [SATURDAYENDINGTIMEAFTERMIDNIGHT] AS 'SATAFTERMIDNIGHT',
    [SUNDAYENDINGTIMEAFTERMIDNIGHT] AS 'SUNAFTERMIDNIGHT',
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILDISCOUNTVALIDATIONPERIOD
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table POSDISPENSEPRINTERSETUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSDISPENSEPRINTERSETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSDISPENSEPRINTERSETUP](
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [PRINTERGROUPID] [nvarchar](10) NOT NULL,
    [DISABLEPRINTING] [int] NULL,
    [NUMBEROFCOPIES] [int] NULL,
    [PRINTERID] [nvarchar](10) NULL,
    [PRIMARYFALLBACKPRINTERID] [nvarchar](10) NULL,
    [SECONDARYFALLBACKPRINTERID] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20057STORETERMINALGROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC,
    [PRINTERGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__STORE__3422C70E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__STORE__3422C70E]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__TERMI__3516EB47]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__TERMI__3516EB47]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__PRINT__360B0F80]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__PRINT__360B0F80]  DEFAULT ('') FOR [PRINTERGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__DISAB__36FF33B9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__DISAB__36FF33B9]  DEFAULT ((0)) FOR [DISABLEPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__NUMBE__37F357F2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__NUMBE__37F357F2]  DEFAULT ((0)) FOR [NUMBEROFCOPIES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__PRINT__38E77C2B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__PRINT__38E77C2B]  DEFAULT ('') FOR [PRINTERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__PRIMA__39DBA064]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__PRIMA__39DBA064]  DEFAULT ('') FOR [PRIMARYFALLBACKPRINTERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__SECON__3ACFC49D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__SECON__3ACFC49D]  DEFAULT ('') FOR [SECONDARYFALLBACKPRINTERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__DATAA__3BC3E8D6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSDISPENSEPRINTERSETUP] ADD  CONSTRAINT [DF__POSDISPEN__DATAA__3BC3E8D6]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSEXTERNALPRINTERTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSEXTERNALPRINTERTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSEXTERNALPRINTERTABLE](
    [PRINTERID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [HARDWAREPROFILEID] [nvarchar](10) NULL,
    [CONNECTION] [int] NULL,
    [HOSTNAME] [nvarchar](20) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20058PRINTERIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PRINTERID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSEXTERN__PRINT__3F9479BA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSEXTERNALPRINTERTABLE] ADD  CONSTRAINT [DF__POSEXTERN__PRINT__3F9479BA]  DEFAULT ('') FOR [PRINTERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSEXTERNA__NAME__40889DF3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSEXTERNALPRINTERTABLE] ADD  CONSTRAINT [DF__POSEXTERNA__NAME__40889DF3]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSEXTERN__HARDW__417CC22C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSEXTERNALPRINTERTABLE] ADD  CONSTRAINT [DF__POSEXTERN__HARDW__417CC22C]  DEFAULT ('') FOR [HARDWAREPROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSEXTERN__CONNE__4270E665]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSEXTERNALPRINTERTABLE] ADD  CONSTRAINT [DF__POSEXTERN__CONNE__4270E665]  DEFAULT ((0)) FOR [CONNECTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSEXTERN__HOSTN__43650A9E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSEXTERNALPRINTERTABLE] ADD  CONSTRAINT [DF__POSEXTERN__HOSTN__43650A9E]  DEFAULT ('') FOR [HOSTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSEXTERN__DATAA__44592ED7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSEXTERNALPRINTERTABLE] ADD  CONSTRAINT [DF__POSEXTERN__DATAA__44592ED7]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSHELPTXT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSHELPTXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSHELPTXT](
    [HELPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [HELPTXT] [nvarchar](1000) NULL,
    [DEL_LINENUM] [numeric](28, 12) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20061HELPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [HELPID] ASC,
    [DEL_LINENUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSHELPTX__HELPI__7A80355E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSHELPTXT] ADD  CONSTRAINT [DF__POSHELPTX__HELPI__7A80355E]  DEFAULT ('') FOR [HELPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSHELPTXT__NAME__7B745997]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSHELPTXT] ADD  CONSTRAINT [DF__POSHELPTXT__NAME__7B745997]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSHELPTX__HELPT__7C687DD0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSHELPTXT] ADD  CONSTRAINT [DF__POSHELPTX__HELPT__7C687DD0]  DEFAULT ('') FOR [HELPTXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSHELPTX__DEL_L__7D5CA209]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSHELPTXT] ADD  CONSTRAINT [DF__POSHELPTX__DEL_L__7D5CA209]  DEFAULT ((0)) FOR [DEL_LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSHELPTX__DATAA__7E50C642]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSHELPTXT] ADD  CONSTRAINT [DF__POSHELPTX__DATAA__7E50C642]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSISCARDTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISCARDTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISCARDTABLE](
    [STOREID] [nvarchar](10) NOT NULL,
    [CARDTYPEID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [BINFROM] [nvarchar](20) NULL,
    [BINTO] [nvarchar](20) NULL,
    [BINLENGTH] [int] NULL,
    [CHECKMODULUS] [int] NULL,
    [CHECKEXPDATE] [int] NULL,
    [PROCESSLOCALLY] [int] NULL,
    [TENDERTYPEID] [nvarchar](10) NULL,
    [ISSUER] [nvarchar](50) NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
    [ISDEBETCARD] [int] NULL,
    [ALLOWMANUALINPUT] [int] NULL,
    [ISTENDER] [int] NULL,
 CONSTRAINT [PK_POSISCARDTABLE] PRIMARY KEY CLUSTERED
(
    [STOREID] ASC,
    [CARDTYPEID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__STORE__48668981]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__STORE__48668981]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__CARDT__4A4ED1F3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__CARDT__4A4ED1F3]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARDT__NAME__4B42F62C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARDT__NAME__4B42F62C]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__ACCOU__4C371A65]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__ACCOU__4C371A65]  DEFAULT ((0)) FOR [BINFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__ACCOU__4D2B3E9E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__ACCOU__4D2B3E9E]  DEFAULT ('') FOR [BINTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__COUNT__4E1F62D7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__COUNT__4E1F62D7]  DEFAULT ((0)) FOR [BINLENGTH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__ALLOW__50FBCF82]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__ALLOW__50FBCF82]  DEFAULT ((0)) FOR [CHECKMODULUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__MANUA__51EFF3BB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__MANUA__51EFF3BB]  DEFAULT ((0)) FOR [CHECKEXPDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__CARDN__52E417F4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__CARDN__52E417F4]  DEFAULT ((0)) FOR [PROCESSLOCALLY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__TENDE__495AADBA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__TENDE__495AADBA]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__MODIF__57A8CD11]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__MODIF__57A8CD11]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__MODIF__589CF14A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__MODIF__589CF14A]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__MODIF__59911583]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__MODIF__59911583]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCARD__DATAA__5A8539BC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF__POSISCARD__DATAA__5A8539BC]  DEFAULT ('DAT') FOR [DATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISCARDTABLE_ISDEBETCARD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF_POSISCARDTABLE_ISDEBETCARD]  DEFAULT ((0)) FOR [ISDEBETCARD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISCARDTABLE_ALLOWMANUALINPUT]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF_POSISCARDTABLE_ALLOWMANUALINPUT]  DEFAULT ((0)) FOR [ALLOWMANUALINPUT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISCARDTABLE_ISTENDER]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCARDTABLE] ADD  CONSTRAINT [DF_POSISCARDTABLE_ISTENDER]  DEFAULT ((0)) FOR [ISTENDER]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSISCTRLLAYOUT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISCTRLLAYOUT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISCTRLLAYOUT](
    [LAYOUTID] [nvarchar](50) NOT NULL,
    [LAYOUTTEXT] [nvarchar](50) NULL,
    [CONTROLXML] [text] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_POSISCTRLLAYOUT] PRIMARY KEY CLUSTERED
(
    [LAYOUTID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCTRL__CONTR__464936E5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCTRLLAYOUT] ADD  CONSTRAINT [DF__POSISCTRL__CONTR__464936E5]  DEFAULT ('') FOR [LAYOUTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISCTRL__CONTR__473D5B1E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISCTRLLAYOUT] ADD  CONSTRAINT [DF__POSISCTRL__CONTR__473D5B1E]  DEFAULT ('') FOR [LAYOUTTEXT]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSISCUSTTRANSACTIONS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISCUSTTRANSACTIONS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISCUSTTRANSACTIONS](
    [CUSTOMERID] [nvarchar](10) NOT NULL,
    [TRANSDATE] [datetime] NOT NULL,
    [STORE] [nvarchar](10) NOT NULL,
    [TERMINAL] [nvarchar](10) NOT NULL,
    [TRANSACTIONID] [nvarchar](10) NOT NULL,
    [RECEIPTID] [nvarchar](18) NULL,
    [TRANSACTIONTYPE] [int] NULL,
    [AMOUNT] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_POSISCUSTTRANSACTIONS] PRIMARY KEY CLUSTERED
(
    [CUSTOMERID] ASC,
    [TRANSDATE] ASC,
    [STORE] ASC,
    [TERMINAL] ASC,
    [TRANSACTIONID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISERPMAPPING ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISERPMAPPING]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISERPMAPPING](
    [FIELDTYPE] [int] NOT NULL,
    [MAPFROM] [nvarchar](50) NOT NULL,
    [MAPTO] [nvarchar](50) NULL,
    [DATAAREAID] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_POSISERPMAPPING] PRIMARY KEY CLUSTERED
(
    [FIELDTYPE] ASC,
    [MAPFROM] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISINFO ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISINFO]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISINFO](
    [ID] [nvarchar](10) NOT NULL,
    [TEXT] [nvarchar](50) NULL,
 CONSTRAINT [PK_POSISINFO] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISINFO__ID__22FFFAA8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISINFO] ADD CONSTRAINT [DF__POSISINFO__ID__22FFFAA8] DEFAULT ('') FOR [ID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISINFO__TEXT__23F41EE1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISINFO] ADD CONSTRAINT [DF__POSISINFO__TEXT__23F41EE1] DEFAULT ('') FOR [TEXT]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSISKEYBOARDINPUT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISKEYBOARDINPUT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISKEYBOARDINPUT](
    [KEYBOARDMAPPINGID] [nvarchar](10) NOT NULL,
    [ASCIIVALUE] [int] NOT NULL,
    [KEYCHAR] [nvarchar](10) NOT NULL,
    [ACTION] [int] NULL,
    [ACTIONPROPERTY] [nvarchar](50) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_POSISKEYBOARDINPUT_1] PRIMARY KEY CLUSTERED
(
    [KEYBOARDMAPPINGID] ASC,
    [ASCIIVALUE] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISPOSCONTROLLERSETTINGS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISPOSCONTROLLERSETTINGS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISPOSCONTROLLERSETTINGS](
    [STOREID] [nvarchar](10) NOT NULL,
    [EODCONTROLFILEDIR] [nvarchar](255) NULL,
    [EODSTARTFILE] [nvarchar](50) NULL,
    [EODINFOFILE] [nvarchar](50) NULL,
    [EODPROGRESSFILE] [nvarchar](50) NULL,
    [EODTERMINATEDFILE] [nvarchar](50) NULL,
    [EODTIMEOUT] [int] NULL,
    [ERPINTERVALTIMEOUT] [int] NULL,
    [ERPSOURCEPATH] [nvarchar](255) NULL,
    [ERPDESTINATIONPATH] [nvarchar](255) NULL,
    [EODFILEPATH] [nvarchar](255) NULL,
    [EODFILENAME] [nvarchar](50) NULL,
    [MAXNUMBEROFLINESINBATCH] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [EODOREOSNEEDED] [int] NULL,
    [AUTOMATICEODTIME] [int] NULL,
    [AUTOMATICEODENBLED] [int] NULL,
    [SKIPNONESALETRANSACTION] [int] NULL,
    [JOINTENDERANDCARDID] [int] NULL,
    [APPENDEODFILE] [int] NULL,
    [MOVEEODFILE] [int] NULL,
    [MOVEEODFILEPATH] [nvarchar](255) NULL,
 CONSTRAINT [PK_POSISPOSCONTROLLERSETTINGS] PRIMARY KEY CLUSTERED
(
    [STOREID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISPOSCONTROLLERSETTINGS_EODANDEOSISNOTNEEDED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISPOSCONTROLLERSETTINGS] ADD  CONSTRAINT [DF_POSISPOSCONTROLLERSETTINGS_EODANDEOSISNOTNEEDED]  DEFAULT ((1)) FOR [EODOREOSNEEDED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISPOSCONTROLLERSETTINGS_AUTOMATICEODTIME]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISPOSCONTROLLERSETTINGS] ADD  CONSTRAINT [DF_POSISPOSCONTROLLERSETTINGS_AUTOMATICEODTIME]  DEFAULT ((0)) FOR [AUTOMATICEODTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISPOSCONTROLLERSETTINGS_SKIPNONESALETRANSACTION]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISPOSCONTROLLERSETTINGS] ADD  CONSTRAINT [DF_POSISPOSCONTROLLERSETTINGS_SKIPNONESALETRANSACTION]  DEFAULT ((0)) FOR [SKIPNONESALETRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISPOSCONTROLLERSETTINGS_JOINTENDERANDCARDID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISPOSCONTROLLERSETTINGS] ADD  CONSTRAINT [DF_POSISPOSCONTROLLERSETTINGS_JOINTENDERANDCARDID]  DEFAULT ((0)) FOR [JOINTENDERANDCARDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISPOSCONTROLLERSETTINGS_APPENDEODFILE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISPOSCONTROLLERSETTINGS] ADD  CONSTRAINT [DF_POSISPOSCONTROLLERSETTINGS_APPENDEODFILE]  DEFAULT ((0)) FOR [APPENDEODFILE]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSISPOSSTATUS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISPOSSTATUS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISPOSSTATUS](
    [POSID] [nvarchar](10) NOT NULL,
    [ACTIVE] [int] NULL,
    [LATESTBATCHID] [int] NULL,
    [STATUS] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [SQLSERVERNAME] [nvarchar](50) NULL,
    [DATABASENAME] [nvarchar](50) NULL,
    [USERNAME] [nvarchar](50) NULL,
    [PASSWORD] [nvarchar](50) NULL,
 CONSTRAINT [PK_POSISPOSSTATUS] PRIMARY KEY NONCLUSTERED
(
    [POSID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[POSISPOSSTATUS]') AND name = N'POSIDDATAAREAID')
CREATE CLUSTERED INDEX [POSIDDATAAREAID] ON [dbo].[POSISPOSSTATUS]
(
    [POSID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISPOSS__DATAA__6E57283F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISPOSSTATUS] ADD  CONSTRAINT [DF__POSISPOSS__DATAA__6E57283F]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSISREPLICATORHISTORY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISREPLICATORHISTORY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISREPLICATORHISTORY](
    [ID] [int] NOT NULL,
    [BATCHID] [int] NULL,
    [POSID] [nvarchar](10) NULL,
    [TRANSACTIONID] [nvarchar](10) NULL,
    [MESSAGE] [nvarchar](200) NULL,
    [LATESTBATCHID] [int] NULL,
    [FLOWID] [int] NULL,
    [MESSAGEDATE] [datetime] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_POSISREPLICATORHISTORY] PRIMARY KEY CLUSTERED
(
    [ID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISREPLICATORSTATUS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISREPLICATORSTATUS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISREPLICATORSTATUS](
    [REPSTATUSID] [int] NOT NULL,
    [DATAPUSHTEXT] [nvarchar](250) NULL,
    [DATAPULLTEXT] [nvarchar](250) NULL,
    [CLEANUPTEXT] [nvarchar](250) NULL,
    [DATAPUSHSTATUS] [int] NULL,
    [DATAPULLSTATUS] [int] NULL,
    [CLEANUPSTATUS] [int] NULL,
    [STATUSTIME] [datetime] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_POSISREPLICATORSTATUS] PRIMARY KEY CLUSTERED
(
    [REPSTATUSID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISRFIDTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISRFIDTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISRFIDTABLE](
    [RFID] [nvarchar](24) NOT NULL,
    [TRANSACTIONID] [nvarchar](10) NULL,
    [SCANNEDTIME] [datetime] NULL,
 CONSTRAINT [PK_POSISRFIDTABLE] PRIMARY KEY CLUSTERED
(
    [RFID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSISRFIDTABLE_SCANNEDTIME]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSISRFIDTABLE] ADD  CONSTRAINT [DF_POSISRFIDTABLE_SCANNEDTIME]  DEFAULT (getdate()) FOR [SCANNEDTIME]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSISTABLELIST ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISTABLELIST]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISTABLELIST](
    [TABLENAME] [nvarchar](50) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_POSISTABLELIST] PRIMARY KEY CLUSTERED
(
    [TABLENAME] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISTENDERRESTRICTIONS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISTENDERRESTRICTIONS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISTENDERRESTRICTIONS](
    [TENDERID] [int] NOT NULL,
    [RESTRICTIONID] [int] NOT NULL,
    [ITEMORGROUPID] [nvarchar](20) NOT NULL,
    [TYPE] [int] NOT NULL,
    [INCLUDE] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_POSISTENDERRESTRICTIONS] PRIMARY KEY CLUSTERED
(
    [TENDERID] ASC,
    [RESTRICTIONID] ASC,
    [ITEMORGROUPID] ASC,
    [TYPE] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISTESTPROCESSES ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISTESTPROCESSES]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISTESTPROCESSES](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [TESTID] [int] NOT NULL,
    [PROCESSID] [int] NOT NULL,
    [EXTRAINFO] [nvarchar](50) NULL,
    [TIMETOWAIT] [int] NULL,
    [ITEMLINEID] [int] NULL,
    [TENDERLINEID] [int] NULL,
    [NUMPADQUANTITY] [numeric](28, 12) NULL,
    [NUMPADVALUE] [nvarchar](50) NULL,
 CONSTRAINT [PK_POSISTESTPROCESSES] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISTESTS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISTESTS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISTESTS](
    [TESTID] [int] IDENTITY(1,1) NOT NULL,
    [NAME] [nvarchar](50) NULL,
    [ITERATIONS] [int] NOT NULL,
 CONSTRAINT [PK_POSISTESTS] PRIMARY KEY CLUSTERED
(
    [TESTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISUPDATETERMINALLIST ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISUPDATETERMINALLIST]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISUPDATETERMINALLIST](
    [UPDATEID] [nvarchar](10) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [SCHEDULEDUPDATEDATE] [datetime] NULL,
    [SCHEDULEDUPDATETIME] [int] NULL,
    [STATUS] [int] NULL,
    [DATEOFUPDATE] [datetime] NULL,
    [TIMEOFUPDATE] [int] NULL,
    [ERRORMESSAGE] [nvarchar](100) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_POSISUPDATETERMINALLIST] PRIMARY KEY CLUSTERED
(
    [UPDATEID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSISVOLUMENO ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSISVOLUMENO]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSISVOLUMENO](
    [VOLUMENO] [nvarchar](50) NULL,
    [COMPANY] [nvarchar](50) NULL
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table POSLOOKUPTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSLOOKUPTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSLOOKUPTABLE](
    [LOOKUPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DEFAULTCOMMANDID] [nvarchar](10) NULL,
    [MENUID] [nvarchar](10) NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20066LOOKUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [LOOKUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUP__LOOKU__228E26B8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUP__LOOKU__228E26B8]  DEFAULT ('') FOR [LOOKUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUPT__NAME__23824AF1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUPT__NAME__23824AF1]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUP__DEFAU__24766F2A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUP__DEFAU__24766F2A]  DEFAULT ('') FOR [DEFAULTCOMMANDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUP__MENUI__256A9363]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUP__MENUI__256A9363]  DEFAULT ('') FOR [MENUID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUP__MODIF__265EB79C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUP__MODIF__265EB79C]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUP__MODIF__2752DBD5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUP__MODIF__2752DBD5]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUP__MODIF__2847000E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUP__MODIF__2847000E]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSLOOKUP__DATAA__293B2447]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSLOOKUPTABLE] ADD  CONSTRAINT [DF__POSLOOKUP__DATAA__293B2447]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSMACROLINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSMACROLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSMACROLINE](
    [PROFILEID] [nvarchar](10) NOT NULL,
    [MACROID] [nvarchar](10) NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [COMMANDID] [nvarchar](10) NULL,
    [NAME] [nvarchar](30) NULL,
    [PARAMETERTYPE] [int] NULL,
    [PARAMETER] [nvarchar](50) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20067PROFILEMACROLINEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PROFILEID] ASC,
    [MACROID] ASC,
    [LINENUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROL__PROFI__2D0BB52B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROL__PROFI__2D0BB52B]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROL__MACRO__2DFFD964]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROL__MACRO__2DFFD964]  DEFAULT ('') FOR [MACROID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROL__LINEN__2EF3FD9D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROL__LINEN__2EF3FD9D]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROL__COMMA__2FE821D6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROL__COMMA__2FE821D6]  DEFAULT ('') FOR [COMMANDID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROLI__NAME__30DC460F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROLI__NAME__30DC460F]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROL__PARAM__31D06A48]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROL__PARAM__31D06A48]  DEFAULT ((0)) FOR [PARAMETERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROL__PARAM__32C48E81]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROL__PARAM__32C48E81]  DEFAULT ('') FOR [PARAMETER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROL__DATAA__33B8B2BA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROLINE] ADD  CONSTRAINT [DF__POSMACROL__DATAA__33B8B2BA]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSMACROTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSMACROTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSMACROTABLE](
    [PROFILEID] [nvarchar](10) NOT NULL,
    [MACROID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20068PROFILEMACROIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PROFILEID] ASC,
    [MACROID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROT__PROFI__3789439E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROTABLE] ADD  CONSTRAINT [DF__POSMACROT__PROFI__3789439E]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROT__MACRO__387D67D7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROTABLE] ADD  CONSTRAINT [DF__POSMACROT__MACRO__387D67D7]  DEFAULT ('') FOR [MACROID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROTA__NAME__39718C10]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROTABLE] ADD  CONSTRAINT [DF__POSMACROTA__NAME__39718C10]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMACROT__DATAA__3A65B049]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMACROTABLE] ADD  CONSTRAINT [DF__POSMACROT__DATAA__3A65B049]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSMENULINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSMENULINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSMENULINE](
    [PROFILEID] [nvarchar](10) NOT NULL,
    [MENUID] [nvarchar](10) NOT NULL,
    [KEYNUM] [int] NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [COMMAND] [nvarchar](10) NULL,
    [PARAMETER] [nvarchar](50) NULL,
    [PARAMETERTYPE] [int] NULL,
    [POSTCOMMAND] [nvarchar](10) NULL,
    [POSTCOMMANDPARAMETER] [nvarchar](50) NULL,
    [POSTCOMMANDPARAMETERTYPE] [int] NULL,
    [FONTNAME] [nvarchar](32) NULL,
    [FONTSIZE] [int] NULL,
    [FONTBOLD] [int] NULL,
    [FORECOLOR] [int] NULL,
    [BACKCOLOR] [int] NULL,
    [FONTITALIC] [int] NULL,
    [GLYPH] [int] NULL,
    [DISABLED] [int] NULL,
    [HELPID] [nvarchar](10) NULL,
    [PICTURE] [image] NULL,
    [PICTUREPOSITION] [int] NULL,
    [PICTUREFILE] [nvarchar](260) NULL,
    [HIDEDESCRIPTION] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20069PROFILEMENUKEYIDX] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [PROFILEID] ASC,
    [MENUID] ASC,
    [KEYNUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__PROFI__3E36412D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__PROFI__3E36412D]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__MENUI__3F2A6566]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__MENUI__3F2A6566]  DEFAULT ('') FOR [MENUID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__KEYNU__401E899F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__KEYNU__401E899F]  DEFAULT ((0)) FOR [KEYNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULIN__NAME__4112ADD8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULIN__NAME__4112ADD8]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__COMMA__4206D211]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__COMMA__4206D211]  DEFAULT ('') FOR [COMMAND]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__PARAM__42FAF64A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__PARAM__42FAF64A]  DEFAULT ('') FOR [PARAMETER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__PARAM__43EF1A83]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__PARAM__43EF1A83]  DEFAULT ((0)) FOR [PARAMETERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__POSTC__44E33EBC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__POSTC__44E33EBC]  DEFAULT ('') FOR [POSTCOMMAND]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__POSTC__45D762F5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__POSTC__45D762F5]  DEFAULT ('') FOR [POSTCOMMANDPARAMETER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__POSTC__46CB872E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__POSTC__46CB872E]  DEFAULT ((0)) FOR [POSTCOMMANDPARAMETERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__FONTN__47BFAB67]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__FONTN__47BFAB67]  DEFAULT ('') FOR [FONTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__FONTS__48B3CFA0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__FONTS__48B3CFA0]  DEFAULT ((0)) FOR [FONTSIZE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__FONTB__49A7F3D9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__FONTB__49A7F3D9]  DEFAULT ((0)) FOR [FONTBOLD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__FOREC__4A9C1812]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__FOREC__4A9C1812]  DEFAULT ((0)) FOR [FORECOLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__BACKC__4B903C4B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__BACKC__4B903C4B]  DEFAULT ((0)) FOR [BACKCOLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__FONTI__4C846084]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__FONTI__4C846084]  DEFAULT ((0)) FOR [FONTITALIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__GLYPH__4D7884BD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__GLYPH__4D7884BD]  DEFAULT ((0)) FOR [GLYPH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__DISAB__4E6CA8F6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__DISAB__4E6CA8F6]  DEFAULT ((0)) FOR [DISABLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__HELPI__4F60CD2F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__HELPI__4F60CD2F]  DEFAULT ('') FOR [HELPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__PICTU__5054F168]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__PICTU__5054F168]  DEFAULT (NULL) FOR [PICTURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__PICTU__514915A1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__PICTU__514915A1]  DEFAULT ((0)) FOR [PICTUREPOSITION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__PICTU__523D39DA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__PICTU__523D39DA]  DEFAULT ('') FOR [PICTUREFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__HIDED__53315E13]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__HIDED__53315E13]  DEFAULT ((0)) FOR [HIDEDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENULI__DATAA__5425824C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENULINE] ADD  CONSTRAINT [DF__POSMENULI__DATAA__5425824C]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSMENUTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSMENUTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSMENUTABLE](
    [PROFILEID] [nvarchar](10) NOT NULL,
    [MENUID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [TYPE] [int] NULL,
    [CAPTION] [nvarchar](30) NULL,
    [MAPENTERTO] [nvarchar](10) NULL,
    [MAPPARAMETER] [nvarchar](50) NULL,
    [MAPPARAMETERTYPE] [int] NULL,
    [COLUMNS] [int] NULL,
    [ROWS_] [int] NULL,
    [HIDETOPLINE] [int] NULL,
    [MANAGERKEY] [int] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20070PROFILEMENUIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PROFILEID] ASC,
    [MENUID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__PROFI__57F61330]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__PROFI__57F61330]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MENUI__58EA3769]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MENUI__58EA3769]  DEFAULT ('') FOR [MENUID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTAB__NAME__59DE5BA2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTAB__NAME__59DE5BA2]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTAB__TYPE__5AD27FDB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTAB__TYPE__5AD27FDB]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__CAPTI__5BC6A414]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__CAPTI__5BC6A414]  DEFAULT ('') FOR [CAPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MAPEN__5CBAC84D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MAPEN__5CBAC84D]  DEFAULT ('') FOR [MAPENTERTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MAPPA__5DAEEC86]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MAPPA__5DAEEC86]  DEFAULT ('') FOR [MAPPARAMETER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MAPPA__5EA310BF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MAPPA__5EA310BF]  DEFAULT ((0)) FOR [MAPPARAMETERTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__COLUM__5F9734F8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__COLUM__5F9734F8]  DEFAULT ((0)) FOR [COLUMNS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__ROWS___608B5931]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__ROWS___608B5931]  DEFAULT ((0)) FOR [ROWS_]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__HIDET__617F7D6A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__HIDET__617F7D6A]  DEFAULT ((0)) FOR [HIDETOPLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MANAG__6273A1A3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MANAG__6273A1A3]  DEFAULT ((0)) FOR [MANAGERKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MODIF__6367C5DC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MODIF__6367C5DC]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MODIF__645BEA15]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MODIF__645BEA15]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__MODIF__65500E4E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__MODIF__65500E4E]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMENUTA__DATAA__66443287]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMENUTABLE] ADD  CONSTRAINT [DF__POSMENUTA__DATAA__66443287]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSMIXANDMATCHTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSMIXANDMATCHTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSMIXANDMATCHTRANS](
    [RECEIPTID] [nvarchar](18) NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [COUNTER] [int] NOT NULL,
    [GROUPID] [nvarchar](10) NULL,
    [STOREID] [nvarchar](10) NULL,
    [TRANSDATE] [datetime] NULL,
    [TRANSTIME] [int] NULL,
    [DISCAMOUNT] [numeric](28, 12) NULL,
    [QTY] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_POSMIXANDMATCHTRANS] PRIMARY KEY CLUSTERED
(
    [RECEIPTID] ASC,
    [LINENUM] ASC,
    [COUNTER] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__RECEI__6A14C36B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__RECEI__6A14C36B]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__LINEN__6B08E7A4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__LINEN__6B08E7A4]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__COUNT__6BFD0BDD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__COUNT__6BFD0BDD]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__GROUP__6CF13016]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__GROUP__6CF13016]  DEFAULT ('') FOR [GROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__STORE__6DE5544F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__STORE__6DE5544F]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__TRANS__6ED97888]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__TRANS__6ED97888]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__TRANS__6FCD9CC1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__TRANS__6FCD9CC1]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__DISCA__70C1C0FA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__DISCA__70C1C0FA]  DEFAULT ((0)) FOR [DISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXANDMA__QTY__71B5E533]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXANDMA__QTY__71B5E533]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSMIXAND__DATAA__72AA096C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSMIXANDMATCHTRANS] ADD  CONSTRAINT [DF__POSMIXAND__DATAA__72AA096C]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view POSMULTIBUYDISCOUNTLINE ..'
GO
IF OBJECT_ID(N'[dbo].[POSMULTIBUYDISCOUNTLINE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[POSMULTIBUYDISCOUNTLINE]
GO
CREATE VIEW [dbo].POSMULTIBUYDISCOUNTLINE AS
(
  SELECT
    [MULTIBUYID] AS 'OFFERID',
    [QTYLOWEST] AS 'MINQUANTITY',
    [PRICEDISCPCT] AS 'UNITPRICEORDISCPCT',
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILMULTIBUYDISCOUNTLINE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table POSOPOSMESSAGE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSOPOSMESSAGE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSOPOSMESSAGE](
    [MODULEID] [nvarchar](10) NOT NULL,
    [RESULTCODE] [int] NOT NULL,
    [RESULTCODEEXTENDED] [int] NOT NULL,
    [MESSAGELINE1] [nvarchar](50) NULL,
    [MESSAGELINE2] [nvarchar](50) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20072MODULERESULTIDX] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [MODULEID] ASC,
    [RESULTCODE] ASC,
    [RESULTCODEEXTENDED] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSOPOSME__MODUL__75867617]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSOPOSMESSAGE] ADD  CONSTRAINT [DF__POSOPOSME__MODUL__75867617]  DEFAULT ('') FOR [MODULEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSOPOSME__RESUL__767A9A50]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSOPOSMESSAGE] ADD  CONSTRAINT [DF__POSOPOSME__RESUL__767A9A50]  DEFAULT ((0)) FOR [RESULTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSOPOSME__RESUL__776EBE89]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSOPOSMESSAGE] ADD  CONSTRAINT [DF__POSOPOSME__RESUL__776EBE89]  DEFAULT ((0)) FOR [RESULTCODEEXTENDED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSOPOSME__MESSA__7862E2C2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSOPOSMESSAGE] ADD  CONSTRAINT [DF__POSOPOSME__MESSA__7862E2C2]  DEFAULT ('') FOR [MESSAGELINE1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSOPOSME__MESSA__795706FB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSOPOSMESSAGE] ADD  CONSTRAINT [DF__POSOPOSME__MESSA__795706FB]  DEFAULT ('') FOR [MESSAGELINE2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSOPOSME__DATAA__7A4B2B34]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSOPOSMESSAGE] ADD  CONSTRAINT [DF__POSOPOSME__DATAA__7A4B2B34]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSPRINTSETUPLINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSPRINTSETUPLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSPRINTSETUPLINE](
    [PRINTSETUPID] [nvarchar](10) NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [TXT] [nvarchar](50) NULL,
    [ALIGNMENT] [int] NULL,
    [WIDE] [int] NULL,
    [HIGH] [int] NULL,
    [BOLD] [int] NULL,
    [ITALIC] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20073PRINTSETUPLINEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PRINTSETUPID] ASC,
    [LINENUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__PRINT__7E1BBC18]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTS__PRINT__7E1BBC18]  DEFAULT ('') FOR [PRINTSETUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__LINEN__7F0FE051]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTS__LINEN__7F0FE051]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTSET__TXT__0004048A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTSET__TXT__0004048A]  DEFAULT ('') FOR [TXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__ALIGN__00F828C3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTS__ALIGN__00F828C3]  DEFAULT ((0)) FOR [ALIGNMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTSE__WIDE__01EC4CFC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTSE__WIDE__01EC4CFC]  DEFAULT ((0)) FOR [WIDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTSE__HIGH__02E07135]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTSE__HIGH__02E07135]  DEFAULT ((0)) FOR [HIGH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTSE__BOLD__03D4956E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTSE__BOLD__03D4956E]  DEFAULT ((0)) FOR [BOLD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__ITALI__04C8B9A7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTS__ITALI__04C8B9A7]  DEFAULT ((0)) FOR [ITALIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__DATAA__05BCDDE0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPLINE] ADD  CONSTRAINT [DF__POSPRINTS__DATAA__05BCDDE0]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSPRINTSETUPTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSPRINTSETUPTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSPRINTSETUPTABLE](
    [PRINTSETUPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [TYPE] [int] NULL,
    [ROTATION] [int] NULL,
    [NUMBEROFEXTRAPRINTS] [int] NULL,
    [PRINTHEADER] [int] NULL,
    [PRINTFOOTER] [int] NULL,
    [PRINTFOREACHUNIT] [int] NULL,
    [DOCUMENTINPRINTER] [nvarchar](30) NULL,
    [PRINTINFOCODES] [int] NULL,
    [PRINTIFRETURN] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20074PRINTSETUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PRINTSETUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__PRINT__098D6EC4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__PRINT__098D6EC4]  DEFAULT ('') FOR [PRINTSETUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTSE__NAME__0A8192FD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTSE__NAME__0A8192FD]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTSE__TYPE__0B75B736]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTSE__TYPE__0B75B736]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__ROTAT__0C69DB6F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__ROTAT__0C69DB6F]  DEFAULT ((0)) FOR [ROTATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__NUMBE__0D5DFFA8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__NUMBE__0D5DFFA8]  DEFAULT ((0)) FOR [NUMBEROFEXTRAPRINTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__PRINT__0E5223E1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__PRINT__0E5223E1]  DEFAULT ((0)) FOR [PRINTHEADER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__PRINT__0F46481A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__PRINT__0F46481A]  DEFAULT ((0)) FOR [PRINTFOOTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__PRINT__103A6C53]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__PRINT__103A6C53]  DEFAULT ((0)) FOR [PRINTFOREACHUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__DOCUM__112E908C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__DOCUM__112E908C]  DEFAULT ('') FOR [DOCUMENTINPRINTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__PRINT__1222B4C5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__PRINT__1222B4C5]  DEFAULT ((0)) FOR [PRINTINFOCODES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__PRINT__1316D8FE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__PRINT__1316D8FE]  DEFAULT ((0)) FOR [PRINTIFRETURN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTS__DATAA__140AFD37]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTSETUPTABLE] ADD  CONSTRAINT [DF__POSPRINTS__DATAA__140AFD37]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSPRINTVARIABLETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSPRINTVARIABLETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSPRINTVARIABLETABLE](
    [VARIABLEID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20075VARIABLEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [VARIABLEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTV__VARIA__17DB8E1B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTVARIABLETABLE] ADD  CONSTRAINT [DF__POSPRINTV__VARIA__17DB8E1B]  DEFAULT ('') FOR [VARIABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTVA__NAME__18CFB254]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTVARIABLETABLE] ADD  CONSTRAINT [DF__POSPRINTVA__NAME__18CFB254]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPRINTV__DATAA__19C3D68D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPRINTVARIABLETABLE] ADD  CONSTRAINT [DF__POSPRINTV__DATAA__19C3D68D]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSPURCHASEORDERRECEIPT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSPURCHASEORDERRECEIPT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSPURCHASEORDERRECEIPT](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [PONUMBER] [nvarchar](50) NOT NULL,
    [RECEIPTNUMBER] [nvarchar](50) NOT NULL,
    [DRIVERDETAILS] [nvarchar](50) NOT NULL,
    [DELIVERYNOTENUMBER] [nvarchar](50) NOT NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL,
    [STATUS] [int] NOT NULL,
    [ORDERTYPE] [int] NOT NULL,
 CONSTRAINT [PK_POSPURCHASEORDERRECEIPT] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPT_PoNumber]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPT] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPT_PoNumber]  DEFAULT ('') FOR [PONUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPT_ReceiptNumber]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPT] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPT_ReceiptNumber]  DEFAULT ('') FOR [RECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPT_DriverDetails]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPT] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPT_DriverDetails]  DEFAULT ('') FOR [DRIVERDETAILS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPT_DeliveryNoteNumber]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPT] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPT_DeliveryNoteNumber]  DEFAULT ('') FOR [DELIVERYNOTENUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPURCHA__DELIV__4F48913A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPT] ADD CONSTRAINT [DF__POSPURCHA__DELIV__4F48913A] DEFAULT ('') FOR [DELIVERYMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPT_Status]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPT] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPT_Status]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPURCHA__ORDER__5130D9AC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPT] ADD CONSTRAINT [DF__POSPURCHA__ORDER__5130D9AC] DEFAULT ((0)) FOR [ORDERTYPE]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSPURCHASEORDERRECEIPTLINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSPURCHASEORDERRECEIPTLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [PONUMBER] [nvarchar](50) NULL,
    [RECEIPTNUMBER] [nvarchar](50) NULL,
    [LINERECEIPTNUMBER] [nvarchar](20) NULL,
    [GUID] [nvarchar](50) NULL,
    [ITEMNUMBER] [nvarchar](20) NULL,
    [ITEMNAME] [nvarchar](60) NULL,
    [QUANTITYORDERED] [numeric](28, 12) NULL,
    [QUANTITYRECEIVED] [numeric](28, 12) NULL,
    [QUANTITYRECEIVEDNOW] [numeric](28, 12) NULL,
    [RECEIPTDATE] [datetime] NULL,
    [USERID] [nvarchar](10) NULL,
    [UNIT] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [STATUS] [int] NULL,
    [INVENTSIZEID] [nvarchar](10) NULL,
    [INVENTCOLORID] [nvarchar](10) NULL,
    [INVENTSTYLEID] [nvarchar](10) NULL,
    [CONFIGID] [nvarchar](10) NULL,
    [DELIVERYMETHOD] [nvarchar](60) NOT NULL,
 CONSTRAINT [PK_POSPURCHASEORDERRECEIPTLINE] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_PONumber]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_PONumber]  DEFAULT ('') FOR [PONUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_ReceiptNumber]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_ReceiptNumber]  DEFAULT ('') FOR [RECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_LineReceiptNumber]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_LineReceiptNumber]  DEFAULT ('') FOR [LINERECEIPTNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_GUID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_GUID]  DEFAULT ('') FOR [GUID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_ItemNumber]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_ItemNumber]  DEFAULT ('') FOR [ITEMNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_QuantityOrdered]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_QuantityOrdered]  DEFAULT ((0)) FOR [QUANTITYORDERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_QuantityReceived]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_QuantityReceived]  DEFAULT ((0)) FOR [QUANTITYRECEIVED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_QuantityReceivedNow]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_QuantityReceivedNow]  DEFAULT ((0)) FOR [QUANTITYRECEIVEDNOW]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_ReceiptDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_ReceiptDate]  DEFAULT (getdate()) FOR [RECEIPTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_UserID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_UserID]  DEFAULT ('') FOR [USERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_Unit]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_Unit]  DEFAULT ('') FOR [UNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_TerminalID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_TerminalID]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_POSPURCHASEORDERRECEIPTLINE_Status]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD  CONSTRAINT [DF_POSPURCHASEORDERRECEIPTLINE_Status]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPURCHA__INVEN__44CB02C7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD CONSTRAINT [DF__POSPURCHA__INVEN__44CB02C7] DEFAULT ('') FOR [INVENTSIZEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPURCHA__INVEN__45BF2700]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD CONSTRAINT [DF__POSPURCHA__INVEN__45BF2700] DEFAULT ('') FOR [INVENTCOLORID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPURCHA__INVEN__46B34B39]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD CONSTRAINT [DF__POSPURCHA__INVEN__46B34B39] DEFAULT ('') FOR [INVENTSTYLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPURCHA__CONFI__47A76F72]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD CONSTRAINT [DF__POSPURCHA__CONFI__47A76F72] DEFAULT ('') FOR [CONFIGID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSPURCHA__DELIV__489B93AB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSPURCHASEORDERRECEIPTLINE] ADD CONSTRAINT [DF__POSPURCHA__DELIV__489B93AB] DEFAULT ('') FOR [DELIVERYMETHOD]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSRUNOBJECT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSRUNOBJECT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSRUNOBJECT](
    [RUNOBJECTID] [nvarchar](10) NOT NULL,
    [OBJECTTYPE] [int] NULL,
    [OBJECTNAME] [nvarchar](40) NULL,
    [MANAGERKEY] [int] NULL,
    [MODAL] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_POSRUNOBJECT] PRIMARY KEY CLUSTERED
(
    [RUNOBJECTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSRUNOBJ__RUNOB__1D946771]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSRUNOBJECT] ADD  CONSTRAINT [DF__POSRUNOBJ__RUNOB__1D946771]  DEFAULT ('') FOR [RUNOBJECTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSRUNOBJ__OBJEC__1E888BAA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSRUNOBJECT] ADD  CONSTRAINT [DF__POSRUNOBJ__OBJEC__1E888BAA]  DEFAULT ((0)) FOR [OBJECTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSRUNOBJ__OBJEC__1F7CAFE3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSRUNOBJECT] ADD  CONSTRAINT [DF__POSRUNOBJ__OBJEC__1F7CAFE3]  DEFAULT ('') FOR [OBJECTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSRUNOBJ__MANAG__2070D41C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSRUNOBJECT] ADD  CONSTRAINT [DF__POSRUNOBJ__MANAG__2070D41C]  DEFAULT ((0)) FOR [MANAGERKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSRUNOBJ__MODAL__2164F855]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSRUNOBJECT] ADD  CONSTRAINT [DF__POSRUNOBJ__MODAL__2164F855]  DEFAULT ((0)) FOR [MODAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSRUNOBJ__DATAA__22591C8E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSRUNOBJECT] ADD  CONSTRAINT [DF__POSRUNOBJ__DATAA__22591C8E]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view POSSEEDVALUES ..'
GO
IF OBJECT_ID(N'[dbo].[POSSEEDVALUES]', N'V') IS NOT NULL
    DROP VIEW [dbo].[POSSEEDVALUES]
GO
CREATE VIEW [dbo].POSSEEDVALUES AS
(
  SELECT
    [DATATYPE] AS 'TYPEID',
    [STORENUMBER] AS 'STOREID',
    [TERMINALID],
    [DATAVALUE] AS 'VALUE',
    [DATAAREAID]
  FROM [ax].RETAILPOSSEEDDATA
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table POSSTOCKCOUNT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSSTOCKCOUNT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSSTOCKCOUNT](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [JOURNALID] [nvarchar](50) NOT NULL,
    [RECID] [nvarchar](50) NULL,
    [OPERATIONTYPE] [int] NULL,
    [ITEMNUMBER] [nvarchar](20) NOT NULL,
    [ITEMNAME] [nvarchar](60) NULL,
    [COUNTED] [numeric](28, 12) NULL,
    [QUANTITY] [numeric](28, 12) NULL,
    [UNIT] [nvarchar](10) NULL,
    [USERID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [COUNTDATE] [datetime] NULL,
    [STATUS] [int] NULL,
    [INVENTSIZEID] [nvarchar](10) NULL,
    [INVENTCOLORID] [nvarchar](10) NULL,
    [INVENTSTYLEID] [nvarchar](10) NULL,
    [CONFIGID] [nvarchar](10) NULL,
    [GUID] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_POSSTOCKCOUNT] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSSTOCKC__INVEN__1427CB6C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSSTOCKCOUNT] ADD CONSTRAINT [DF__POSSTOCKC__INVEN__1427CB6C] DEFAULT ('') FOR [INVENTSIZEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSSTOCKC__INVEN__151BEFA5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSSTOCKCOUNT] ADD CONSTRAINT [DF__POSSTOCKC__INVEN__151BEFA5] DEFAULT ('') FOR [INVENTCOLORID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSSTOCKC__INVEN__161013DE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSSTOCKCOUNT] ADD CONSTRAINT [DF__POSSTOCKC__INVEN__161013DE] DEFAULT ('') FOR [INVENTSTYLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSSTOCKC__CONFI__17043817]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSSTOCKCOUNT] ADD CONSTRAINT [DF__POSSTOCKC__CONFI__17043817] DEFAULT ('') FOR [CONFIGID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSSTOCKCOUNTJOURNALS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSSTOCKCOUNTJOURNALS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSSTOCKCOUNTJOURNALS](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RECID] [varchar](50) NOT NULL,
    [JOURNALID] [nvarchar](50) NOT NULL,
    [DESCRIPTION] [nvarchar](60) NULL,
 CONSTRAINT [PK_POSSTOCKCOUNTJOURNALS] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSSTOCKC__RECID__0F63164F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSSTOCKCOUNTJOURNALS] ADD CONSTRAINT [DF__POSSTOCKC__RECID__0F63164F] DEFAULT ('') FOR [RECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSSTOCKC__JOURN__10573A88]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSSTOCKCOUNTJOURNALS] ADD CONSTRAINT [DF__POSSTOCKC__JOURN__10573A88] DEFAULT ('') FOR [JOURNALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSSTOCKC__DESCR__114B5EC1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSSTOCKCOUNTJOURNALS] ADD CONSTRAINT [DF__POSSTOCKC__DESCR__114B5EC1] DEFAULT ('') FOR [DESCRIPTION]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSTABLE](
    [STOREID] [nvarchar](10) NOT NULL,
    [TABLEGROUPID] [nvarchar](10) NOT NULL,
    [POSTABLEID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20077STORETABLEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TABLEGROUPID] ASC,
    [POSTABLEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLE__STOREI__25358939]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLE] ADD  CONSTRAINT [DF__POSTABLE__STOREI__25358939]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLE__TABLEG__2629AD72]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLE] ADD  CONSTRAINT [DF__POSTABLE__TABLEG__2629AD72]  DEFAULT ('') FOR [TABLEGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLE__POSTAB__271DD1AB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLE] ADD  CONSTRAINT [DF__POSTABLE__POSTAB__271DD1AB]  DEFAULT ('') FOR [POSTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLE__DATAAR__2811F5E4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLE] ADD  CONSTRAINT [DF__POSTABLE__DATAAR__2811F5E4]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSTABLEGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSTABLEGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSTABLEGROUP](
    [TABLEGROUPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [CREATEDDATE] [datetime] NULL,
    [CREATEDTIME] [int] NULL,
    [CREATEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20078STOREGROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TABLEGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__TABLE__2BE286C8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__TABLE__2BE286C8]  DEFAULT ('') FOR [TABLEGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEGR__NAME__2CD6AB01]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEGR__NAME__2CD6AB01]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__STORE__2DCACF3A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__STORE__2DCACF3A]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__MODIF__2EBEF373]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__MODIF__2EBEF373]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__MODIF__2FB317AC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__MODIF__2FB317AC]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__MODIF__30A73BE5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__MODIF__30A73BE5]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__CREAT__319B601E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__CREAT__319B601E]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CREATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__CREAT__328F8457]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__CREAT__328F8457]  DEFAULT ((0)) FOR [CREATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__CREAT__3383A890]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__CREAT__3383A890]  DEFAULT ('?') FOR [CREATEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTABLEG__DATAA__3477CCC9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTABLEGROUP] ADD  CONSTRAINT [DF__POSTABLEG__DATAA__3477CCC9]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSTRANSACTION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSTRANSACTION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSTRANSACTION](
    [RECEIPTID] [nvarchar](18) NOT NULL,
    [STAFFID] [nvarchar](10) NULL,
    [STOREID] [nvarchar](10) NULL,
    [NEWTRANSACTION] [int] NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [TRANSACTIONTYPE] [int] NULL,
    [SALEISRETURNSALE] [int] NULL,
    [TRANSACTIONSTATUS] [int] NULL,
    [TRANSDATE] [datetime] NULL,
    [TRANSTIME] [int] NULL,
    [CURRENCY] [nvarchar](3) NULL,
    [EXCHRATE] [numeric](28, 12) NULL,
    [CUSTACCOUNT] [nvarchar](10) NULL,
    [CREATEDONTERMINALID] [nvarchar](10) NULL,
    [SALESSTAFFID] [nvarchar](10) NULL,
    [SUPERVISORRIGHTS] [int] NULL,
    [SHIFTID] [nvarchar](10) NULL,
    [SHIFTDATE] [datetime] NULL,
    [INFOCODEDISCOUNTGROUP] [nvarchar](10) NULL,
    [SALESPAYMENTDIFFERENCE] [numeric](28, 12) NULL,
    [NETAMOUNT] [numeric](28, 12) NULL,
    [COSTAMOUNT] [numeric](28, 12) NULL,
    [GROSSAMOUNT] [numeric](28, 12) NULL,
    [PAYMENTAMOUNT] [numeric](28, 12) NULL,
    [INCOMEEXPENSEAMOUNT] [numeric](28, 12) NULL,
    [SERVICECHARGE] [numeric](28, 12) NULL,
    [MANAGERKEY] [int] NULL,
    [MANAGERID] [nvarchar](10) NULL,
    [LINEDISCOUNTAMOUNT] [numeric](28, 12) NULL,
    [TOTALDISCOUNT] [numeric](28, 12) NULL,
    [NUMBEROFITEMS] [numeric](28, 12) NULL,
    [ROUNDED] [numeric](28, 12) NULL,
    [TAXONDISCOUNT] [numeric](28, 12) NULL,
    [NUMBEROFITEMSLINES] [numeric](28, 12) NULL,
    [NUMBEROFINCOMEEXPENSELINES] [numeric](28, 12) NULL,
    [NUMBEROFPAYMENTLINES] [numeric](28, 12) NULL,
    [NOSALESOPENDRAWER] [int] NULL,
    [RECEIPTPRINTEDFORRETURN] [int] NULL,
    [COUNTER] [numeric](28, 12) NULL,
    [TIMEWHENTOTALPRESSED] [int] NULL,
    [TIMEWHENTRANSACTIONCLOSED] [int] NULL,
    [CUSTIDNUMBER] [nvarchar](10) NULL,
    [POSTASSHIPMENT] [int] NULL,
    [PICTURE] [image] NULL,
    [RETRIEVEDFROMRECEIPTID] [nvarchar](18) NULL,
    [POSTABLEID] [nvarchar](10) NULL,
    [NUMBEROFCOVERS] [int] NULL,
    [INUSEONTILL] [nvarchar](10) NULL,
    [CREATEDBYSTAFFID] [nvarchar](10) NULL,
    [ACTIVEPOSTABLEID] [nvarchar](10) NULL,
    [TABLEGROUP] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20081RECEIPTIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [RECEIPTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__RECEI__4D437A93]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__RECEI__4D437A93]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__STAFF__4E379ECC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__STAFF__4E379ECC]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__STORE__4F2BC305]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__STORE__4F2BC305]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NEWTR__501FE73E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NEWTR__501FE73E]  DEFAULT ((0)) FOR [NEWTRANSACTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TERMI__51140B77]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TERMI__51140B77]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__52082FB0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__52082FB0]  DEFAULT ((0)) FOR [TRANSACTIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SALEI__52FC53E9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__SALEI__52FC53E9]  DEFAULT ((0)) FOR [SALEISRETURNSALE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__53F07822]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__53F07822]  DEFAULT ((0)) FOR [TRANSACTIONSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__54E49C5B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__54E49C5B]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__55D8C094]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__55D8C094]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CURRE__56CCE4CD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__CURRE__56CCE4CD]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__EXCHR__57C10906]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__EXCHR__57C10906]  DEFAULT ((0)) FOR [EXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CUSTA__58B52D3F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__CUSTA__58B52D3F]  DEFAULT ('') FOR [CUSTACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CREAT__59A95178]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__CREAT__59A95178]  DEFAULT ('') FOR [CREATEDONTERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SALES__5A9D75B1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__SALES__5A9D75B1]  DEFAULT ('') FOR [SALESSTAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SUPER__5B9199EA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__SUPER__5B9199EA]  DEFAULT ((0)) FOR [SUPERVISORRIGHTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SHIFT__5C85BE23]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__SHIFT__5C85BE23]  DEFAULT ('') FOR [SHIFTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SHIFT__5D79E25C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__SHIFT__5D79E25C]  DEFAULT ('1900-01-01 00:00:00.000') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INFOC__5E6E0695]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__INFOC__5E6E0695]  DEFAULT ('') FOR [INFOCODEDISCOUNTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SALES__5F622ACE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__SALES__5F622ACE]  DEFAULT ((0)) FOR [SALESPAYMENTDIFFERENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NETAM__60564F07]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NETAM__60564F07]  DEFAULT ((0)) FOR [NETAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COSTA__614A7340]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__COSTA__614A7340]  DEFAULT ((0)) FOR [COSTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__GROSS__623E9779]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__GROSS__623E9779]  DEFAULT ((0)) FOR [GROSSAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PAYME__6332BBB2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__PAYME__6332BBB2]  DEFAULT ((0)) FOR [PAYMENTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INCOM__6426DFEB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__INCOM__6426DFEB]  DEFAULT ((0)) FOR [INCOMEEXPENSEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SERVI__651B0424]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__SERVI__651B0424]  DEFAULT ((0)) FOR [SERVICECHARGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__MANAG__660F285D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__MANAG__660F285D]  DEFAULT ((0)) FOR [MANAGERKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__MANAG__67034C96]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__MANAG__67034C96]  DEFAULT ('') FOR [MANAGERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__LINED__67F770CF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__LINED__67F770CF]  DEFAULT ((0)) FOR [LINEDISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TOTAL__68EB9508]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TOTAL__68EB9508]  DEFAULT ((0)) FOR [TOTALDISCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NUMBE__69DFB941]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NUMBE__69DFB941]  DEFAULT ((0)) FOR [NUMBEROFITEMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ROUND__6AD3DD7A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__ROUND__6AD3DD7A]  DEFAULT ((0)) FOR [ROUNDED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TAXON__6BC801B3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TAXON__6BC801B3]  DEFAULT ((0)) FOR [TAXONDISCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NUMBE__6CBC25EC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NUMBE__6CBC25EC]  DEFAULT ((0)) FOR [NUMBEROFITEMSLINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NUMBE__6DB04A25]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NUMBE__6DB04A25]  DEFAULT ((0)) FOR [NUMBEROFINCOMEEXPENSELINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NUMBE__6EA46E5E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NUMBE__6EA46E5E]  DEFAULT ((0)) FOR [NUMBEROFPAYMENTLINES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NOSAL__6F989297]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NOSAL__6F989297]  DEFAULT ((0)) FOR [NOSALESOPENDRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__RECEI__708CB6D0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__RECEI__708CB6D0]  DEFAULT ((0)) FOR [RECEIPTPRINTEDFORRETURN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COUNT__7180DB09]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__COUNT__7180DB09]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TIMEW__7274FF42]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TIMEW__7274FF42]  DEFAULT ((0)) FOR [TIMEWHENTOTALPRESSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TIMEW__7369237B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TIMEW__7369237B]  DEFAULT ((0)) FOR [TIMEWHENTRANSACTIONCLOSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CUSTI__745D47B4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__CUSTI__745D47B4]  DEFAULT ('') FOR [CUSTIDNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__POSTA__75516BED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__POSTA__75516BED]  DEFAULT ((0)) FOR [POSTASSHIPMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PICTU__76459026]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__PICTU__76459026]  DEFAULT (NULL) FOR [PICTURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__RETRI__7739B45F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__RETRI__7739B45F]  DEFAULT ('') FOR [RETRIEVEDFROMRECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__POSTA__782DD898]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__POSTA__782DD898]  DEFAULT ('') FOR [POSTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NUMBE__7921FCD1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__NUMBE__7921FCD1]  DEFAULT ((0)) FOR [NUMBEROFCOVERS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INUSE__7A16210A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__INUSE__7A16210A]  DEFAULT ('') FOR [INUSEONTILL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CREAT__7B0A4543]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__CREAT__7B0A4543]  DEFAULT ('') FOR [CREATEDBYSTAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ACTIV__7BFE697C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__ACTIV__7BFE697C]  DEFAULT ('') FOR [ACTIVEPOSTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TABLE__7CF28DB5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__TABLE__7CF28DB5]  DEFAULT ('') FOR [TABLEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DATAA__7DE6B1EE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTION] ADD  CONSTRAINT [DF__POSTRANSA__DATAA__7DE6B1EE]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSTRANSACTIONINFOCODETRA20083 ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSTRANSACTIONINFOCODETRA20083]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSTRANSACTIONINFOCODETRA20083](
    [RECEIPTID] [nvarchar](18) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__RECEI__15BE3B7F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRA20083] ADD  CONSTRAINT [DF__POSTRANSA__RECEI__15BE3B7F]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DATAA__16B25FB8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRA20083] ADD  CONSTRAINT [DF__POSTRANSA__DATAA__16B25FB8]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSTRANSACTIONINFOCODETRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSTRANSACTIONINFOCODETRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSTRANSACTIONINFOCODETRANS](
    [STOREID] [nvarchar](10) NULL,
    [RECEIPTID] [nvarchar](18) NOT NULL,
    [TRANSACTIONTYPE] [int] NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [INFOCODEID] [nvarchar](10) NOT NULL,
    [INFORMATION] [nvarchar](10) NULL,
    [INFOAMOUNT] [numeric](28, 12) NULL,
    [TRANSDATE] [datetime] NULL,
    [TRANSTIME] [int] NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [STAFFID] [nvarchar](10) NULL,
    [NO] [nvarchar](10) NULL,
    [AMOUNT] [numeric](28, 12) NULL,
    [INPUTTYPE] [int] NULL,
    [SUBCODEID] [nvarchar](10) NULL,
    [SOURCECODE] [nvarchar](10) NULL,
    [COUNTER] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20082RECEIPTTRANSACTIONIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [RECEIPTID] ASC,
    [TRANSACTIONTYPE] ASC,
    [LINENUM] ASC,
    [INFOCODEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__STORE__01B742D2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__STORE__01B742D2]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__RECEI__02AB670B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__RECEI__02AB670B]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__039F8B44]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__039F8B44]  DEFAULT ((0)) FOR [TRANSACTIONTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__LINEN__0493AF7D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__LINEN__0493AF7D]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INFOC__0587D3B6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__INFOC__0587D3B6]  DEFAULT ('') FOR [INFOCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INFOR__067BF7EF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__INFOR__067BF7EF]  DEFAULT ('') FOR [INFORMATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INFOA__07701C28]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__INFOA__07701C28]  DEFAULT ((0)) FOR [INFOAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__08644061]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__08644061]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__0958649A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__0958649A]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TERMI__0A4C88D3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__TERMI__0A4C88D3]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__STAFF__0B40AD0C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__STAFF__0B40AD0C]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSACTI__NO__0C34D145]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSACTI__NO__0C34D145]  DEFAULT ('') FOR [NO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__AMOUN__0D28F57E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__AMOUN__0D28F57E]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INPUT__0E1D19B7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__INPUT__0E1D19B7]  DEFAULT ((0)) FOR [INPUTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SUBCO__0F113DF0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__SUBCO__0F113DF0]  DEFAULT ('') FOR [SUBCODEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SOURC__10056229]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__SOURC__10056229]  DEFAULT ('') FOR [SOURCECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COUNT__10F98662]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__COUNT__10F98662]  DEFAULT ((0)) FOR [COUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DATAA__11EDAA9B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONINFOCODETRANS] ADD  CONSTRAINT [DF__POSTRANSA__DATAA__11EDAA9B]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table POSTRANSACTIONLINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSTRANSACTIONLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[POSTRANSACTIONLINE](
    [TRANSTYPE] [int] NULL,
    [LINENUM] [numeric](28, 12) NULL,
    [RECEIPTID] [nvarchar](18) NULL,
    [BARCODE] [nvarchar](60) NULL,
    [NUMBER_] [nvarchar](10) NULL,
    [STATUS] [int] NULL,
    [CURRENCY] [nvarchar](3) NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [UNIT] [nvarchar](10) NULL,
    [STOREID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [STAFFID] [nvarchar](10) NULL,
    [PRICE] [numeric](28, 12) NULL,
    [SCALEITEM] [int] NULL,
    [NODISCOUNTALLOWED] [int] NULL,
    [PRICEINBARCODE] [int] NULL,
    [AMOUNT] [numeric](28, 12) NULL,
    [QTY] [numeric](28, 12) NULL,
    [NETPRICE] [numeric](28, 12) NULL,
    [PRICEGROUP] [nvarchar](10) NULL,
    [TAXCODE] [nvarchar](10) NULL,
    [TAXPCT] [numeric](28, 12) NULL,
    [DISCOUNTAMOUNT] [numeric](28, 12) NULL,
    [DISCOUNTPCT] [numeric](28, 12) NULL,
    [COSTAMOUNT] [numeric](28, 12) NULL,
    [COSTPRICE] [numeric](28, 12) NULL,
    [NETAMOUNT] [numeric](28, 12) NULL,
    [TAXAMOUNT] [numeric](28, 12) NULL,
    [AMOUNTMST] [numeric](28, 12) NULL,
    [CARDTYPEID] [nvarchar](10) NULL,
    [CARDCUSTCOUPONITEMID] [nvarchar](10) NULL,
    [TAXGROUP] [nvarchar](10) NULL,
    [ITEMDISCOUNTGROUP] [nvarchar](10) NULL,
    [CARDTRANSID] [int] NULL,
    [COUPONEANORG] [nvarchar](10) NULL,
    [ITEMIDSCANNED] [int] NULL,
    [PRICECHANGE] [int] NULL,
    [WEIGHTMANUALLYENTERED] [int] NULL,
    [QTYINBARCODE] [int] NULL,
    [DISPENSEPRINTING] [int] NULL,
    [LINKEDITEMIDNOTORIGINAL] [int] NULL,
    [ORIGOFALINKEDITEMLIST] [int] NULL,
    [PRICEOVERRIDE] [int] NULL,
    [ITEMDEPARTMENTNEGATIVE] [int] NULL,
    [COUNTASONE] [int] NULL,
    [ITEMPOSTINGGROUP] [nvarchar](10) NULL,
    [TOTALROUNDEDAMOUNT] [numeric](28, 12) NULL,
    [ORIGPRICEINCLTAX] [numeric](28, 12) NULL,
    [ORIGPRICEEXCLTAX] [numeric](28, 12) NULL,
    [PICTURE] [image] NULL,
    [DISCINFOLINENUM] [numeric](28, 12) NULL,
    [DISCOUNTTRIGGERED] [int] NULL,
    [QTYDISCOUNTED] [numeric](28, 12) NULL,
    [PERIODICDISCTYPE] [int] NULL,
    [PERIODICDISCGROUP] [nvarchar](10) NULL,
    [INFOCODEDISCDISABLE] [int] NULL,
    [INFOCODEDISCPCT] [numeric](28, 12) NULL,
    [PERIODICDISCPCT] [numeric](28, 12) NULL,
    [DISCOUNTOFFERID] [nvarchar](10) NULL,
    [MIXANDMATCHLINENUM] [numeric](28, 12) NULL,
    [LINEDISCPCT] [numeric](28, 12) NULL,
    [TOTALDISCPCT] [numeric](28, 12) NULL,
    [TOTALDISCINFOLINENUM] [numeric](28, 12) NULL,
    [TOTALDISCAMOUNT] [numeric](28, 12) NULL,
    [CUSTOMERPRICE] [numeric](28, 12) NULL,
    [CUSTOMERDISCPCT] [numeric](28, 12) NULL,
    [CUSTOMERQTYUSED] [numeric](28, 12) NULL,
    [PARENTLINE] [numeric](28, 12) NULL,
    [ROUNDNUMBER] [int] NULL,
    [COVERNUMBER] [int] NULL,
    [MARKED] [int] NULL,
    [DISCOUNTAMOUNTFORPRINTING] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TRANS__198ECC63]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TRANS__198ECC63]  DEFAULT ((0)) FOR [TRANSTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__LINEN__1A82F09C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__LINEN__1A82F09C]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__RECEI__1B7714D5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__RECEI__1B7714D5]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__BARCO__1C6B390E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__BARCO__1C6B390E]  DEFAULT ('') FOR [BARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NUMBE__1D5F5D47]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__NUMBE__1D5F5D47]  DEFAULT ('') FOR [NUMBER_]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__STATU__1E538180]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__STATU__1E538180]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CURRE__1F47A5B9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__CURRE__1F47A5B9]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DESCR__203BC9F2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DESCR__203BC9F2]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSAC__UNIT__212FEE2B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSAC__UNIT__212FEE2B]  DEFAULT ('') FOR [UNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__STORE__22241264]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__STORE__22241264]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TERMI__2318369D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TERMI__2318369D]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__STAFF__240C5AD6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__STAFF__240C5AD6]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PRICE__25007F0F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PRICE__25007F0F]  DEFAULT ((0)) FOR [PRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__SCALE__25F4A348]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__SCALE__25F4A348]  DEFAULT ((0)) FOR [SCALEITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NODIS__26E8C781]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__NODIS__26E8C781]  DEFAULT ((0)) FOR [NODISCOUNTALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PRICE__27DCEBBA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PRICE__27DCEBBA]  DEFAULT ((0)) FOR [PRICEINBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__AMOUN__28D10FF3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__AMOUN__28D10FF3]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSACT__QTY__29C5342C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSACT__QTY__29C5342C]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NETPR__2AB95865]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__NETPR__2AB95865]  DEFAULT ((0)) FOR [NETPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PRICE__2BAD7C9E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PRICE__2BAD7C9E]  DEFAULT ('') FOR [PRICEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TAXCO__2CA1A0D7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TAXCO__2CA1A0D7]  DEFAULT ('') FOR [TAXCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TAXPC__2D95C510]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TAXPC__2D95C510]  DEFAULT ((0)) FOR [TAXPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DISCO__2E89E949]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DISCO__2E89E949]  DEFAULT ((0)) FOR [DISCOUNTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DISCO__2F7E0D82]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DISCO__2F7E0D82]  DEFAULT ((0)) FOR [DISCOUNTPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COSTA__307231BB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__COSTA__307231BB]  DEFAULT ((0)) FOR [COSTAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COSTP__316655F4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__COSTP__316655F4]  DEFAULT ((0)) FOR [COSTPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__NETAM__325A7A2D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__NETAM__325A7A2D]  DEFAULT ((0)) FOR [NETAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TAXAM__334E9E66]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TAXAM__334E9E66]  DEFAULT ((0)) FOR [TAXAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__AMOUN__3442C29F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__AMOUN__3442C29F]  DEFAULT ((0)) FOR [AMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CARDT__3536E6D8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__CARDT__3536E6D8]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CARDC__362B0B11]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__CARDC__362B0B11]  DEFAULT ('') FOR [CARDCUSTCOUPONITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TAXGR__371F2F4A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TAXGR__371F2F4A]  DEFAULT ('') FOR [TAXGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ITEMD__38135383]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ITEMD__38135383]  DEFAULT ('') FOR [ITEMDISCOUNTGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CARDT__390777BC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__CARDT__390777BC]  DEFAULT ((0)) FOR [CARDTRANSID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COUPO__39FB9BF5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__COUPO__39FB9BF5]  DEFAULT ('') FOR [COUPONEANORG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ITEMI__3AEFC02E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ITEMI__3AEFC02E]  DEFAULT ((0)) FOR [ITEMIDSCANNED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PRICE__3BE3E467]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PRICE__3BE3E467]  DEFAULT ((0)) FOR [PRICECHANGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__WEIGH__3CD808A0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__WEIGH__3CD808A0]  DEFAULT ((0)) FOR [WEIGHTMANUALLYENTERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__QTYIN__3DCC2CD9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__QTYIN__3DCC2CD9]  DEFAULT ((0)) FOR [QTYINBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DISPE__3EC05112]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DISPE__3EC05112]  DEFAULT ((0)) FOR [DISPENSEPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__LINKE__3FB4754B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__LINKE__3FB4754B]  DEFAULT ((0)) FOR [LINKEDITEMIDNOTORIGINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ORIGO__40A89984]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ORIGO__40A89984]  DEFAULT ((0)) FOR [ORIGOFALINKEDITEMLIST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PRICE__419CBDBD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PRICE__419CBDBD]  DEFAULT ((0)) FOR [PRICEOVERRIDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ITEMD__4290E1F6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ITEMD__4290E1F6]  DEFAULT ((0)) FOR [ITEMDEPARTMENTNEGATIVE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COUNT__4385062F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__COUNT__4385062F]  DEFAULT ((0)) FOR [COUNTASONE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ITEMP__44792A68]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ITEMP__44792A68]  DEFAULT ('') FOR [ITEMPOSTINGGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TOTAL__456D4EA1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TOTAL__456D4EA1]  DEFAULT ((0)) FOR [TOTALROUNDEDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ORIGP__466172DA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ORIGP__466172DA]  DEFAULT ((0)) FOR [ORIGPRICEINCLTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ORIGP__47559713]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ORIGP__47559713]  DEFAULT ((0)) FOR [ORIGPRICEEXCLTAX]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PICTU__4849BB4C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PICTU__4849BB4C]  DEFAULT (NULL) FOR [PICTURE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DISCI__493DDF85]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DISCI__493DDF85]  DEFAULT ((0)) FOR [DISCINFOLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DISCO__4A3203BE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DISCO__4A3203BE]  DEFAULT ((0)) FOR [DISCOUNTTRIGGERED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__QTYDI__4B2627F7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__QTYDI__4B2627F7]  DEFAULT ((0)) FOR [QTYDISCOUNTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PERIO__4C1A4C30]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PERIO__4C1A4C30]  DEFAULT ((0)) FOR [PERIODICDISCTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PERIO__4D0E7069]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PERIO__4D0E7069]  DEFAULT ('') FOR [PERIODICDISCGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INFOC__4E0294A2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__INFOC__4E0294A2]  DEFAULT ((0)) FOR [INFOCODEDISCDISABLE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__INFOC__4EF6B8DB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__INFOC__4EF6B8DB]  DEFAULT ((0)) FOR [INFOCODEDISCPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PERIO__4FEADD14]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PERIO__4FEADD14]  DEFAULT ((0)) FOR [PERIODICDISCPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DISCO__50DF014D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DISCO__50DF014D]  DEFAULT ('') FOR [DISCOUNTOFFERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__MIXAN__51D32586]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__MIXAN__51D32586]  DEFAULT ((0)) FOR [MIXANDMATCHLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__LINED__52C749BF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__LINED__52C749BF]  DEFAULT ((0)) FOR [LINEDISCPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TOTAL__53BB6DF8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TOTAL__53BB6DF8]  DEFAULT ((0)) FOR [TOTALDISCPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TOTAL__54AF9231]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TOTAL__54AF9231]  DEFAULT ((0)) FOR [TOTALDISCINFOLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__TOTAL__55A3B66A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__TOTAL__55A3B66A]  DEFAULT ((0)) FOR [TOTALDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CUSTO__5697DAA3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__CUSTO__5697DAA3]  DEFAULT ((0)) FOR [CUSTOMERPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CUSTO__578BFEDC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__CUSTO__578BFEDC]  DEFAULT ((0)) FOR [CUSTOMERDISCPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__CUSTO__58802315]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__CUSTO__58802315]  DEFAULT ((0)) FOR [CUSTOMERQTYUSED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__PAREN__5974474E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__PAREN__5974474E]  DEFAULT ((0)) FOR [PARENTLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__ROUND__5A686B87]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__ROUND__5A686B87]  DEFAULT ((0)) FOR [ROUNDNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__COVER__5B5C8FC0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__COVER__5B5C8FC0]  DEFAULT ((0)) FOR [COVERNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__MARKE__5C50B3F9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__MARKE__5C50B3F9]  DEFAULT ((0)) FOR [MARKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DISCO__5D44D832]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DISCO__5D44D832]  DEFAULT ((0)) FOR [DISCOUNTAMOUNTFORPRINTING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DATAA__5E38FC6B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[POSTRANSACTIONLINE] ADD  CONSTRAINT [DF__POSTRANSA__DATAA__5E38FC6B]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view PRICEDISCGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[PRICEDISCGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[PRICEDISCGROUP]
GO
CREATE VIEW [dbo].PRICEDISCGROUP AS
(
  SELECT
    [MODULE],
    [TYPE],
    [GROUPID],
    [NAME],
    CONVERT([int], 0) AS 'INCLTAX',
    [DATAAREAID],
    [RECID]
  FROM [ax].PRICEDISCGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view PRICEDISCTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[PRICEDISCTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[PRICEDISCTABLE]
GO
CREATE VIEW [dbo].PRICEDISCTABLE AS
(
  SELECT
    [AGREEMENT],
    [ITEMCODE],
    [ACCOUNTCODE],
    [ITEMRELATION],
    [ACCOUNTRELATION],
    [QUANTITYAMOUNTFROM],
    [FROMDATE],
    [TODATE],
    [AMOUNT],
    [CURRENCY],
    [PERCENT1],
    [PERCENT2],
    [DELIVERYTIME],
    [SEARCHAGAIN],
    [PRICEUNIT],
    [RELATION],
    [QUANTITYAMOUNTTO],
    [UNITID],
    [MARKUP],
    [ALLOCATEMARKUP],
    [MODULE],
    [INVENTDIMID],
    [CALENDARDAYS],
    [GENERICCURRENCY],
    [MODIFIEDDATETIME],
    [DATAAREAID],
    [RECID],
    CONVERT([numeric](32, 16), 0) AS 'PRICEINCLVAT',
    [MAXIMUMRETAILPRICE_IN]
  FROM [ax].PRICEDISCTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view PRICEPARAMETERS ..'
GO
IF OBJECT_ID(N'[dbo].[PRICEPARAMETERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[PRICEPARAMETERS]
GO
CREATE VIEW [dbo].PRICEPARAMETERS AS
(
  SELECT
    [SALESPRICEACCOUNTITEM],
    [SALESLINEACCOUNTITEM],
    [SALESLINEACCOUNTGROUP],
    [SALESLINEACCOUNTALL],
    [SALESMULTILNACCOUNTGROUP],
    [SALESMULTILNACCOUNTALL],
    [SALESENDACCOUNTALL],
    [SALESPRICEGROUPITEM],
    [SALESLINEGROUPITEM],
    [SALESLINEGROUPGROUP],
    [SALESLINEGROUPALL],
    [SALESMULTILNGROUPGROUP],
    [SALESMULTILNGROUPALL],
    [SALESENDGROUPALL],
    [SALESPRICEALLITEM],
    [SALESLINEALLITEM],
    [SALESLINEALLGROUP],
    [SALESLINEALLALL],
    [SALESMULTILNALLGROUP],
    [SALESMULTILNALLALL],
    [SALESENDALLALL],
    [PURCHPRICEACCOUNTITEM],
    [PURCHLINEACCOUNTITEM],
    [PURCHLINEACCOUNTGROUP],
    [PURCHLINEACCOUNTALL],
    [PURCHMULTILNACCOUNTGROUP],
    [PURCHMULTILNACCOUNTALL],
    [PURCHENDACCOUNTALL],
    [PURCHPRICEGROUPITEM],
    [PURCHLINEGROUPITEM],
    [PURCHLINEGROUPGROUP],
    [PURCHLINEGROUPALL],
    [PURCHMULTILNGROUPGROUP],
    [PURCHMULTILNGROUPALL],
    [PURCHENDGROUPALL],
    [PURCHPRICEALLITEM],
    [PURCHLINEALLITEM],
    [PURCHLINEALLGROUP],
    [PURCHLINEALLALL],
    [PURCHMULTILNALLGROUP],
    [PURCHMULTILNALLALL],
    [PURCHENDALLALL],
    [KEY] AS 'KEY_',
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID]
  FROM [ax].PRICEPARAMETERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RBOCOLORGROUPTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOCOLORGROUPTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOCOLORGROUPTABLE](
    [COLORGROUP] [nvarchar](10) NOT NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20092GROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [COLORGROUP] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__COLOR__3BAEDA3D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOCOLORGROUPTABLE] ADD  CONSTRAINT [DF__RBOCOLORG__COLOR__3BAEDA3D]  DEFAULT ('') FOR [COLORGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__DESCR__3CA2FE76]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOCOLORGROUPTABLE] ADD  CONSTRAINT [DF__RBOCOLORG__DESCR__3CA2FE76]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__DATAA__3D9722AF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOCOLORGROUPTABLE] ADD  CONSTRAINT [DF__RBOCOLORG__DATAA__3D9722AF]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOCURRENCY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOCURRENCY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOCURRENCY](
    [CURRENCYCODE] [nvarchar](3) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCURREN__CURRE__78B7E87D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOCURRENCY] ADD  CONSTRAINT [DF__RBOCURREN__CURRE__78B7E87D]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCURREN__DATAA__79AC0CB6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOCURRENCY] ADD  CONSTRAINT [DF__RBOCURREN__DATAA__79AC0CB6]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOINVENTITEMGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOINVENTITEMGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOINVENTITEMGROUP](
    [GROUPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [NAMEALIAS] [nvarchar](20) NULL,
    [DEPARTMENTID] [nvarchar](10) NULL,
    [SIZEGROUPID] [nvarchar](10) NULL,
    [COLORGROUPID] [nvarchar](10) NULL,
    [ITEMREPORTNAME] [nvarchar](40) NULL,
    [SHELFREPORTNAME] [nvarchar](40) NULL,
    [DISPENSEPRINTERGROUPID] [nvarchar](10) NULL,
    [BARCODESETUPID] [nvarchar](10) NULL,
    [DISPENSEPRINTINGDISABLED] [int] NULL,
    [USEEANSTANDARDBARCODE] [int] NULL,
    [POSINVENTORYLOOKUP] [int] NULL,
    [STYLEGROUPID] [nvarchar](10) NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20113GROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [GROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__GROUP__4F4BBE96]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__GROUP__4F4BBE96]  DEFAULT ('') FOR [GROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTI__NAME__503FE2CF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENTI__NAME__503FE2CF]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__NAMEA__51340708]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__NAMEA__51340708]  DEFAULT ('') FOR [NAMEALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DEPAR__52282B41]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__DEPAR__52282B41]  DEFAULT ('') FOR [DEPARTMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SIZEG__531C4F7A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__SIZEG__531C4F7A]  DEFAULT ('') FOR [SIZEGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__COLOR__541073B3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__COLOR__541073B3]  DEFAULT ('') FOR [COLORGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMR__550497EC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__ITEMR__550497EC]  DEFAULT ('') FOR [ITEMREPORTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SHELF__55F8BC25]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__SHELF__55F8BC25]  DEFAULT ('') FOR [SHELFREPORTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISPE__56ECE05E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__DISPE__56ECE05E]  DEFAULT ('') FOR [DISPENSEPRINTERGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__BARCO__57E10497]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__BARCO__57E10497]  DEFAULT ('') FOR [BARCODESETUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISPE__58D528D0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__DISPE__58D528D0]  DEFAULT ((0)) FOR [DISPENSEPRINTINGDISABLED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__USEEA__5ABD7142]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__USEEA__5ABD7142]  DEFAULT ((0)) FOR [USEEANSTANDARDBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__POSIN__5BB1957B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__POSIN__5BB1957B]  DEFAULT ((0)) FOR [POSINVENTORYLOOKUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__STYLE__5CA5B9B4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__STYLE__5CA5B9B4]  DEFAULT ('') FOR [STYLEGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__5D99DDED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__5D99DDED]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__5E8E0226]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__5E8E0226]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__5F82265F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__5F82265F]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__60764A98]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUP] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__60764A98]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOINVENTITEMGROUPSECTION20114 ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOINVENTITEMGROUPSECTION20114]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOINVENTITEMGROUPSECTION20114](
    [ITEMGROUPID] [nvarchar](10) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [SECTIONID] [nvarchar](10) NOT NULL,
    [SHELFID] [nvarchar](10) NOT NULL,
    [SHOWSSALESSTATISTICS] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20114PRIMARYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMGROUPID] ASC,
    [STOREID] ASC,
    [SECTIONID] ASC,
    [SHELFID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMG__6446DB7C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUPSECTION20114] ADD  CONSTRAINT [DF__RBOINVENT__ITEMG__6446DB7C]  DEFAULT ('') FOR [ITEMGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__STORE__653AFFB5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUPSECTION20114] ADD  CONSTRAINT [DF__RBOINVENT__STORE__653AFFB5]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SECTI__662F23EE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUPSECTION20114] ADD  CONSTRAINT [DF__RBOINVENT__SECTI__662F23EE]  DEFAULT ('') FOR [SECTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SHELF__67234827]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUPSECTION20114] ADD  CONSTRAINT [DF__RBOINVENT__SHELF__67234827]  DEFAULT ('') FOR [SHELFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SHOWS__68176C60]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUPSECTION20114] ADD  CONSTRAINT [DF__RBOINVENT__SHOWS__68176C60]  DEFAULT ((0)) FOR [SHOWSSALESSTATISTICS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__690B9099]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOINVENTITEMGROUPSECTION20114] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__690B9099]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOMSRCARDTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOMSRCARDTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOMSRCARDTABLE](
    [LINKTYPE] [int] NULL,
    [LINKID] [nvarchar](10) NULL,
    [CARDNUMBER] [nvarchar](30) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_RBOMSRCARDTABLE] PRIMARY KEY CLUSTERED
(
    [CARDNUMBER] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table RBOPERIODICDISCPRIORITY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOPERIODICDISCPRIORITY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOPERIODICDISCPRIORITY](
    [PERIODICDISCOUNTTYPE] [int] NULL,
    [PERIODICDISCGROUP] [nvarchar](10) NULL,
    [PRIORITY] [int] NULL,
    [STATUS] [int] NULL,
    [DISCOUNTVALIDATIONPERIODID] [nvarchar](10) NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPERIOD__PERIO__4C053D97]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPERIODICDISCPRIORITY] ADD  CONSTRAINT [DF__RBOPERIOD__PERIO__4C053D97]  DEFAULT ((0)) FOR [PERIODICDISCOUNTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPERIOD__PERIO__4CF961D0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPERIODICDISCPRIORITY] ADD  CONSTRAINT [DF__RBOPERIOD__PERIO__4CF961D0]  DEFAULT ('') FOR [PERIODICDISCGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPERIOD__PRIOR__4DED8609]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPERIODICDISCPRIORITY] ADD  CONSTRAINT [DF__RBOPERIOD__PRIOR__4DED8609]  DEFAULT ((0)) FOR [PRIORITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPERIOD__STATU__4EE1AA42]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPERIODICDISCPRIORITY] ADD  CONSTRAINT [DF__RBOPERIOD__STATU__4EE1AA42]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPERIOD__DISCO__4FD5CE7B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPERIODICDISCPRIORITY] ADD  CONSTRAINT [DF__RBOPERIOD__DISCO__4FD5CE7B]  DEFAULT ('') FOR [DISCOUNTVALIDATIONPERIODID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPERIOD__DESCR__50C9F2B4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPERIODICDISCPRIORITY] ADD  CONSTRAINT [DF__RBOPERIOD__DESCR__50C9F2B4]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPERIOD__DATAA__51BE16ED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPERIODICDISCPRIORITY] ADD  CONSTRAINT [DF__RBOPERIOD__DATAA__51BE16ED]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOPRICEDISCGROUP_DEL ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOPRICEDISCGROUP_DEL]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOPRICEDISCGROUP_DEL](
    [MODULE] [int] NULL,
    [TYPE] [int] NULL,
    [ALLOWDISCOUNT] [int] NULL,
    [CURRENCY] [nvarchar](3) NULL,
    [DISTRIBUTIONGROUP] [nvarchar](10) NULL,
    [DISTRIBUTIONSUBGROUP] [nvarchar](10) NULL,
    [RETAILPRICEGROUP] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICED__MODUL__549A8398]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICED__MODUL__549A8398]  DEFAULT ((0)) FOR [MODULE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICEDI__TYPE__558EA7D1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICEDI__TYPE__558EA7D1]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICED__ALLOW__5682CC0A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICED__ALLOW__5682CC0A]  DEFAULT ((0)) FOR [ALLOWDISCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICED__CURRE__5776F043]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICED__CURRE__5776F043]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICED__DISTR__586B147C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICED__DISTR__586B147C]  DEFAULT ('') FOR [DISTRIBUTIONGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICED__DISTR__595F38B5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICED__DISTR__595F38B5]  DEFAULT ('') FOR [DISTRIBUTIONSUBGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICED__RETAI__5A535CEE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICED__RETAI__5A535CEE]  DEFAULT ((0)) FOR [RETAILPRICEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOPRICED__DATAA__5B478127]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOPRICEDISCGROUP_DEL] ADD  CONSTRAINT [DF__RBOPRICED__DATAA__5B478127]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOREPLICATIONITEM ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOREPLICATIONITEM]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOREPLICATIONITEM](
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOREPLIC__DATAA__5E23EDD2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOREPLICATIONITEM] ADD  CONSTRAINT [DF__RBOREPLIC__DATAA__5E23EDD2]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOSALESSTATISTICS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOSALESSTATISTICS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOSALESSTATISTICS](
    [ENTRYNUM] [int] NULL,
    [STOREID] [nvarchar](10) NULL,
    [ITEMRELATION] [nvarchar](10) NULL,
    [TRANSDATE] [datetime] NULL,
    [TRANSTIME] [int] NULL,
    [ITEMSSOLD] [numeric](28, 12) NULL,
    [ITEMSSCANNED] [numeric](28, 12) NULL,
    [NUMBEROFDEPARTMENTSALES] [numeric](28, 12) NULL,
    [NUMBEROFRETURNSALES] [numeric](28, 12) NULL,
    [VOIDEDAMOUNTMST] [numeric](28, 12) NULL,
    [SALESAMOUNTMST] [numeric](28, 12) NULL,
    [TAXAMOUNTMST] [numeric](28, 12) NULL,
    [COSTAMOUNTMST] [numeric](28, 12) NULL,
    [DISCOUNTAMOUNTMST] [numeric](28, 12) NULL,
    [NUMBEROFTRANSSALESTRANS] [numeric](28, 12) NULL,
    [TOTALDISCOUNTMST] [numeric](28, 12) NULL,
    [SALESAMOUNTCUR] [numeric](28, 12) NULL,
    [TAXAMOUNTCUR] [numeric](28, 12) NULL,
    [COSTAMOUNTCUR] [numeric](28, 12) NULL,
    [DISCOUNTAMOUNTCUR] [numeric](28, 12) NULL,
    [TOTALDISCOUNTAMOUNTCUR] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__ENTRY__53433F50]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__ENTRY__53433F50]  DEFAULT ((0)) FOR [ENTRYNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__STORE__54376389]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__STORE__54376389]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__ITEMR__552B87C2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__ITEMR__552B87C2]  DEFAULT ('') FOR [ITEMRELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__TRANS__561FABFB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__TRANS__561FABFB]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__TRANS__5713D034]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__TRANS__5713D034]  DEFAULT ((0)) FOR [TRANSTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__ITEMS__5807F46D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__ITEMS__5807F46D]  DEFAULT ((0)) FOR [ITEMSSOLD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__ITEMS__58FC18A6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__ITEMS__58FC18A6]  DEFAULT ((0)) FOR [ITEMSSCANNED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__NUMBE__59F03CDF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__NUMBE__59F03CDF]  DEFAULT ((0)) FOR [NUMBEROFDEPARTMENTSALES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__NUMBE__5AE46118]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__NUMBE__5AE46118]  DEFAULT ((0)) FOR [NUMBEROFRETURNSALES]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__VOIDE__5BD88551]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__VOIDE__5BD88551]  DEFAULT ((0)) FOR [VOIDEDAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__SALES__5CCCA98A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__SALES__5CCCA98A]  DEFAULT ((0)) FOR [SALESAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__TAXAM__5DC0CDC3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__TAXAM__5DC0CDC3]  DEFAULT ((0)) FOR [TAXAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__COSTA__5EB4F1FC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__COSTA__5EB4F1FC]  DEFAULT ((0)) FOR [COSTAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__DISCO__5FA91635]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__DISCO__5FA91635]  DEFAULT ((0)) FOR [DISCOUNTAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__NUMBE__609D3A6E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__NUMBE__609D3A6E]  DEFAULT ((0)) FOR [NUMBEROFTRANSSALESTRANS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__TOTAL__61915EA7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__TOTAL__61915EA7]  DEFAULT ((0)) FOR [TOTALDISCOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__SALES__628582E0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__SALES__628582E0]  DEFAULT ((0)) FOR [SALESAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__TAXAM__6379A719]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__TAXAM__6379A719]  DEFAULT ((0)) FOR [TAXAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__COSTA__646DCB52]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__COSTA__646DCB52]  DEFAULT ((0)) FOR [COSTAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__DISCO__6561EF8B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__DISCO__6561EF8B]  DEFAULT ((0)) FOR [DISCOUNTAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__TOTAL__665613C4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__TOTAL__665613C4]  DEFAULT ((0)) FOR [TOTALDISCOUNTAMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSALESS__DATAA__674A37FD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSALESSTATISTICS] ADD  CONSTRAINT [DF__RBOSALESS__DATAA__674A37FD]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOSTATISTICSTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOSTATISTICSTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOSTATISTICSTABLE](
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATIS__DATAA__411D9AD0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOSTATISTICSTABLE] ADD  CONSTRAINT [DF__RBOSTATIS__DATAA__411D9AD0]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RBOTRANSACTIONLOYALTYTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RBOTRANSACTIONLOYALTYTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS](
    [TRANSACTIONID] [nvarchar](10) NOT NULL,
    [CARDNUMBER] [nvarchar](50) NULL,
    [CALCULATEDPOINTS] [numeric](28, 12) NULL,
    [ACCUMULATEDPOINTS] [numeric](28, 12) NULL,
    [REPLICATED] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
    [TERMINAL] [nvarchar](10) NOT NULL,
    [STORE] [nvarchar](10) NOT NULL,
 CONSTRAINT [PK_RBOTRANSACTIONLOYALTYTRANS] PRIMARY KEY CLUSTERED
(
    [TRANSACTIONID] ASC,
    [DATAAREAID] ASC,
    [STORE] ASC,
    [TERMINAL] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTRANSA__TRANS__2F65D18D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD  CONSTRAINT [DF__RBOTRANSA__TRANS__2F65D18D]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTRANSA__CARDN__3059F5C6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD  CONSTRAINT [DF__RBOTRANSA__CARDN__3059F5C6]  DEFAULT ('') FOR [CARDNUMBER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_RBOTRANSACTIONLOYALTYTRANS_CALCULATEDPOINTS]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD  CONSTRAINT [DF_RBOTRANSACTIONLOYALTYTRANS_CALCULATEDPOINTS]  DEFAULT ((0)) FOR [CALCULATEDPOINTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_RBOTRANSACTIONLOYALTYTRANS_ACCUMULATEDPOINTS]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD  CONSTRAINT [DF_RBOTRANSACTIONLOYALTYTRANS_ACCUMULATEDPOINTS]  DEFAULT ((0)) FOR [ACCUMULATEDPOINTS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTRANSA__REPLI__314E19FF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD  CONSTRAINT [DF__RBOTRANSA__REPLI__314E19FF]  DEFAULT ((0)) FOR [REPLICATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTRANSA__DATAA__32423E38]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD  CONSTRAINT [DF__RBOTRANSA__DATAA__32423E38]  DEFAULT ('DAT') FOR [DATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTRANSA__TERMI__6B84DD35]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD CONSTRAINT [DF__RBOTRANSA__TERMI__6B84DD35] DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTRANSA__STORE__6C79016E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RBOTRANSACTIONLOYALTYTRANS] ADD CONSTRAINT [DF__RBOTRANSA__STORE__6C79016E] DEFAULT ('') FOR [STORE]
END

-------------------------------------------------------------------------------
PRINT 'Creating table REPORTDATA ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[REPORTDATA]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[REPORTDATA](
    [GCRECORD] [int] NULL,
    [OID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [OBJECTTYPENAME] [nvarchar](100) NULL,
    [CONTENT] [image] NULL,
    [NAME] [nvarchar](100) NULL,
    [OPTIMISTICLOCKFIELD] [int] NULL,
 CONSTRAINT [PK_REPORTDATA] PRIMARY KEY CLUSTERED
(
    [OID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILAFFILIATION ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILAFFILIATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].RETAILAFFILIATION
GO
CREATE VIEW [dbo].RETAILAFFILIATION AS
(
  SELECT
    [RECID],
    [AFFILIATIONTYPE],
    [NAME]
  FROM [ax].RETAILAFFILIATION
);
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILAFFILIATIONPRICEGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILAFFILIATIONPRICEGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].RETAILAFFILIATIONPRICEGROUP
GO
CREATE VIEW [dbo].RETAILAFFILIATIONPRICEGROUP AS
(
  SELECT
    [RECID],
    [RETAILAFFILIATION],
    [PRICEDISCGROUP]
  FROM [ax].RETAILAFFILIATIONPRICEGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILAFFILIATIONTRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILAFFILIATIONTRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].RETAILAFFILIATIONTRANSLATION
GO
CREATE VIEW [dbo].RETAILAFFILIATIONTRANSLATION AS
(
  SELECT
    [RECID],
    [AFFILIATION],
    [DESCRIPTION],
    [LANGUAGEID]
  FROM [ax].RETAILAFFILIATIONTRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILBARCODEMASKCHARACTER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILBARCODEMASKCHARACTER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILBARCODEMASKCHARACTER]
GO
CREATE VIEW [dbo].RETAILBARCODEMASKCHARACTER AS
(
  SELECT
    [CHARACTERTYPE],
    [CHARACTER],
    [COMMENT] AS 'COMMENT_',
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILBARCODEMASKCHARACTER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILBARCODEMASKSEGMENT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILBARCODEMASKSEGMENT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILBARCODEMASKSEGMENT]
GO
CREATE VIEW [dbo].RETAILBARCODEMASKSEGMENT AS
(
  SELECT
    [SEGMENTNUM],
    [LENGTH],
    [TYPE],
    [DECIMALS],
    [CHAR],
    [MASKID],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILBARCODEMASKSEGMENT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILBARCODEMASKTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILBARCODEMASKTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILBARCODEMASKTABLE]
GO
CREATE VIEW [dbo].RETAILBARCODEMASKTABLE AS
(
  SELECT
    [DESCRIPTION],
    [MASK],
    [PREFIX],
    [SYMBOLOGY],
    [TYPE],
    [MASKID],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILBARCODEMASKTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILBUTTONGRID ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILBUTTONGRID]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILBUTTONGRID]
GO
CREATE VIEW [dbo].RETAILBUTTONGRID AS
(
  SELECT
    [BUTTONGRIDID],
    [NAME],
    [SPACEBETWEENBUTTONS],
    [FONT],
    [KEYBOARDUSED],
    [RECID],
    [DEFAULTCOLOR],
    [DEFAULTFONTSIZE],
    [DEFAULTFONTSTYLE]
  FROM [ax].RETAILBUTTONGRID
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILBUTTONGRIDBUTTONS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILBUTTONGRIDBUTTONS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILBUTTONGRIDBUTTONS]
GO
CREATE VIEW [dbo].RETAILBUTTONGRIDBUTTONS AS
(
  SELECT
    [ID],
    [COL],
    [COLSPAN],
    [ROWNUM],
    [ROWSPAN],
    [ACTION],
    [ACTIONPROPERTY],
    [PICTUREID],
    [DISPLAYTEXT],
    [COLOUR],
    [FONTSIZE],
    [FONTSTYLE],
    [BUTTONGRIDID],
    [RECID],
    [IMAGEALIGNMENT],
    [BACKCOLOR],
    [BACKCOLOR2],
    [BORDERCOLOR],
    [FONTCOLOR],
    [GRADIENTMODE],
    [NEWIMAGEALIGNMENT],
    [NEWTEXTALIGNMENT],
    [USECUSTOMLOOKANDFEEL],
    [ROWVERSION]
  FROM [ax].RETAILBUTTONGRIDBUTTONS
)
GO

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCARDPAYMENT_BR ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCARDPAYMENT_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCARDPAYMENT_BR](
    [CARDTYPE] [nvarchar](3) NOT NULL,
    [TRANSACTIONDATE] [datetime] NOT NULL,
    [CREDITCARDCOMPANYNAME] [nvarchar](30) NULL,
    [OPERATIONTYPE] [nvarchar](2) NULL,
    [INSTALLMENTS] [int] NULL,
    [RECEIPTNUMBER] [nvarchar](12) NOT NULL,
    [AMOUNT] [numeric](28, 12) NOT NULL,
    [LINENUMBER] [numeric](28, 12) NULL,
    [PAYMENTSTATUS] [int] NOT NULL,
    [RECEIPTSTATUS] [int] NOT NULL,
    [PRINTTARGET] [int] NOT NULL,
    [RESPONSEFILE] [nvarchar](max) NULL,
    [CONTROLNUMBER] [nvarchar](6) NOT NULL,
    [TRANSACTIONID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [REPLICATIONCOUNTER] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_RETAILCARDPAYMENT_BR] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC,
    [TRANSACTIONID] ASC,
    [CONTROLNUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCARDTOTENDERMAPPING ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCARDTOTENDERMAPPING]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCARDTOTENDERMAPPING](
    [BROKERID] [nvarchar](30) NOT NULL,
    [CARDID] [int] NOT NULL,
    [TENDERID] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_PRETAILCARDTOTENDERMAPPING_1] PRIMARY KEY NONCLUSTERED
(
    [BROKERID] ASC,
    [CARDID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_RETAILCARDTOTENDERMAPPING_DATAAREAID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCARDTOTENDERMAPPING] ADD  CONSTRAINT [DF_RETAILCARDTOTENDERMAPPING_DATAAREAID]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCASHDECLARATION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCASHDECLARATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCASHDECLARATION](
    [CURRENCYCODE] [nvarchar](3) NOT NULL,
    [STATEMENTID] [nvarchar](20) NOT NULL,
    [AMOUNTCUR] [numeric](28, 12) NOT NULL,
    [TYPE] [int] NOT NULL,
    [QTY] [numeric](28, 12) NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [TOTALLINE] [int] NOT NULL,
    [TOTALAMOUNT] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NOT NULL,
 CONSTRAINT [I_20091PRIMARYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STATEMENTID] ASC,
    [CURRENCYCODE] ASC,
    [TYPE] ASC,
    [AMOUNTCUR] ASC,
    [LINENUM] ASC,
    [TOTALLINE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDE__CURRE__303D2791]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDE__CURRE__303D2791]  DEFAULT ('') FOR [CURRENCYCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDE__STATE__31314BCA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDE__STATE__31314BCA]  DEFAULT ('') FOR [STATEMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDE__AMOUN__32257003]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDE__AMOUN__32257003]  DEFAULT ((0)) FOR [AMOUNTCUR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDEC__TYPE__3319943C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDEC__TYPE__3319943C]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDECL__QTY__340DB875]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDECL__QTY__340DB875]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDE__LINEN__3501DCAE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDE__LINEN__3501DCAE]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDE__TOTAL__35F600E7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDE__TOTAL__35F600E7]  DEFAULT ((0)) FOR [TOTALLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDE__TOTAL__36EA2520]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDE__TOTAL__36EA2520]  DEFAULT ((0)) FOR [TOTALAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCASHDE__DATAA__37DE4959]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCASHDECLARATION] ADD  CONSTRAINT [DF__RBOCASHDE__DATAA__37DE4959]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCATEGORYCONTAINMENTLOOKUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCATEGORYCONTAINMENTLOOKUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILCATEGORYCONTAINMENTLOOKUP]
GO
CREATE VIEW [dbo].RETAILCATEGORYCONTAINMENTLOOKUP AS
(
  SELECT
    [CATEGORY],
    [CONTAINEDCATEGORY],
    [ISDIRTY],
    [RECID]
  FROM [ax].RETAILCATEGORYCONTAINMENTLOOKUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCHANNELCURRENCY ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCHANNELCURRENCY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILCHANNELCURRENCY]
GO
CREATE VIEW [dbo].RETAILCHANNELCURRENCY AS
(
  SELECT
    [CURRENCYCODE],
    [CHANNEL],
    [RECID]
  FROM [ax].RETAILCHANNELCURRENCY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCHANNELPRICEGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCHANNELPRICEGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILCHANNELPRICEGROUP]
GO
CREATE VIEW [dbo].RETAILCHANNELPRICEGROUP AS
(
  SELECT
    [RECID],
    [RETAILCHANNEL],
    [PRICEGROUP]
  FROM [ax].RETAILCHANNELPRICEGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCHANNELREPORT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCHANNELREPORT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILCHANNELREPORT]
GO
CREATE VIEW [dbo].RETAILCHANNELREPORT AS
(
  SELECT
    [RECID],
    [REPORTDEFINITIONXML],
    [REPORTNAME],
    [REPORTID]
  FROM [ax].RETAILCHANNELREPORT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCHANNELTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCHANNELTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILCHANNELTABLE]
GO
CREATE VIEW [dbo].RETAILCHANNELTABLE AS
(
  SELECT
    [PRICEINCLUDESSALESTAX],
    [INSTANCERELATIONTYPE],
    [OMOPERATINGUNITID],
    [CHANNELTYPE],
    [RELATIONTYPE],
    [RECID],
    [INVENTLOCATION],
    [INVENTLOCATIONDATAAREAID],
    [CURRENCY],
    [DEFAULTCUSTACCOUNT],
    [DEFAULTCUSTDATAAREAID],
    [TRANSACTIONSERVICEPROFILE]
  FROM [ax].RETAILCHANNELTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCONFIGURATION_BR ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCONFIGURATION_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].RETAILCONFIGURATION_BR
GO
CREATE VIEW [dbo].RETAILCONFIGURATION_BR AS
(
  SELECT
    [PURPOSE],
    [RECID],
    [TYPE],
    [VALUE]
  FROM [ax].RETAILCONFIGURATION_BR
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCONFIGURATIONSTORETABLE_BR ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCONFIGURATIONSTORETABLE_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].RETAILCONFIGURATIONSTORETABLE_BR
GO
CREATE VIEW [dbo].RETAILCONFIGURATIONSTORETABLE_BR AS
(
  SELECT
    [RECID],
    [RETAILCONFIGURATION_BR],
    [RETAILSTORETABLE]
  FROM [ax].RETAILCONFIGURATIONSTORETABLE_BR
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCOLORGROUPTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCOLORGROUPTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCOLORGROUPTRANS](
    [COLORGROUP] [nvarchar](10) NOT NULL,
    [COLOR] [nvarchar](4) NOT NULL,
    [NAME] [nvarchar](10) NULL,
    [WEIGHT] [int] NULL,
    [NOINBARCODE] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
    [DESCRIPTION] [ntext] NULL,
 CONSTRAINT [I_20093COLORGROUPCOLORIDIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [COLORGROUP] ASC,
    [COLOR] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__COLOR__4167B393]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOLORGROUPTRANS] ADD  CONSTRAINT [DF__RBOCOLORG__COLOR__4167B393]  DEFAULT ('') FOR [COLORGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__COLOR__425BD7CC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOLORGROUPTRANS] ADD  CONSTRAINT [DF__RBOCOLORG__COLOR__425BD7CC]  DEFAULT ('') FOR [COLOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORGR__NAME__434FFC05]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOLORGROUPTRANS] ADD  CONSTRAINT [DF__RBOCOLORGR__NAME__434FFC05]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__WEIGH__4444203E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOLORGROUPTRANS] ADD  CONSTRAINT [DF__RBOCOLORG__WEIGH__4444203E]  DEFAULT ((0)) FOR [WEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__NOINB__45384477]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOLORGROUPTRANS] ADD  CONSTRAINT [DF__RBOCOLORG__NOINB__45384477]  DEFAULT ('') FOR [NOINBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__DATAA__47208CE9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOLORGROUPTRANS] ADD  CONSTRAINT [DF__RBOCOLORG__DATAA__47208CE9]  DEFAULT ('DAT') FOR [DATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOLORG__DESCR__462C68B0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOLORGROUPTRANS] ADD  CONSTRAINT [DF__RBOCOLORG__DESCR__462C68B0]  DEFAULT (NULL) FOR [DESCRIPTION]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCOMPETITORPRICETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCOMPETITORPRICETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCOMPETITORPRICETABLE](
    [COMPETITORID] [nvarchar](20) NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [BARCODE] [nvarchar](80) NULL,
    [PRICEDATE] [datetime] NOT NULL,
    [PRICE] [numeric](28, 12) NULL,
    [LASTCHECKEDDATE] [datetime] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [CREATEDDATE] [datetime] NULL,
    [CREATEDTIME] [int] NULL,
    [CREATEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20095ITEMCOMPETITORDATEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [COMPETITORID] ASC,
    [PRICEDATE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__COMPE__519E1B5C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__COMPE__519E1B5C]  DEFAULT ('') FOR [COMPETITORID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__ITEMI__52923F95]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__ITEMI__52923F95]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__BARCO__538663CE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__BARCO__538663CE]  DEFAULT ('') FOR [BARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__PRICE__547A8807]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__PRICE__547A8807]  DEFAULT ('1900-01-01 00:00:00.000') FOR [PRICEDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__PRICE__556EAC40]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__PRICE__556EAC40]  DEFAULT ((0)) FOR [PRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__LASTC__5662D079]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__LASTC__5662D079]  DEFAULT ('1900-01-01 00:00:00.000') FOR [LASTCHECKEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__MODIF__5756F4B2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__MODIF__5756F4B2]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__MODIF__584B18EB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__MODIF__584B18EB]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__MODIF__593F3D24]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__MODIF__593F3D24]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__CREAT__5A33615D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__CREAT__5A33615D]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CREATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__CREAT__5B278596]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__CREAT__5B278596]  DEFAULT ((0)) FOR [CREATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__CREAT__5C1BA9CF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__CREAT__5C1BA9CF]  DEFAULT ('?') FOR [CREATEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__DATAA__5D0FCE08]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORPRICETABLE] ADD  CONSTRAINT [DF__RBOCOMPET__DATAA__5D0FCE08]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCOMPETITORTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCOMPETITORTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCOMPETITORTABLE](
    [COMPETITORID] [nvarchar](20) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [ADDRESS] [nvarchar](250) NULL,
    [STREET] [nvarchar](250) NULL,
    [ZIPCODE] [nvarchar](10) NULL,
    [CITY] [nvarchar](30) NULL,
    [COUNTY] [nvarchar](10) NULL,
    [STATE] [nvarchar](10) NULL,
    [COUNTRY] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20096COMPETITORIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [COMPETITORID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__COMPE__60E05EEC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__COMPE__60E05EEC]  DEFAULT ('') FOR [COMPETITORID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPETI__NAME__61D48325]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPETI__NAME__61D48325]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__ADDRE__62C8A75E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__ADDRE__62C8A75E]  DEFAULT ('') FOR [ADDRESS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__STREE__63BCCB97]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__STREE__63BCCB97]  DEFAULT ('') FOR [STREET]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__ZIPCO__64B0EFD0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__ZIPCO__64B0EFD0]  DEFAULT ('') FOR [ZIPCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPETI__CITY__65A51409]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPETI__CITY__65A51409]  DEFAULT ('') FOR [CITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__COUNT__66993842]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__COUNT__66993842]  DEFAULT ('') FOR [COUNTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__STATE__678D5C7B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__STATE__678D5C7B]  DEFAULT ('') FOR [STATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__COUNT__688180B4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__COUNT__688180B4]  DEFAULT ('') FOR [COUNTRY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOMPET__DATAA__6975A4ED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOMPETITORTABLE] ADD  CONSTRAINT [DF__RBOCOMPET__DATAA__6975A4ED]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCOUNTER ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCOUNTER]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCOUNTER](
    [REFTABLEID] [int] NOT NULL,
    [REFRECID] [bigint] NOT NULL,
    [REFKEY] [nvarchar](10) NULL,
    [LINENUM] [numeric](28, 12) NULL,
    [COUNTER1] [int] NULL,
    [COUNTER2] [int] NULL,
    [COUNTER3] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__REFTA__09386909]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__REFTA__09386909]  DEFAULT ((0)) FOR [REFTABLEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__REFRE__0A2C8D42]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__REFRE__0A2C8D42]  DEFAULT ((0)) FOR [REFRECID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__REFKE__0B20B17B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__REFKE__0B20B17B]  DEFAULT ('') FOR [REFKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__LINEN__0C14D5B4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__LINEN__0C14D5B4]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__COUNT__0D08F9ED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__COUNT__0D08F9ED]  DEFAULT ((0)) FOR [COUNTER1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__COUNT__0DFD1E26]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__COUNT__0DFD1E26]  DEFAULT ((0)) FOR [COUNTER2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__COUNT__0EF1425F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__COUNT__0EF1425F]  DEFAULT ((0)) FOR [COUNTER3]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSCOUNTE__DATAA__0FE56698]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUNTER] ADD  CONSTRAINT [DF__POSCOUNTE__DATAA__0FE56698]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILCOUPONISSUERTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILCOUPONISSUERTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILCOUPONISSUERTABLE](
    [ISSUERID] [nvarchar](10) NOT NULL,
    [CUSTACCOUNT] [nvarchar](10) NULL,
    [ISSUERNAME] [nvarchar](30) NULL,
    [HANDLING] [int] NULL,
    [BLOCKED] [int] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20097ISSUERIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ISSUERID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__ISSUE__6D4635D1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__ISSUE__6D4635D1]  DEFAULT ('') FOR [ISSUERID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__CUSTA__6E3A5A0A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__CUSTA__6E3A5A0A]  DEFAULT ('') FOR [CUSTACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__ISSUE__6F2E7E43]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__ISSUE__6F2E7E43]  DEFAULT ('') FOR [ISSUERNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__HANDL__7022A27C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__HANDL__7022A27C]  DEFAULT ((0)) FOR [HANDLING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__BLOCK__7116C6B5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__BLOCK__7116C6B5]  DEFAULT ((0)) FOR [BLOCKED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__MODIF__720AEAEE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__MODIF__720AEAEE]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__MODIF__72FF0F27]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__MODIF__72FF0F27]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__MODIF__73F33360]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__MODIF__73F33360]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOCOUPON__DATAA__74E75799]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILCOUPONISSUERTABLE] ADD  CONSTRAINT [DF__RBOCOUPON__DATAA__74E75799]  DEFAULT ('DAT') FOR [DATAAREAID]
END
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCUSTAFFILIATION ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCUSTAFFILIATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILCUSTAFFILIATION]
GO
CREATE VIEW [dbo].RETAILCUSTAFFILIATION AS
(
  SELECT
    [RECID],
    [CUSTACCOUNTNUM],
    [RETAILAFFILIATIONID],
    [DATAAREAID]
  FROM [ax].RETAILCUSTAFFILIATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILCUSTTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILCUSTTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILCUSTTABLE]
GO
CREATE VIEW [dbo].RETAILCUSTTABLE AS
(
  SELECT
    [ACCOUNTNUM],
    [POSTASSHIPMENT],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID],
    [USEORDERNUMBERREFERENCE],
    [RECEIPTOPTION],
    [RECEIPTEMAIL],
    [NONCHARGABLEACCOUNT],
    [REQUIRESAPPROVAL]
  FROM [ax].RETAILCUSTTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILDATAENTRYTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILDATAENTRYTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILDATAENTRYTRANS](
    [ENTRYTYPEID] [nvarchar](20) NOT NULL,
    [ENTRYID] [nvarchar](10) NOT NULL,
    [AMOUNT] [numeric](28, 12) NULL,
    [APPLIEDAMOUNT] [numeric](28, 12) NULL,
    [CREATEDBYRECEIPID] [nvarchar](10) NULL,
    [CREATEDBYLINENUM] [numeric](28, 12) NULL,
    [APPLIED] [int] NULL,
    [APPLIEDBYRECEIPTID] [nvarchar](18) NULL,
    [APPLIEDBYLINENUM] [numeric](28, 12) NULL,
    [TRANSDATE] [datetime] NULL,
    [APPLIEDDATE] [datetime] NULL,
    [RESERVEDBYTERMINALID] [nvarchar](10) NULL,
    [CREATEDINSTOREID] [nvarchar](10) NULL,
    [REPLICATIONCOUNTER] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20054TYPEENTRYIDX] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [ENTRYTYPEID] ASC,
    [ENTRYID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__ENTRY__12C1D343]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__ENTRY__12C1D343]  DEFAULT ('') FOR [ENTRYTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__ENTRY__13B5F77C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__ENTRY__13B5F77C]  DEFAULT ('') FOR [ENTRYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__AMOUN__14AA1BB5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__AMOUN__14AA1BB5]  DEFAULT ((0)) FOR [AMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__APPLI__159E3FEE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__APPLI__159E3FEE]  DEFAULT ((0)) FOR [APPLIEDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__CREAT__16926427]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__CREAT__16926427]  DEFAULT ('') FOR [CREATEDBYRECEIPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__CREAT__17868860]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__CREAT__17868860]  DEFAULT ((0)) FOR [CREATEDBYLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__APPLI__187AAC99]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__APPLI__187AAC99]  DEFAULT ((0)) FOR [APPLIED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__APPLI__196ED0D2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__APPLI__196ED0D2]  DEFAULT ('') FOR [APPLIEDBYRECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__APPLI__1A62F50B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__APPLI__1A62F50B]  DEFAULT ((0)) FOR [APPLIEDBYLINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__TRANS__1B571944]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__TRANS__1B571944]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__APPLI__1C4B3D7D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__APPLI__1C4B3D7D]  DEFAULT ('1900-01-01 00:00:00.000') FOR [APPLIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__RESER__1D3F61B6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__RESER__1D3F61B6]  DEFAULT ('') FOR [RESERVEDBYTERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__CREAT__1E3385EF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__CREAT__1E3385EF]  DEFAULT ('') FOR [CREATEDINSTOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__REPLI__1F27AA28]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__REPLI__1F27AA28]  DEFAULT ((0)) FOR [REPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__DATAA__201BCE61]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTRANS] ADD  CONSTRAINT [DF__POSDATAEN__DATAA__201BCE61]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILDATAENTRYTYPETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILDATAENTRYTYPETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILDATAENTRYTYPETABLE](
    [ENTRYTYPEID] [nvarchar](20) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [CREATEBARCODE] [int] NULL,
    [CHECKAMOUNT] [int] NULL,
    [DATAENTRYONLYALLOWED] [int] NULL,
    [NUMBERING] [int] NULL,
    [NUMBERSEQUENCECODE] [nvarchar](10) NULL,
    [BARCODEMASK] [nvarchar](22) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__ENTRY__23EC5F45]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__ENTRY__23EC5F45]  DEFAULT ('') FOR [ENTRYTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAENT__NAME__24E0837E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAENT__NAME__24E0837E]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__CREAT__25D4A7B7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__CREAT__25D4A7B7]  DEFAULT ((0)) FOR [CREATEBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__CHECK__26C8CBF0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__CHECK__26C8CBF0]  DEFAULT ((0)) FOR [CHECKAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__DATAE__27BCF029]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__DATAE__27BCF029]  DEFAULT ((0)) FOR [DATAENTRYONLYALLOWED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__NUMBE__28B11462]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__NUMBE__28B11462]  DEFAULT ((0)) FOR [NUMBERING]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__NUMBE__29A5389B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__NUMBE__29A5389B]  DEFAULT ('') FOR [NUMBERSEQUENCECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__BARCO__2A995CD4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__BARCO__2A995CD4]  DEFAULT ('') FOR [BARCODEMASK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDATAEN__DATAA__2B8D810D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDATAENTRYTYPETABLE] ADD  CONSTRAINT [DF__POSDATAEN__DATAA__2B8D810D]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTCODE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTCODE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTCODE]
GO
CREATE VIEW [dbo].RETAILDISCOUNTCODE AS
(
  SELECT
    [DISCOUNTCODE],
    [BARCODE],
    [DISCOUNTOFFERID],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILDISCOUNTCODE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTLINEMIXANDMATCH ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTLINEMIXANDMATCH]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTLINEMIXANDMATCH]
GO
CREATE VIEW [dbo].RETAILDISCOUNTLINEMIXANDMATCH AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [DISCOUNTTYPE],
    [NUMBEROFITEMSNEEDED],
    [LINEGROUP]
  FROM [ax].RETAILDISCOUNTLINEMIXANDMATCH
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTLINEMULTIBUY ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTLINEMULTIBUY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTLINEMULTIBUY]
GO
CREATE VIEW [dbo].RETAILDISCOUNTLINEMULTIBUY AS
(
  SELECT
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILDISCOUNTLINEMULTIBUY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTLINEOFFER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTLINEOFFER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTLINEOFFER]
GO
CREATE VIEW [dbo].RETAILDISCOUNTLINEOFFER AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [DISCAMOUNT],
    [DISCOUNTMETHOD],
    [DISCPCT],
    [OFFERPRICE],
    [OFFERPRICEINCLTAX]
  FROM [ax].RETAILDISCOUNTLINEOFFER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTMIXANDMATCH ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTMIXANDMATCH]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTMIXANDMATCH]
GO
CREATE VIEW [dbo].RETAILDISCOUNTMIXANDMATCH AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [DEALPRICEVALUE],
    [MIXANDMATCHDISCOUNTTYPE],
    [NOOFLEASTEXPENSIVELINES],
    [NUMBEROFTIMESAPPLICABLE],
    [DISCOUNTAMOUNTVALUE]
  FROM [ax].RETAILDISCOUNTMIXANDMATCH
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTMULTIBUY ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTMULTIBUY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTMULTIBUY]
GO
CREATE VIEW [dbo].RETAILDISCOUNTMULTIBUY AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [MULTIBUYDISCOUNTTYPE]
  FROM [ax].RETAILDISCOUNTMULTIBUY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTOFFER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTOFFER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTOFFER]
GO
CREATE VIEW [dbo].RETAILDISCOUNTOFFER AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [DISCONPOS]
  FROM [ax].RETAILDISCOUNTOFFER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTPRICEGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTPRICEGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].RETAILDISCOUNTPRICEGROUP
GO
CREATE VIEW [dbo].RETAILDISCOUNTPRICEGROUP AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [OFFERID],
    [PRICEDISCGROUP]
  FROM [ax].RETAILDISCOUNTPRICEGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTTHRESHOLD ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTTHRESHOLD]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTTHRESHOLD]
GO
CREATE VIEW [dbo].RETAILDISCOUNTTHRESHOLD AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [COUNTNONDISCOUNTITEMS]
  FROM [ax].RETAILDISCOUNTTHRESHOLD
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTTHRESHOLDTIERS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTTHRESHOLDTIERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTTHRESHOLDTIERS]
GO
CREATE VIEW [dbo].RETAILDISCOUNTTHRESHOLDTIERS AS
(
  SELECT
    [DATAAREAID],
    [RECID],
    [OFFERID],
    [AMOUNTTHRESHOLD],
    [DISCOUNTMETHOD],
    [DISCOUNTVALUE]
  FROM [ax].RETAILDISCOUNTTHRESHOLDTIERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDISCOUNTVALIDATIONPERIOD ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDISCOUNTVALIDATIONPERIOD]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDISCOUNTVALIDATIONPERIOD]
GO
CREATE VIEW [dbo].RETAILDISCOUNTVALIDATIONPERIOD AS
(
  SELECT
    [PERIODID],
    [NAME],
    [VALIDFROM],
    [VALIDTO],
    [STARTINGTIME],
    [ENDINGTIME],
    CONVERT([int], 0) AS 'DATEWITHINBOUNDS',
    [MONDAYSTARTINGTIME],
    [MONDAYENDINGTIME],
    [MONDAYTIMEWITHINBOUNDS],
    [THUESDAYSTARTINGTIME],
    [THUESDAYENDINGTIME],
    [THUESDAYTIMEWITHINBOUNDS],
    [WEDNESDAYSTARTINGTIME],
    [WEDNESDAYENDINGTIME],
    [WEDNESDAYTIMEWITHINBOUNDS],
    [THURSDAYSTARTINGTIME],
    [THURSDAYENDINGTIME],
    [THURSDAYTIMEWITHINBOUNDS],
    [FRIDAYSTARTINGTIME],
    [FRIDAYENDINGTIME],
    [FRIDAYTIMEWITHINBOUNDS],
    [SATURDAYSTARTINGTIME],
    [SATURDAYENDINGTIME],
    [SATURDAYTIMEWITHINBOUNDS],
    [SUNDAYSTARTINGTIME],
    [SUNDAYENDINGTIME],
    [SUNDAYTIMEWITHINBOUNDS],
    [MONDAYENDINGTIMEAFTERMIDNIGHT],
    CONVERT([int], 0) AS 'THUESDAYENDINGTIMEAFTERMI20030',
    CONVERT([int], 0) AS 'WEDNESDAYENDINGTIMEAFTERM20031',
    CONVERT([int], 0) AS 'THURSDAYENDINGTIMEAFTERMI20032',
    [FRIDAYENDINGTIMEAFTERMIDNIGHT],
    CONVERT([int], 0) AS 'SATURDAYENDINGTIMEAFTERMI20034',
    [SUNDAYENDINGTIMEAFTERMIDNIGHT],
    [ENDINGTIMEAFTERMIDNIGHT],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILDISCOUNTVALIDATIONPERIOD
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILDISPENSEPRINTERGROUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILDISPENSEPRINTERGROUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILDISPENSEPRINTERGROUP](
    [GROUPID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20056GROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [GROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__GROUP__2E69EDB8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDISPENSEPRINTERGROUP] ADD  CONSTRAINT [DF__POSDISPEN__GROUP__2E69EDB8]  DEFAULT ('') FOR [GROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPENS__NAME__2F5E11F1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDISPENSEPRINTERGROUP] ADD  CONSTRAINT [DF__POSDISPENS__NAME__2F5E11F1]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSDISPEN__DATAA__3052362A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILDISPENSEPRINTERGROUP] ADD  CONSTRAINT [DF__POSDISPEN__DATAA__3052362A]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDLVMODEADDRESSEXPLODED ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDLVMODEADDRESSEXPLODED]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDLVMODEADDRESSEXPLODED]
GO
CREATE VIEW [dbo].RETAILDLVMODEADDRESSEXPLODED AS
(
  SELECT
    [COUNTRYREGION],
    [DLVMODE],
    [STATE],
    [RECID],
    [DATAAREAID]
  FROM [ax].RETAILDLVMODEADDRESSEXPLODED
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDLVMODECHANNELEXPLODED ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDLVMODECHANNELEXPLODED]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDLVMODECHANNELEXPLODED]
GO
CREATE VIEW [dbo].RETAILDLVMODECHANNELEXPLODED AS
(
  SELECT
    [DLVMODE],
    [OMOPERATINGUNIT],
    [RECID],
    [DATAAREAID]
  FROM [ax].RETAILDLVMODECHANNELEXPLODED
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILDLVMODEPRODUCTEXPLODED ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILDLVMODEPRODUCTEXPLODED]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILDLVMODEPRODUCTEXPLODED]
GO
CREATE VIEW [dbo].RETAILDLVMODEPRODUCTEXPLODED AS
(
  SELECT
    [DLVMODE],
    [INVENTDIM],
    [ITEMID],
    [RECID],
    [DATAAREAID]
  FROM [ax].RETAILDLVMODEPRODUCTEXPLODED
)
GO

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILEFDOCUMENT_BR ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILEFDOCUMENT_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILEFDOCUMENT_BR](
    [CHV_NFE] [nvarchar](44) NOT NULL,
    [IND_OPER] [nvarchar](1) NOT NULL,
    [IND_EMIT] [nvarchar](1) NOT NULL,
    [COD_PART] [nvarchar](60) NOT NULL,
    [COD_MOD] [nvarchar](2) NOT NULL,
    [COD_SIT] [numeric](9, 0) NOT NULL,
    [SER] [nvarchar](3) NOT NULL,
    [NUM_DOC] [numeric](9, 0) NOT NULL,
    [DT_DOC] [date] NOT NULL,
    [DT_E_S] [date] NOT NULL,
    [VL_DOC] [numeric](28, 2) NOT NULL,
    [IND_PGTO] [nvarchar](1) NOT NULL,
    [VL_DESC] [numeric](28, 2) NOT NULL,
    [VL_ABAT_NT] [numeric](28, 2) NOT NULL,
    [VL_MERC] [numeric](28, 2) NOT NULL,
    [IND_FRT] [nvarchar](1) NOT NULL,
    [VL_FRT] [numeric](28, 2) NOT NULL,
    [VL_SEG] [numeric](28, 2) NOT NULL,
    [VL_OUT_DA] [numeric](28, 2) NOT NULL,
    [VL_BC_ICMS] [numeric](28, 2) NOT NULL,
    [VL_ICMS] [numeric](28, 2) NOT NULL,
    [VL_BC_ICMS_ST] [numeric](28, 2) NOT NULL,
    [UF] [nvarchar](2) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_RETAILEFDOCUMENT_BR] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC,
    [CHV_NFE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__CHV_N__4F7F3212]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD  CONSTRAINT [DF__RETAILEFD__CHV_N__4F7F3212]  DEFAULT ('') FOR [CHV_NFE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__IND_O__5503013E]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__IND_O__5503013E] DEFAULT ('') FOR [IND_OPER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__IND_E__58D39222]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__IND_E__58D39222]  DEFAULT ('') FOR [IND_EMIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__COD_P__5ABBDA94]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__COD_P__5ABBDA94]  DEFAULT ('') FOR [COD_PART]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__COD_M__534FC2F6]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__COD_M__534FC2F6]  DEFAULT ('') FOR [COD_MOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__COD_S__5443E72F]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__COD_S__5443E72F]  DEFAULT ((0)) FOR [COD_SIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFDOC__SER__55380B68]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFDOC__SER__55380B68]  DEFAULT ('') FOR [SER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__NUM_D__562C2FA1]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__NUM_D__562C2FA1]  DEFAULT ((0)) FOR [NUM_DOC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__DT_DO__572053DA]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__DT_DO__572053DA]  DEFAULT ('1900-01-01') FOR [DT_DOC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__DT_E___58147813]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__DT_E___58147813]  DEFAULT ('1900-01-01') FOR [DT_E_S]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_DO__59089C4C]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_DO__59089C4C]  DEFAULT ((0)) FOR [VL_DOC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__IND_P__59FCC085]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__IND_P__59FCC085]  DEFAULT ('') FOR [IND_PGTO]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_DE__5AF0E4BE]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_DE__5AF0E4BE]  DEFAULT ((0)) FOR [VL_DESC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_AB__5BE508F7]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_AB__5BE508F7]  DEFAULT ((0)) FOR [VL_ABAT_NT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_ME__5CD92D30]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_ME__5CD92D30]  DEFAULT ((0)) FOR [VL_MERC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__IND_F__5DCD5169]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__IND_F__5DCD5169]  DEFAULT ('') FOR [IND_FRT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_FR__5EC175A2]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_FR__5EC175A2]  DEFAULT ('') FOR [VL_FRT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_SE__5FB599DB]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_SE__5FB599DB]  DEFAULT ((0)) FOR [VL_SEG]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_OU__60A9BE14]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_OU__60A9BE14]  DEFAULT ((0)) FOR [VL_OUT_DA]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_BC__619DE24D]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_BC__619DE24D]  DEFAULT ((0)) FOR [VL_BC_ICMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_IC__62920686]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_IC__62920686]  DEFAULT ((0)) FOR [VL_ICMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_BC__63862ABF]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_BC__63862ABF]  DEFAULT ((0)) FOR [VL_BC_ICMS_ST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFDOCU__UF__647A4EF8]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFDOCU__UF__647A4EF8]  DEFAULT ('') FOR [UF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__STORE__656E7331]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__STORE__656E7331]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__TERMI__6662976A]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__TERMI__6662976A]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__DATAA__6756BBA3]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENT_BR] ADD CONSTRAINT [DF__RETAILEFD__DATAA__6756BBA3]  DEFAULT ('') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILEFDOCUMENTLINES_BR ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILEFDOCUMENTLINES_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILEFDOCUMENTLINES_BR](
    [CHV_NFE] [nvarchar](44) NOT NULL,
    [CFOP] [numeric](4, 0) NOT NULL,
    [CST_ICMS] [numeric](5, 0) NOT NULL,
    [NUM_ITEM] [numeric](3, 0) NOT NULL,
    [COD_ITEM] [nvarchar](60) NOT NULL,
    [QTD] [numeric](28, 5) NOT NULL,
    [VL_ITEM] [numeric](28, 2) NOT NULL,
    [VL_DESC] [numeric](28, 2) NOT NULL,
    [VL_ICMS] [numeric](28, 2) NOT NULL,
    [VL_BC_ICMS] [numeric](28, 2) NOT NULL,
    [VL_BC_ICMS_ST] [numeric](28, 2) NOT NULL,
    [VL_ICMS_ST] [numeric](28, 2) NOT NULL,
    [VL_IPI] [numeric](28, 2) NOT NULL,
    [ALIQ_ICMS] [numeric](6, 2) NOT NULL,
    [VL_RED_BC] [numeric](28, 2) NOT NULL,
    [VL_ISE_IPI] [numeric](28, 2) NOT NULL,
    [VL_OUT_IPI] [numeric](28, 2) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_RETAILEFDOCUMENTLINES_BR] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC,
    [CHV_NFE] ASC,
    [NUM_ITEM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__CHV_N__0174E9AB]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__CHV_N__0174E9AB]  DEFAULT ('') FOR [CHV_NFE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFDO__CFOP__02690DE4]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFDO__CFOP__02690DE4]  DEFAULT ((0)) FOR [CFOP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__CST_I__035D321D]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__CST_I__035D321D]  DEFAULT ((0)) FOR [CST_ICMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__NUM_I__04515656]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__NUM_I__04515656]  DEFAULT ((0)) FOR [NUM_ITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__COD_I__05457A8F]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__COD_I__05457A8F]  DEFAULT ((0)) FOR [COD_ITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFDOC__QTD__06399EC8]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFDOC__QTD__06399EC8]  DEFAULT ((0)) FOR [QTD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_IT__072DC301]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_IT__072DC301]  DEFAULT ((0)) FOR [VL_ITEM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_DE__0821E73A]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_DE__0821E73A]  DEFAULT ((0)) FOR [VL_DESC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_IC__09160B73]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_IC__09160B73]  DEFAULT ((0)) FOR [VL_ICMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_IC__0BF2781E]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_IC__0BF2781E]  DEFAULT ((0)) FOR [VL_BC_ICMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_BC__0AFE53E5]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_BC__0AFE53E5]  DEFAULT ((0)) FOR [VL_BC_ICMS_ST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_BC__0A0A2FAC]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_BC__0A0A2FAC]  DEFAULT ((0)) FOR [VL_ICMS_ST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_IP__0CE69C57]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_IP__0CE69C57]  DEFAULT ((0)) FOR [VL_IPI]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__ALIQ___0DDAC090]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__ALIQ___0DDAC090]  DEFAULT ((0)) FOR [ALIQ_ICMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_RE__0ECEE4C9]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_RE__0ECEE4C9]  DEFAULT ((0)) FOR [VL_RED_BC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_IS__0FC30902]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_IS__0FC30902]  DEFAULT ((0)) FOR [VL_ISE_IPI]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__VL_OU__10B72D3B]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__VL_OU__10B72D3B]  DEFAULT ((0)) FOR [VL_OUT_IPI]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__STORE__11AB5174]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__STORE__11AB5174]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__TERMI__129F75AD]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__TERMI__129F75AD]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILEFD__DATAA__139399E6]'))
BEGIN
ALTER TABLE [dbo].[RETAILEFDOCUMENTLINES_BR] ADD CONSTRAINT [DF__RETAILEFD__DATAA__139399E6] DEFAULT ('') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILERRORS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILERRORS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILERRORS](
    [ERRORID] [int] NOT NULL,
    [ERRORMESSAGEID] [int] NOT NULL,
    [DESCRIPTION] [nvarchar](255) NULL,
    [CODEUNIT] [nvarchar](100) NULL,
    [ACTIVE] [int] NULL,
    [FIRSTINVERSION] [nvarchar](20) NULL,
    [DATECREATED] [datetime] NULL,
    [DATEUPDATED] [datetime] NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_RETAILERRORS_2] PRIMARY KEY NONCLUSTERED
(
    [ERRORID] ASC,
    [ERRORMESSAGEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[RETAILERRORS]') AND name = N'PK_RETAILERRORS')
CREATE UNIQUE CLUSTERED INDEX [PK_RETAILERRORS] ON [dbo].[RETAILERRORS]
(
    [ERRORID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILFORMLAYOUT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILFORMLAYOUT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILFORMLAYOUT]
GO
CREATE VIEW [dbo].RETAILFORMLAYOUT AS
(
  SELECT
    [TITLE],
    [DESCRIPTION],
    [UPPERCASE],
    [RECID],
    [PRINTASSLIP],
    [PRINTBEHAVIOUR],
    [PROMPTQUESTION],
    [HEADERXML],
    [LINESXML],
    [FOOTERXML],
    [FORMLAYOUTID],
    [LAYOUTTYPE]
  FROM [ax].RETAILFORMLAYOUT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILFUNCTIONALITYPROFILE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILFUNCTIONALITYPROFILE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILFUNCTIONALITYPROFILE]
GO
CREATE VIEW [dbo].RETAILFUNCTIONALITYPROFILE AS
(
  SELECT
    [PROFILEID],
    [NAME],
    [NOTAXUSED],
    [ADDTAXONPRICES],
    [SKIPTAXONRECEIPT],
    [MULTIBLEITEMSYMBOL],
    [CURRENCYSYMBOL],
    [AMOUNTROUNDINGTO],
    [PRICEROUNDINGTO],
    [AMOUNTDECIMALPLACES],
    [PRICEDECIMALPLACES],
    [NEGATIVEADJUSTMENT],
    [VOIDISPRESSED],
    [VOIDTRANSACTION],
    [VOIDPAYMENT],
    [REFUNDSALE],
    [MARKDOWN],
    [MARKUP],
    [OVERRIDEPRICE],
    [STARTOFTRANSACTION],
    [DISCOUNTATTOTAL],
    [TENDERDECLARATION],
    [ENDOFTRANSACTION],
    [EODBANKTOTALSVERIFICATION],
    [SERIALNUMBER],
    [SALESPERSON],
    [ITEMNOTONFILE],
    [NEGATIVESALESLINE],
    [MUSTKEYINPRICEIFZERO],
    [SALESPERSONMODE],
    [DISPLAYSECONDARYTOTALCURRENCY],
    [SECONDARYTOTALCURRENCY],
    [MINIMUMPASSWORDLENGTH],
    [BLOCKEDCLOSEDACCOUNT],
    [PRINTXREPORTONTERMINAL],
    [STAFFBARCODELOGON],
    [STAFFCARDLOGON],
    [MAXIMUMSTORETRANSLOG],
    [MAXIMUMPRICE],
    [MAXIMUMQTY],
    [MAXTRANSACTIONSEARCHRESULTS],
    [BACKUPTRAININGTRANSACTIONS],
    [DAYSTRANSACTIONSEXISTS],
    [TRANSACTIONDELETEREMINDER],
    [TAXREGISTRATIONNUMBERONRECEIPT],
    [CENTRALTABLESERVER],
    [TSSENDTRANSACTIONS],
    [TSSENDVOIDTRANSACTIONS],
    [TSSUSPENDRETRIEVETRANSACTIONS],
    [TSSTAFF],
    [TSCUSTOMER],
    [TSDATAENTRIES],
    [TSFLOATINGCASHIER],
    [TSINVENTORYLOOKUP],
    [TSCENTRALTABLESERVER],
    [TSUPDATEREPLICATIONCOUNTER],
    [TSTRANSACTIONRESENDLIMIT],
    [TSRESENDDELAY],
    [AGGREGATEITEMS],
    [MODIFIEDDATETIME] AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID],
    CONVERT([int], 0) AS 'LOGLEVEL',
    [CENTRALTABLESERVERPORT],
    [AGGREGATEPAYMENTS],
    [AGGREGATEITEMSFORPRINTING],
    CONVERT([int], 0) AS 'ALLOWSALESIFDRAWERISOPEN',
    [SHOWSTAFFLISTATLOGON],
    [LIMITSTAFFLISTTOSTORE],
    [LINEITEMTAXCHANGE],
    [TRANSACTIONTAXCHANGE],
    [SUPPORTEDCOUNTRYREGIONISOCODE],
    [REQUIREAMOUNTDECLARATION],
    [STAFFBARCODELOGONREQUIRESPASSWORD],
    [STAFFCARDLOGONREQUIRESPASSWORD],
    [AUDITENABLED],
    [DECIMALNOTREQUIREDFORMINORCURRENCYUNIT],
    [DAYSCUSTOMERHISTORY],
    [TAENABLEREGISTRATION],
    [INCLUDEKITCOMPONENTS],
    [APPLYDISCOUNTONUNITPRICES],
    [MANUALCALCULATEDISCOUNTS],
    [NOSALE]
  FROM [ax].RETAILFUNCTIONALITYPROFILE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILGROUPMEMBERLINE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILGROUPMEMBERLINE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILGROUPMEMBERLINE]
GO
CREATE VIEW [dbo].RETAILGROUPMEMBERLINE AS
(
  SELECT
    [CATEGORY],
    [PRODUCT],
    [VARIANT],
    [RECID]
  FROM [ax].RETAILGROUPMEMBERLINE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILHARDWAREPROFILE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILHARDWAREPROFILE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILHARDWAREPROFILE]
GO
CREATE VIEW [dbo].RETAILHARDWAREPROFILE AS
(
  SELECT
    [PROFILEID],
    [NAME],
    [FORMXPOS],
    [FORMYPOS],
    [SCREENKEYBOARD],
    [DRAWER],
    [DRAWERDEVICENAME],
    [DRAWERDESCRIPTION],
    [DRAWERMAKE],
    [DRAWERMODEL],
    [DISPLAYBINCONVERSION],
    [DISPLAYDEVICE],
    [DISPLAYDEVICENAME],
    [DISPLAYDESCRIPTION],
    [DISPLAYTOTALTEXT],
    [DISPLAYBALANCETEXT],
    [DISPLAYCLOSEDLINE1],
    [DISPLAYCLOSEDLINE2],
    [DISPLAYCHARACTERSET],
    [DELAYFORLINKEDITEMS],
    [SHOWPICTURE],
    [MSR],
    [MSRDEVICENAME],
    [MSRDESCRIPTION],
    [MSRMAKE],
    [MSRMODEL],
    [LOGOALIGNMENT],
    [LOGOBITMAP],
    [LOGO],
    [STARTTRACK1],
    [SEPARATOR1],
    [ENDTRACK1],
    [STARTTRACK2AFTER],
    [ENDTRACK2],
    [PINPAD],
    [PINPADDEVICENAME],
    [PINPADDESCRIPTION],
    [PINPADMAKE],
    [PINPADMODEL],
    [PRINTER],
    [PRINTERDEVICENAME],
    [PRINTERCHARACTERSET],
    [PRINTERDESCRIPTION],
    [PRINTERMAKE],
    [PRINTERMODEL],
    [MAXINVOICELINES],
    [PRINTBINARYCONVERSION],
    [HARDTOTAL],
    [HARDTOTALDEVICENAME],
    [HARDTOTALDESCRIPTION],
    [SCANNER],
    [SCANNERDEVICENAME],
    [SCANNERDESCRIPTION],
    [SCALE],
    [SCALEDEVICENAME],
    [SCALEDESCRIPTION],
    [TIMEOUTINSEC],
    [MANUALINPUTALLOWED],
    [KEYLOCK],
    [KEYLOCKDEVICENAME],
    [KEYLOCKDESCRIPTION],
    [DOCINSERTREMOVALTIMEOUT],
    [EFT],
    [EFTDESCRIPTION],
    [EFTSERVERNAME],
    [EFTSERVERPORT],
    [EFTCOMPANYID],
    [EFTUSERID],
    [EFTPASSWORD],
    [EFTDATA],
    [EFTCONFIGURATION],
    CONVERT([int], 0) AS 'EFTENVIRONMENT',
    [EFTTESTMODE],
    CONVERT([nvarchar](15), '') AS 'EFTCHECKDIGITS',
    [CAPTUREEXTRADATA],
    [MICR],
    [MICRDRIVERNAME],
    [MICRDESCRIPTION],
    [MODIFIEDDATETIME] AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID],
    [CCTV],
    [CCTVPORT],
    [CCTVHOSTNAME],
    [CCTVCAMERA],
    [PHARMACY],
    [PHARMACYHOST],
    [PHARMACYPORT],
    [KEYBOARDMAPPINGID],
    CONVERT([int], 0) AS 'EFTBATCHINCREMENTATEOS',
    [RFIDSCANNERTYPE],
    [RFIDDEVICENAME],
    [RFIDDESCRIPTION],
    [DUALDISPLAY],
    [DUALDISPLAYTYPE],
    [DUALDISPLAYRECEIPTPERCENTAGE],
    [DUALDISPLAYIMAGEPATH],
    [DUALDISPLAYIMAGEINTERVAL],
    [DUALDISPLAYBROWSERURL],
    [CASHCHANGER],
    [CASHCHANGERPORTSETTINGS],
    [CASHCHANGERINITSETTINGS],
    [PRINTERRECEIPTPROFILEID],
    [DISPLAYTERMINALCLOSED],
    [DISPLAYLINKEDITEM],
    [EFTMERCHANTID],
    [SIGCAP],
    [SIGCAPDEVICENAME],
    [SIGCAPDESCRIPTION],
    [SIGCAPFORMNAME],
    [SIGCAPMAKE],
    [SIGCAPMODEL],
    [EFTCONNECTORPROPERTIES],
    [SCANNER2],
    [SCANNER2DEVICENAME],
    [SCANNER2DESCRIPTION],
    [PRINTER2],
    [PRINTER2DEVICENAME],
    [PRINTER2BINARYCONVERSION],
    [PRINTER2CHARACTERSET],
    [PRINTER2DESCRIPTION],
    [PRINTER2DOCINSERTREMOVALTIMEOUT],
    [PRINTER2LOGOALIGNMENT],
    [PRINTER2LOGOBITMAP],
    [PRINTER2LOGO],
    [PRINTER2MAKE],
    [PRINTER2MODEL],
    [DRAWER2],
    [DRAWER2DEVICENAME],
    [DRAWER2DESCRIPTION],
    [DRAWER2MAKE],
    [DRAWER2MODEL],
    [PRINTER2RECEIPTPROFILEID],
    [EFTCONNECTORNAME],
    [FISCALPRINTER],
    [FISCALPRINTERDEVICENAME],
    [FISCALPRINTERDESCRIPTION]
  FROM [ax].RETAILHARDWAREPROFILE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILIMAGES ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILIMAGES]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILIMAGES]
GO
CREATE VIEW [dbo].RETAILIMAGES AS
(
  SELECT
    [PICTUREID],
    [PICTURE],
    [RECID]
  FROM [ax].RETAILIMAGES
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILINCOMEEXPENSEACCOUNTTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILINCOMEEXPENSEACCOUNTTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILINCOMEEXPENSEACCOUNTTABLE]
GO
CREATE VIEW [dbo].RETAILINCOMEEXPENSEACCOUNTTABLE AS
(
  SELECT
    [ACCOUNTNUM],
    [NAME],
    [STOREID],
    [NAMEALIAS],
    [ACCOUNTTYPE],
    CONVERT([nvarchar](10), '') AS 'LEDGERACCOUNT',
    [MESSAGELINE1],
    [MESSAGELINE2],
    [SLIPTEXT1],
    [SLIPTEXT2],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    CONVERT([bigint], 0) AS 'MODIFIEDTRANSACTIONID',
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILINCOMEEXPENSEACCOUNTTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILINFOCODETABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILINFOCODETABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILINFOCODETABLE]
GO
CREATE VIEW [dbo].RETAILINFOCODETABLE AS
(
  SELECT
    [INFOCODEID],
    [DESCRIPTION],
    [PROMPT],
    [ONCEPERTRANSACTION],
    [PRINTPROMPTONRECEIPT],
    [PRINTINPUTONRECEIPT],
    [PRINTINPUTNAMEONRECEIPT],
    [INPUTTYPE],
    [MINIMUMVALUE],
    [MAXIMUMVALUE],
    [MINIMUMLENGTH],
    [MAXIMUMLENGTH],
    [INPUTREQUIRED],
    [LINKEDINFOCODEID],
    [RANDOMFACTOR],
    [MODIFIEDDATETIME] AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID],
    CONVERT([int], 0) AS 'ADDITIONALCHECK'
  FROM [ax].RETAILINFOCODETABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILINFOCODETABLESPECIFIC ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILINFOCODETABLESPECIFIC]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILINFOCODETABLESPECIFIC]
GO
CREATE VIEW [dbo].RETAILINFOCODETABLESPECIFIC AS
(
  SELECT
    [REFRELATION],
    [SEQUENCE],
    [INFOCODEID],
    [INPUTREQUIRED],
    [WHENREQUIRED],
    [REFRELATION2],
    [REFRELATION3],
    [REFTABLEID],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILINFOCODETABLESPECIFIC
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILINFORMATIONSUBCODETABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILINFORMATIONSUBCODETABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILINFORMATIONSUBCODETABLE]
GO
CREATE VIEW [dbo].RETAILINFORMATIONSUBCODETABLE AS
(
  SELECT
    [INFOCODEID],
    [SUBCODEID],
    [DESCRIPTION],
    [TRIGGERFUNCTION],
    [TRIGGERCODE],
    [NEWSALESLINE],
    [PRICETYPE],
    [AMOUNTPERCENT],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILINFORMATIONSUBCODETABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILINVENTAVAILABILITY ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILINVENTAVAILABILITY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILINVENTAVAILABILITY]
GO
CREATE VIEW [dbo].RETAILINVENTAVAILABILITY AS
(
  SELECT
    [RECID],
    [ITEMRECID],
    [INVENTDIMRECID],
    [AVAILPHYSICAL],
    [LASTINVENTTRANS]
  FROM [ax].RETAILINVENTAVAILABILITY
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMACTIVITYTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMACTIVITYTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMACTIVITYTABLE](
    [ACTIVITYTYPEID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [ACTIVITYID] [nvarchar](20) NOT NULL,
    [ENDINGDATE] [datetime] NULL,
    [STARTINGDATE] [datetime] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20108ACTIVITYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ACTIVITYTYPEID] ASC,
    [ACTIVITYID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ACTIV__1F9CAB74]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTABLE] ADD  CONSTRAINT [DF__RBOINVENT__ACTIV__1F9CAB74]  DEFAULT ('') FOR [ACTIVITYTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTI__NAME__2090CFAD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTABLE] ADD  CONSTRAINT [DF__RBOINVENTI__NAME__2090CFAD]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ACTIV__2184F3E6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTABLE] ADD  CONSTRAINT [DF__RBOINVENT__ACTIV__2184F3E6]  DEFAULT ('') FOR [ACTIVITYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ENDIN__2279181F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTABLE] ADD  CONSTRAINT [DF__RBOINVENT__ENDIN__2279181F]  DEFAULT ('1900-01-01 00:00:00.000') FOR [ENDINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__START__236D3C58]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTABLE] ADD  CONSTRAINT [DF__RBOINVENT__START__236D3C58]  DEFAULT ('1900-01-01 00:00:00.000') FOR [STARTINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__24616091]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTABLE] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__24616091]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMACTIVITYTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMACTIVITYTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS](
    [ACTIVITYTYPEID] [nvarchar](10) NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [ACTIVITYID] [nvarchar](20) NOT NULL,
    [ENDINGDATE] [datetime] NULL,
    [STARTINGDATE] [datetime] NULL,
    [AUTOMATIC] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20109ITEMACTIVITYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [ACTIVITYTYPEID] ASC,
    [ACTIVITYID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ACTIV__2831F175]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS] ADD  CONSTRAINT [DF__RBOINVENT__ACTIV__2831F175]  DEFAULT ('') FOR [ACTIVITYTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMI__292615AE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS] ADD  CONSTRAINT [DF__RBOINVENT__ITEMI__292615AE]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ACTIV__2A1A39E7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS] ADD  CONSTRAINT [DF__RBOINVENT__ACTIV__2A1A39E7]  DEFAULT ('') FOR [ACTIVITYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ENDIN__2B0E5E20]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS] ADD  CONSTRAINT [DF__RBOINVENT__ENDIN__2B0E5E20]  DEFAULT ('1900-01-01 00:00:00.000') FOR [ENDINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__START__2C028259]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS] ADD  CONSTRAINT [DF__RBOINVENT__START__2C028259]  DEFAULT ('1900-01-01 00:00:00.000') FOR [STARTINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__AUTOM__2CF6A692]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS] ADD  CONSTRAINT [DF__RBOINVENT__AUTOM__2CF6A692]  DEFAULT ((0)) FOR [AUTOMATIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__2DEACACB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTRANS] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__2DEACACB]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMACTIVITYTYPE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMACTIVITYTYPE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE](
    [TYPEID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [AUTOMATIC] [int] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20110ACTIVITYTYPEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [TYPEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__TYPEI__31BB5BAF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE] ADD  CONSTRAINT [DF__RBOINVENT__TYPEI__31BB5BAF]  DEFAULT ('') FOR [TYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTI__NAME__32AF7FE8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE] ADD  CONSTRAINT [DF__RBOINVENTI__NAME__32AF7FE8]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__AUTOM__33A3A421]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE] ADD  CONSTRAINT [DF__RBOINVENT__AUTOM__33A3A421]  DEFAULT ((0)) FOR [AUTOMATIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__3497C85A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__3497C85A]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__358BEC93]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__358BEC93]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__368010CC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__368010CC]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__37743505]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMACTIVITYTYPE] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__37743505]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMDEPARTMENT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMDEPARTMENT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMDEPARTMENT](
    [DEPARTMENTID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DISPENSEPRINTERGROUPID] [nvarchar](10) NULL,
    [DISPENSEPRINTERSEQNUM] [int] NULL,
    [NAMEALIAS] [nvarchar](20) NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20111DEPARTMENTIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [DEPARTMENTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DEPAR__3B44C5E9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__DEPAR__3B44C5E9]  DEFAULT ('') FOR [DEPARTMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTI__NAME__3C38EA22]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENTI__NAME__3C38EA22]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISPE__3E213294]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__DISPE__3E213294]  DEFAULT ('') FOR [DISPENSEPRINTERGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISPE__3F1556CD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__DISPE__3F1556CD]  DEFAULT ((0)) FOR [DISPENSEPRINTERSEQNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__NAMEA__40097B06]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__NAMEA__40097B06]  DEFAULT ('') FOR [NAMEALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__40FD9F3F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__40FD9F3F]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__41F1C378]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__41F1C378]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__42E5E7B1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__42E5E7B1]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__43DA0BEA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMDEPARTMENT] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__43DA0BEA]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMFAMILY ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMFAMILY]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMFAMILY](
    [FAMILYID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [SAMESALESPRICE] [int] NULL,
    [SAMECOSTPRICE] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20112FAMILYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [FAMILYID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__FAMIL__47AA9CCE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMFAMILY] ADD  CONSTRAINT [DF__RBOINVENT__FAMIL__47AA9CCE]  DEFAULT ('') FOR [FAMILYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTI__NAME__489EC107]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMFAMILY] ADD  CONSTRAINT [DF__RBOINVENTI__NAME__489EC107]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SAMES__4992E540]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMFAMILY] ADD  CONSTRAINT [DF__RBOINVENT__SAMES__4992E540]  DEFAULT ((0)) FOR [SAMESALESPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SAMEC__4A870979]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMFAMILY] ADD  CONSTRAINT [DF__RBOINVENT__SAMEC__4A870979]  DEFAULT ((0)) FOR [SAMECOSTPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__4B7B2DB2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMFAMILY] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__4B7B2DB2]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMIMAGE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMIMAGE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMIMAGE](
    [ITEMID] [nvarchar](20) NOT NULL,
    [IMAGE] [image] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMI__6CDC217D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMIMAGE] ADD  CONSTRAINT [DF__RBOINVENT__ITEMI__6CDC217D]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__IMAGE__6DD045B6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMIMAGE] ADD  CONSTRAINT [DF__RBOINVENT__IMAGE__6DD045B6]  DEFAULT (NULL) FOR [IMAGE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__6EC469EF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMIMAGE] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__6EC469EF]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMLABEL ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMLABEL]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMLABEL](
    [TYPE] [int] NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [ITEMBARCODE] [nvarchar](80) NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [QTY] [numeric](28, 12) NULL,
    [TEXT2] [nvarchar](50) NULL,
    [TEXT1] [nvarchar](50) NULL,
    [PRICE] [numeric](28, 12) NULL,
    [PRIMARYKEY] [nvarchar](30) NULL,
    [VALIDONDATE] [datetime] NOT NULL,
    [PRINTED] [int] NULL,
    [COMPLABELPRICE] [numeric](28, 12) NULL,
    [UNITID] [nvarchar](10) NOT NULL,
    [LABELTYPE] [int] NOT NULL,
    [REPORTNAME] [nvarchar](40) NOT NULL,
    [VARIANTID] [nvarchar](10) NOT NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [CREATEDDATE] [datetime] NULL,
    [CREATEDTIME] [int] NULL,
    [CREATEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20116PRIMARYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [LABELTYPE] ASC,
    [STOREID] ASC,
    [ITEMID] ASC,
    [VARIANTID] ASC,
    [UNITID] ASC,
    [VALIDONDATE] ASC,
    [REPORTNAME] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTI__TYPE__71A0D69A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENTI__TYPE__71A0D69A]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__STORE__7294FAD3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__STORE__7294FAD3]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMB__73891F0C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__ITEMB__73891F0C]  DEFAULT ('') FOR [ITEMBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMI__747D4345]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__ITEMI__747D4345]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTIT__QTY__7571677E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENTIT__QTY__7571677E]  DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__TEXT2__76658BB7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__TEXT2__76658BB7]  DEFAULT ('') FOR [TEXT2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__TEXT1__7759AFF0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__TEXT1__7759AFF0]  DEFAULT ('') FOR [TEXT1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__PRICE__784DD429]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__PRICE__784DD429]  DEFAULT ((0)) FOR [PRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__PRIMA__7941F862]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__PRIMA__7941F862]  DEFAULT ('') FOR [PRIMARYKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__VALID__7A361C9B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__VALID__7A361C9B]  DEFAULT ('1900-01-01 00:00:00.000') FOR [VALIDONDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__PRINT__7B2A40D4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__PRINT__7B2A40D4]  DEFAULT ((0)) FOR [PRINTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__COMPL__7C1E650D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__COMPL__7C1E650D]  DEFAULT ((0)) FOR [COMPLABELPRICE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__UNITI__7D128946]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__UNITI__7D128946]  DEFAULT ('') FOR [UNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__LABEL__7E06AD7F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__LABEL__7E06AD7F]  DEFAULT ((0)) FOR [LABELTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__REPOR__7EFAD1B8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__REPOR__7EFAD1B8]  DEFAULT ('') FOR [REPORTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__VARIA__7FEEF5F1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__VARIA__7FEEF5F1]  DEFAULT ('') FOR [VARIANTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__00E31A2A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__00E31A2A]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__01D73E63]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__01D73E63]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MODIF__02CB629C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__MODIF__02CB629C]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__CREAT__03BF86D5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__CREAT__03BF86D5]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CREATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__CREAT__04B3AB0E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__CREAT__04B3AB0E]  DEFAULT ((0)) FOR [CREATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__CREAT__05A7CF47]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__CREAT__05A7CF47]  DEFAULT ('?') FOR [CREATEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__069BF380]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABEL] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__069BF380]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMLABELREPORTSETUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMLABELREPORTSETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMLABELREPORTSETUP](
    [TYPE] [int] NOT NULL,
    [REPORTNAME] [nvarchar](40) NOT NULL,
    [PRIMARYKEY] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20117TYPENAMEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [TYPE] ASC,
    [REPORTNAME] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENTI__TYPE__0A6C8464]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELREPORTSETUP] ADD  CONSTRAINT [DF__RBOINVENTI__TYPE__0A6C8464]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__REPOR__0B60A89D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELREPORTSETUP] ADD  CONSTRAINT [DF__RBOINVENT__REPOR__0B60A89D]  DEFAULT ('') FOR [REPORTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__PRIMA__0C54CCD6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELREPORTSETUP] ADD  CONSTRAINT [DF__RBOINVENT__PRIMA__0C54CCD6]  DEFAULT ('') FOR [PRIMARYKEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__0D48F10F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELREPORTSETUP] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__0D48F10F]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMLABELSETUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMLABELSETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMLABELSETUP](
    [ITEMID] [nvarchar](20) NOT NULL,
    [TEXT1] [nvarchar](50) NULL,
    [TEXT2] [nvarchar](50) NULL,
    [TEXT1ISITEMDESCRIPTION] [int] NULL,
    [LABELTYPE] [int] NOT NULL,
    [REPORTNAME] [nvarchar](40) NOT NULL,
    [DISTRIBUTIONSUBGROUPID] [nvarchar](10) NULL,
    [DISTRIBUTIONGROUPID] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20118TYPEITEMPRICEGROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [LABELTYPE] ASC,
    [ITEMID] ASC,
    [REPORTNAME] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMI__111981F3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__ITEMI__111981F3]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__TEXT1__120DA62C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__TEXT1__120DA62C]  DEFAULT ('') FOR [TEXT1]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__TEXT2__1301CA65]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__TEXT2__1301CA65]  DEFAULT ('') FOR [TEXT2]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__TEXT1__13F5EE9E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__TEXT1__13F5EE9E]  DEFAULT ((0)) FOR [TEXT1ISITEMDESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__LABEL__14EA12D7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__LABEL__14EA12D7]  DEFAULT ((0)) FOR [LABELTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__REPOR__15DE3710]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__REPOR__15DE3710]  DEFAULT ('') FOR [REPORTNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISTR__16D25B49]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__DISTR__16D25B49]  DEFAULT ('') FOR [DISTRIBUTIONSUBGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISTR__17C67F82]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__DISTR__17C67F82]  DEFAULT ('') FOR [DISTRIBUTIONGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__18BAA3BB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMLABELSETUP] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__18BAA3BB]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMSECTIONLOCATION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMSECTIONLOCATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMSECTIONLOCATION](
    [ITEMID] [nvarchar](20) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [SECTIONID] [nvarchar](10) NOT NULL,
    [SHELFID] [nvarchar](10) NOT NULL,
    [SHOWSSALESSTATISTICS] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20119PRIMARYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [STOREID] ASC,
    [SECTIONID] ASC,
    [SHELFID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMI__1C8B349F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSECTIONLOCATION] ADD  CONSTRAINT [DF__RBOINVENT__ITEMI__1C8B349F]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__STORE__1D7F58D8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSECTIONLOCATION] ADD  CONSTRAINT [DF__RBOINVENT__STORE__1D7F58D8]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SECTI__1E737D11]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSECTIONLOCATION] ADD  CONSTRAINT [DF__RBOINVENT__SECTI__1E737D11]  DEFAULT ('') FOR [SECTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SHELF__1F67A14A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSECTIONLOCATION] ADD  CONSTRAINT [DF__RBOINVENT__SHELF__1F67A14A]  DEFAULT ('') FOR [SHELFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__SHOWS__205BC583]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSECTIONLOCATION] ADD  CONSTRAINT [DF__RBOINVENT__SHOWS__205BC583]  DEFAULT ((0)) FOR [SHOWSSALESSTATISTICS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__214FE9BC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSECTIONLOCATION] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__214FE9BC]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMSTOREORDERINGINFO ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMSTOREORDERINGINFO]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO](
    [DISTRIBUTIONSUBGROUPID] [nvarchar](10) NOT NULL,
    [DISTRIBUTIONGROUPID] [nvarchar](10) NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [REORDERPOINT] [numeric](28, 12) NULL,
    [MAXIMUMSHELFINVENTORY] [numeric](28, 12) NULL,
    [MAXIMUMINVENTORY] [numeric](28, 12) NULL,
    [REORDERQTY] [numeric](28, 12) NULL,
    [REORDERPOINTINSHELF] [numeric](28, 12) NULL,
    [VENDACCOUNT] [nvarchar](10) NULL,
    [VENDITEMID] [nvarchar](20) NULL,
    [LEADTIMECALCULATION] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20120ITEMDISTRIBUTIONGR20001] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [DISTRIBUTIONGROUPID] ASC,
    [DISTRIBUTIONSUBGROUPID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISTR__25207AA0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__DISTR__25207AA0]  DEFAULT ('') FOR [DISTRIBUTIONSUBGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DISTR__26149ED9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__DISTR__26149ED9]  DEFAULT ('') FOR [DISTRIBUTIONGROUPID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__ITEMI__2708C312]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__ITEMI__2708C312]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__REORD__27FCE74B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__REORD__27FCE74B]  DEFAULT ((0)) FOR [REORDERPOINT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MAXIM__28F10B84]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__MAXIM__28F10B84]  DEFAULT ((0)) FOR [MAXIMUMSHELFINVENTORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__MAXIM__29E52FBD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__MAXIM__29E52FBD]  DEFAULT ((0)) FOR [MAXIMUMINVENTORY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__REORD__2AD953F6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__REORD__2AD953F6]  DEFAULT ((0)) FOR [REORDERQTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__REORD__2BCD782F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__REORD__2BCD782F]  DEFAULT ((0)) FOR [REORDERPOINTINSHELF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__VENDA__2CC19C68]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__VENDA__2CC19C68]  DEFAULT ('') FOR [VENDACCOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__VENDI__2DB5C0A1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__VENDI__2DB5C0A1]  DEFAULT ('') FOR [VENDITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__LEADT__2EA9E4DA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__LEADT__2EA9E4DA]  DEFAULT ((0)) FOR [LEADTIMECALCULATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOINVENT__DATAA__2F9E0913]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMSTOREORDERINGINFO] ADD  CONSTRAINT [DF__RBOINVENT__DATAA__2F9E0913]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMTXT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMTXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMTXT](
    [ITEMID] [nvarchar](20) NOT NULL,
    [TEXTTYPE] [int] NOT NULL,
    [LANGUAGEID] [nvarchar](7) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20062ITEMTYPELANGUAGEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [TEXTTYPE] ASC,
    [LANGUAGEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__ITEMI__02215726]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXT] ADD  CONSTRAINT [DF__POSINVENT__ITEMI__02215726]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__TEXTT__03157B5F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXT] ADD  CONSTRAINT [DF__POSINVENT__TEXTT__03157B5F]  DEFAULT ((0)) FOR [TEXTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__LANGU__04099F98]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXT] ADD  CONSTRAINT [DF__POSINVENT__LANGU__04099F98]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__DATAA__04FDC3D1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXT] ADD  CONSTRAINT [DF__POSINVENT__DATAA__04FDC3D1]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTITEMTXTLINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTITEMTXTLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTITEMTXTLINE](
    [LANGUAGEID] [nvarchar](7) NOT NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [TEXTTYPE] [int] NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [TXT] [nvarchar](50) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20063ITEMTYPELANGUAGELINEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC,
    [TEXTTYPE] ASC,
    [LANGUAGEID] ASC,
    [LINENUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__LANGU__08CE54B5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXTLINE] ADD  CONSTRAINT [DF__POSINVENT__LANGU__08CE54B5]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__ITEMI__09C278EE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXTLINE] ADD  CONSTRAINT [DF__POSINVENT__ITEMI__09C278EE]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__TEXTT__0AB69D27]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXTLINE] ADD  CONSTRAINT [DF__POSINVENT__TEXTT__0AB69D27]  DEFAULT ((0)) FOR [TEXTTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__LINEN__0BAAC160]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXTLINE] ADD  CONSTRAINT [DF__POSINVENT__LINEN__0BAAC160]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENTIT__TXT__0C9EE599]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXTLINE] ADD  CONSTRAINT [DF__POSINVENTIT__TXT__0C9EE599]  DEFAULT ('') FOR [TXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSINVENT__DATAA__0D9309D2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILINVENTITEMTXTLINE] ADD  CONSTRAINT [DF__POSINVENT__DATAA__0D9309D2]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILINVENTLINKEDITEM ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILINVENTLINKEDITEM]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILINVENTLINKEDITEM]
GO
CREATE VIEW [dbo].RETAILINVENTLINKEDITEM AS
(
  SELECT
    [ITEMID],
    [UNIT],
    [LINKEDITEMID],
    [QTY],
    [BLOCKED],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILINVENTLINKEDITEM
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTORY_BR ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTORY_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTORY_BR](
    [ITEMID] [nvarchar](20) NOT NULL,
    [ITEMNAME] [nvarchar](60) NOT NULL,
    [UNITID] [nvarchar](10) NOT NULL,
    [INVENTSIGNAL] [nvarchar](1) NOT NULL,
    [QTY] [numeric](28, 12) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_RETAILINVENTORY_BR] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC,
    [ITEMID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__ITEMI__52B9FAC2]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINV__ITEMI__52B9FAC2]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__ITEMN__53AE1EFB]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINV__ITEMN__53AE1EFB] DEFAULT ('') FOR [ITEMNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__UNITI__54A24334]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINV__UNITI__54A24334] DEFAULT ('') FOR [UNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__INVEN__5596676D]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINV__INVEN__5596676D] DEFAULT ('') FOR [INVENTSIGNAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINVEN__QTY__568A8BA6]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINVEN__QTY__568A8BA6] DEFAULT ((0)) FOR [QTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__TERMI__577EAFDF]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINV__TERMI__577EAFDF] DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__STORE__5872D418]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINV__STORE__5872D418] DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__DATAA__5966F851]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORY_BR] ADD CONSTRAINT [DF__RETAILINV__DATAA__5966F851] DEFAULT ('') FOR [DATAAREAID]
END
-------------------------------------------------------------------------------

-- Creating table trigger [dbo].[manualChanges_RETAILINVENTORY_BR]
PRINT N'Creating table trigger [dbo].[manualChanges_RETAILINVENTORY_BR]';

GO
IF OBJECT_ID(N'[dbo].[manualChanges_RETAILINVENTORY_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [dbo].[manualChanges_RETAILINVENTORY_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [dbo].[manualChanges_RETAILINVENTORY_BR].'
GO

CREATE TRIGGER [dbo].[manualChanges_RETAILINVENTORY_BR]
ON [dbo].[RETAILINVENTORY_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @DATAAREAIDIns NVARCHAR (4)
DECLARE @DATAAREAIDDel NVARCHAR (4)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @TERMINALIDIns NVARCHAR (10)
DECLARE @TERMINALIDDel NVARCHAR (10)
DECLARE @ITEMIDIns NVARCHAR (20
)
DECLARE @ITEMIDDel NVARCHAR (20
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORY_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORY_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORY_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORY_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT DATAAREAID , STOREID , TERMINALID , ITEMID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns , @ITEMIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @DATAAREAIDIns + @STOREIDIns + @TERMINALIDIns + @ITEMIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORY_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORY_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns , @ITEMIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT DATAAREAID , STOREID , TERMINALID , ITEMID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns , @ITEMIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT DATAAREAID , STOREID , TERMINALID , ITEMID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @DATAAREAIDDel , @STOREIDDel , @TERMINALIDDel , @ITEMIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @DATAAREAIDIns + @STOREIDIns + @TERMINALIDIns + @ITEMIDIns  

SET @primaryKeyDel = @DATAAREAIDDel + @STOREIDDel + @TERMINALIDDel + @ITEMIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORY_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORY_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILINVENTORY_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @DATAAREAIDDel , @STOREIDDel , @TERMINALIDDel , @ITEMIDDel  
FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns , @ITEMIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [dbo].[manualChanges_RETAILINVENTORY_BR]'
-- End creating table trigger [dbo].[manualChanges_RETAILINVENTORY_BR]


-------------------------------------------------------------------------------
PRINT 'Creating table RETAILINVENTORYHEADER_BR ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILINVENTORYHEADER_BR]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILINVENTORYHEADER_BR](
    [FIRSTDOCUMENTDATE] [datetime] NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [FISCALPRINTERSERIALNUMBER] [nvarchar](20) NOT NULL,
 CONSTRAINT [PK_RETAILINVENTORYHEADER_BR] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__FIRST__5C4364FC]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORYHEADER_BR] ADD CONSTRAINT [DF__RETAILINV__FIRST__5C4364FC] DEFAULT ('1900-01-01 00:00:00.000') FOR [FIRSTDOCUMENTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__TERMI__5D378935]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORYHEADER_BR] ADD CONSTRAINT [DF__RETAILINV__TERMI__5D378935] DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__STORE__5E2BAD6E]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORYHEADER_BR] ADD CONSTRAINT [DF__RETAILINV__STORE__5E2BAD6E] DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__DATAA__5F1FD1A7]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORYHEADER_BR] ADD CONSTRAINT [DF__RETAILINV__DATAA__5F1FD1A7] DEFAULT ('') FOR [DATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILINV__FISCA__3084DE4F]'))
BEGIN
ALTER TABLE [dbo].[RETAILINVENTORYHEADER_BR] ADD CONSTRAINT [DF__RETAILINV__FISCA__3084DE4F] DEFAULT ('') FOR [FISCALPRINTERSERIALNUMBER]
END
-------------------------------------------------------------------------------

-- Creating table trigger [dbo].[manualChanges_RETAILINVENTORYHEADER_BR]
PRINT N'Creating table trigger [dbo].[manualChanges_RETAILINVENTORYHEADER_BR]';

GO
IF OBJECT_ID(N'[dbo].[manualChanges_RETAILINVENTORYHEADER_BR]', N'TR') IS NOT NULL
BEGIN
    DROP TRIGGER [dbo].[manualChanges_RETAILINVENTORYHEADER_BR]
END
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table trigger [dbo].[manualChanges_RETAILINVENTORYHEADER_BR].'
GO

CREATE TRIGGER [dbo].[manualChanges_RETAILINVENTORYHEADER_BR]
ON [dbo].[RETAILINVENTORYHEADER_BR]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @app NVARCHAR(128)
DECLARE @DATAAREAIDIns NVARCHAR (4)
DECLARE @DATAAREAIDDel NVARCHAR (4)
DECLARE @STOREIDIns NVARCHAR (10)
DECLARE @STOREIDDel NVARCHAR (10)
DECLARE @TERMINALIDIns NVARCHAR (10
)
DECLARE @TERMINALIDDel NVARCHAR (10
)

DECLARE @primaryKeyIns NVARCHAR(200)
DECLARE @primaryKeyDel NVARCHAR(200)

SET NOCOUNT ON
SET @app = APP_NAME()
IF (@app <> 'Commerce Data Exchange Async Client') 
AND (@app <> 'Microsoft Dynamics AX for Retail POS') 
AND (@app <> 'Retail Offline Sync Service')
AND EXISTS(SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME='RETAILMANUALCHANGESLOG_BR' AND PRIMARYKEY = 'ENABLED')
BEGIN
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORYHEADER_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORYHEADER_BR', N'INSORDEL', @app)
END
ELSE
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORYHEADER_BR' AND PRIMARYKEY = N'INSORDEL')
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORYHEADER_BR', N'INSORDEL', @app)

DECLARE insertedCursor CURSOR
FOR SELECT DATAAREAID , STOREID , TERMINALID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @DATAAREAIDIns + @STOREIDIns + @TERMINALIDIns  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORYHEADER_BR' AND PRIMARYKEY = @primaryKeyIns)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORYHEADER_BR', @primaryKeyIns, @app)

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns  
END

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
ELSE
-- update
BEGIN
DECLARE insertedCursor CURSOR
FOR SELECT DATAAREAID , STOREID , TERMINALID  
FROM inserted
OPEN insertedCursor

FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns  

DECLARE deletedCursor CURSOR
FOR SELECT DATAAREAID , STOREID , TERMINALID  
FROM deleted
OPEN deletedCursor

FETCH NEXT FROM deletedCursor INTO @DATAAREAIDDel , @STOREIDDel , @TERMINALIDDel  

WHILE @@FETCH_STATUS = 0
BEGIN
SET @primaryKeyIns = @DATAAREAIDIns + @STOREIDIns + @TERMINALIDIns  

SET @primaryKeyDel = @DATAAREAIDDel + @STOREIDDel + @TERMINALIDDel  

IF NOT EXISTS (SELECT * FROM [ax].[RETAILMANUALCHANGESLOG_BR] WHERE TABLENAME = N'RETAILINVENTORYHEADER_BR' AND PRIMARYKEY = @primaryKeyDel)
INSERT INTO [ax].[RETAILMANUALCHANGESLOG_BR] VALUES (N'RETAILINVENTORYHEADER_BR', @primaryKeyIns, @app)
ELSE
UPDATE [ax].[RETAILMANUALCHANGESLOG_BR] SET PRIMARYKEY = @primaryKeyIns WHERE TABLENAME = N'RETAILINVENTORYHEADER_BR' AND PRIMARYKEY = @primaryKeyDel

FETCH NEXT FROM deletedCursor INTO @DATAAREAIDDel , @STOREIDDel , @TERMINALIDDel  
FETCH NEXT FROM insertedCursor INTO @DATAAREAIDIns , @STOREIDIns , @TERMINALIDIns  
END

CLOSE deletedCursor
DEALLOCATE deletedCursor

CLOSE insertedCursor
DEALLOCATE insertedCursor
END
END
END;


GO
PRINT N'Finished creating table trigger [dbo].[manualChanges_RETAILINVENTORYHEADER_BR]'
-- End creating table trigger [dbo].[manualChanges_RETAILINVENTORYHEADER_BR]


-------------------------------------------------------------------------------
PRINT 'Creating view RETAILINVENTTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILINVENTTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILINVENTTABLE]
GO
CREATE VIEW [dbo].RETAILINVENTTABLE AS
(
  SELECT
    [ITEMID],
    CONVERT([numeric](28, 12), 0) AS 'DEL_VALIDSALESPRICE',
    CONVERT([nvarchar](10), '') AS 'ITEMFAMILY',
    CONVERT([int], 0) AS 'NOINVENTPOSTING',
    [ZEROPRICEVALID],
    [QTYBECOMESNEGATIVE],
    [NODISCOUNTALLOWED],
    [KEYINGINPRICE],
    [SCALEITEM],
    [KEYINGINQTY],
    [DATEBLOCKED],
    [DATETOBEBLOCKED],
    [BLOCKEDONPOS],
    [BASECOMPARISONUNITCODE],
    [BARCODESETUPID],
    [PRINTVARIANTSSHELFLABELS],
    [USEEANSTANDARDBARCODE],
    [DATAAREAID],
    [RECID],
    [MUSTKEYINCOMMENT],
    [DATETOACTIVATEITEM],
    [PROHIBITRETURN_RU]
  FROM [ax].RETAILINVENTTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILJOBPOSPERMISSIONGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILJOBPOSPERMISSIONGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILJOBPOSPERMISSIONGROUP]
GO
CREATE VIEW [dbo].RETAILJOBPOSPERMISSIONGROUP AS
(
  SELECT
    [RECID],
    [JOB],
    [RETAILPOSPERMISSIONGROUP]
  FROM [ax].RETAILJOBPOSPERMISSIONGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKEYBOARDBUTTONCONTROL ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKEYBOARDBUTTONCONTROL]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKEYBOARDBUTTONCONTROL]
GO
CREATE VIEW [dbo].RETAILKEYBOARDBUTTONCONTROL AS
(
  SELECT
    [BUTTONCONTROLID],
    [NAME],
    [DEFAULTFONT],
    [DEFAULTCOLOR],
    [DEFAULTFONTSIZE],
    [DEFAULTFONTSTYLE],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILKEYBOARDBUTTONCONTROL
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKEYBOARDBUTTONCONTROLB ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKEYBOARDBUTTONCONTROLB]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKEYBOARDBUTTONCONTROLB]
GO
CREATE VIEW [dbo].RETAILKEYBOARDBUTTONCONTROLB AS
(
  SELECT
    [ID],
    [BUTTONCONTROLID],
    [ROWNUM],
    CONVERT([int], 0) AS 'TYPE',
    CONVERT([int], 0) AS 'OPERATIONID',
    CONVERT([nvarchar](50), '') AS 'SHOWMENUID',
    [ACTION],
    [ACTIONPROPERTY],
    [PICTURE],
    [DISPLAYTEXT],
    [COLOUR],
    [FONTSIZE],
    [FONTSTYLE],
    [DATAAREAID],
    [RECID],
    CONVERT([text], NULL) AS 'ALLES'
  FROM [ax].RETAILKEYBOARDBUTTONCONTROLB
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKEYBOARDMAPPINGTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKEYBOARDMAPPINGTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKEYBOARDMAPPINGTABLE]
GO
CREATE VIEW [dbo].RETAILKEYBOARDMAPPINGTABLE AS
(
  SELECT
    [KEYBOARDMAPPINGID],
    [DESCRIPTION],
    [RECID]
  FROM [ax].RETAILKEYBOARDMAPPINGTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKEYBOARDMAPPINGTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKEYBOARDMAPPINGTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKEYBOARDMAPPINGTRANS]
GO
CREATE VIEW [dbo].RETAILKEYBOARDMAPPINGTRANS AS
(
  SELECT
    [KEYBOARDMAPPINGID],
    [ASCIIVALUE],
    [KEYCHAR],
    [ACTION],
    [ACTIONPROPERTY],
    [RECID]
  FROM [ax].RETAILKEYBOARDMAPPINGTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILKEYCOMMAND ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILKEYCOMMAND]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILKEYCOMMAND](
    [PROFILEID] [nvarchar](10) NOT NULL,
    [KEYNAME] [nvarchar](30) NOT NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [KEYTYPE] [int] NULL,
    [KEYID] [int] NULL,
    [WEDGETYPE] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20064PROFILEKEYIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [PROFILEID] ASC,
    [KEYNAME] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYCOM__PROFI__11639AB6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYCOMMAND] ADD  CONSTRAINT [DF__POSKEYCOM__PROFI__11639AB6]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYCOM__KEYNA__1257BEEF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYCOMMAND] ADD  CONSTRAINT [DF__POSKEYCOM__KEYNA__1257BEEF]  DEFAULT ('') FOR [KEYNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYCOM__DESCR__134BE328]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYCOMMAND] ADD  CONSTRAINT [DF__POSKEYCOM__DESCR__134BE328]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYCOM__KEYTY__14400761]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYCOMMAND] ADD  CONSTRAINT [DF__POSKEYCOM__KEYTY__14400761]  DEFAULT ((0)) FOR [KEYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYCOM__KEYID__15342B9A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYCOMMAND] ADD  CONSTRAINT [DF__POSKEYCOM__KEYID__15342B9A]  DEFAULT ((0)) FOR [KEYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYCOM__WEDGE__16284FD3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYCOMMAND] ADD  CONSTRAINT [DF__POSKEYCOM__WEDGE__16284FD3]  DEFAULT ((0)) FOR [WEDGETYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYCOM__DATAA__171C740C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYCOMMAND] ADD  CONSTRAINT [DF__POSKEYCOM__DATAA__171C740C]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILKEYMAPPING ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILKEYMAPPING]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILKEYMAPPING](
    [PROFILEID] [nvarchar](10) NOT NULL,
    [MAPFROM] [nvarchar](30) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [MAPTO] [nvarchar](30) NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20065PROFILEMAPFROMIDX] PRIMARY KEY CLUSTERED
(
    [PROFILEID] ASC,
    [MAPFROM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYMAP__PROFI__1AED04F0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYMAPPING] ADD  CONSTRAINT [DF__POSKEYMAP__PROFI__1AED04F0]  DEFAULT ('') FOR [PROFILEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYMAP__MAPFR__1BE12929]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYMAPPING] ADD  CONSTRAINT [DF__POSKEYMAP__MAPFR__1BE12929]  DEFAULT ('') FOR [MAPFROM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYMAPP__NAME__1CD54D62]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYMAPPING] ADD  CONSTRAINT [DF__POSKEYMAPP__NAME__1CD54D62]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSKEYMAP__MAPTO__1DC9719B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILKEYMAPPING] ADD  CONSTRAINT [DF__POSKEYMAP__MAPTO__1DC9719B]  DEFAULT ('') FOR [MAPTO]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKIT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKIT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKIT]
GO
CREATE VIEW [dbo].RETAILKIT AS
(
  SELECT
    [DISCONTINUEKIT],
    [STATUS],
    [DISASSEMBLYATREGISTERALLOWED],
    [PRODUCTMASTER],
    [RECID]
  FROM [ax].RETAILKIT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKITCOMPONENT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKITCOMPONENT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKITCOMPONENT]
GO
CREATE VIEW [dbo].RETAILKITCOMPONENT AS
(
  SELECT
    [COMPONENT],
    [KIT],
    [QUANTITY],
    [UNITOFMEASURE],
    [DONOTSHOWATREGISTER],
    [MODIFIEDDATETIME],
    [CREATEDDATETIME],
    [RECID]
  FROM [ax].RETAILKITCOMPONENT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKITCOMPONENTSUBSTITUTE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKITCOMPONENTSUBSTITUTE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKITCOMPONENTSUBSTITUTE]
GO
CREATE VIEW [dbo].RETAILKITCOMPONENTSUBSTITUTE AS
(
  SELECT
    [KITCOMPONENT],
    [QUANTITY],
    [SUBSTITUTEPRODUCT],
    [UNITOFMEASURE],
    [RECID]
  FROM [ax].RETAILKITCOMPONENTSUBSTITUTE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILKITVARIANTCOMPONENT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILKITVARIANTCOMPONENT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILKITVARIANTCOMPONENT]
GO
CREATE VIEW [dbo].RETAILKITVARIANTCOMPONENT AS
(
  SELECT
    [COMPONENT],
    [COMPONENTRECID],
    [QUANTITY],
    [UNITOFMEASURE],
    [RECID],
    [KITVARIANT]
  FROM [ax].RETAILKITVARIANTCOMPONENT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILLABELGENERATION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILLABELGENERATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILLABELGENERATION](
    [ITEMID] [nvarchar](20) NOT NULL,
    [SHELFLABELGENERATED] [int] NULL,
    [ITEMLABELGENERATED] [int] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [CREATEDDATE] [datetime] NULL,
    [CREATEDTIME] [int] NULL,
    [CREATEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20176ITEMIDIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [ITEMID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__ITEMI__283CDE6D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__ITEMI__283CDE6D]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__SHELF__293102A6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__SHELF__293102A6]  DEFAULT ((0)) FOR [SHELFLABELGENERATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__ITEML__2A2526DF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__ITEML__2A2526DF]  DEFAULT ((0)) FOR [ITEMLABELGENERATED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__MODIF__2B194B18]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__MODIF__2B194B18]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__MODIF__2C0D6F51]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__MODIF__2C0D6F51]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__MODIF__2D01938A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__MODIF__2D01938A]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__CREAT__2DF5B7C3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__CREAT__2DF5B7C3]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CREATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__CREAT__2EE9DBFC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__CREAT__2EE9DBFC]  DEFAULT ((0)) FOR [CREATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__CREAT__2FDE0035]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__CREAT__2FDE0035]  DEFAULT ('?') FOR [CREATEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOLABELG__DATAA__30D2246E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILLABELGENERATION] ADD  CONSTRAINT [DF__RBOLABELG__DATAA__30D2246E]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILLANGUAGETEXT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILLANGUAGETEXT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILLANGUAGETEXT]
GO
CREATE VIEW [dbo].RETAILLANGUAGETEXT AS
(
  SELECT
    [LANGUAGEID],
    [TEXTID],
    [TEXT],
    [ERRORTEXT],
    [MODULEID],
    [ACTIVE],
    [FIRSTINVERSION],
    [DATECREATED],
    [DATEUPDATED],
    [RECID],
    [DATAAREAID]
  FROM [ax].RETAILLANGUAGETEXT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILLOG ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILLOG]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILLOG]
GO
CREATE VIEW [dbo].RETAILLOG AS
(
  SELECT
    [LOGDATE],
    [CODEUNIT],
    [LOGLEVEL],
    [LOGSTRING],
    [STOREID],
    [TERMINALID],
    [DURATIONINMILLISEC],
    [DATAAREAID],
    [RETAILLOGID]
  FROM [ax].RETAILLOG
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILLOYALTYTIER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILLOYALTYTIER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILLOYALTYTIER]
GO
CREATE VIEW [dbo].RETAILLOYALTYTIER AS
(
  SELECT
    [RECID],
    [AFFILIATION],
    [TIERID],
    [TIERLEVEL],
    [VALIDDATEINTERVAL]
  FROM [ax].RETAILLOYALTYTIER
);
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILMIXANDMATCHLINEGROUPS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILMIXANDMATCHLINEGROUPS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILMIXANDMATCHLINEGROUPS]
GO
CREATE VIEW [dbo].RETAILMIXANDMATCHLINEGROUPS AS
(
  SELECT
    [MIXANDMATCHID],
    [NUMBEROFITEMSNEEDED],
    [DISCOUNTLINECOLORID],
    [MIXANDMATCHLINEGROUP],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILMIXANDMATCHLINEGROUPS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILOFFLINEPROFILE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILOFFLINEPROFILE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILOFFLINEPROFILE]
GO
CREATE VIEW [dbo].RETAILOFFLINEPROFILE AS
(
  SELECT
    [DESCRIPTION],
    [NAME],
    [RECID]
  FROM [ax].RETAILOFFLINEPROFILE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILOFFLINEPROFILESCOPES ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILOFFLINEPROFILESCOPES]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILOFFLINEPROFILESCOPES]
GO
CREATE VIEW [dbo].RETAILOFFLINEPROFILESCOPES AS
(
  SELECT
    [SCOPEID],
    [PROFILEID],
    [RECID]
  FROM [ax].RETAILOFFLINEPROFILESCOPES
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILOFFLINESCOPE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILOFFLINESCOPE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILOFFLINESCOPE]
GO
CREATE VIEW [dbo].RETAILOFFLINESCOPE AS
(
  SELECT
    [SYNCDIRECTION],
    [SYNCFREQUENCY],
    [LASTSYNCTIME],
    [LASTSYNCTIMETZID],
    [DESCRIPTION],
    [RECID]
  FROM [ax].RETAILOFFLINESCOPE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILOFFLINESCOPETABLES ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILOFFLINESCOPETABLES]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILOFFLINESCOPETABLES]
GO
CREATE VIEW [dbo].RETAILOFFLINESCOPETABLES AS
(
  SELECT
    [SCOPEID],
    [SYNCTABLEID],
    [RECID]
  FROM [ax].RETAILOFFLINESCOPETABLES
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILOFFLINESYNCLOG ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILOFFLINESYNCLOG]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILOFFLINESYNCLOG](
    [RECID] [bigint] NOT NULL,
    [LOGTIME] [datetime] NOT NULL,
    [LOGTIMETZID] [int] NOT NULL,
    [SCOPEID] [bigint] NOT NULL,
    [TOTALDOWNLOADED] [int] NOT NULL,
    [TOTALDOWNLOADEDOK] [int] NOT NULL,
    [TOTALDOWNLOADEDERR] [int] NOT NULL,
    [TOTALUPLOADED] [int] NOT NULL,
    [TOTALUPLOADEDOK] [int] NOT NULL,
    [TOTALUPLOADEDERR] [int] NOT NULL,
    [SYNCSTARTTIME] [datetime] NOT NULL,
    [SYNCSTARTTIMETZID] [int] NOT NULL,
    [SYNCSTOPTIME] [datetime] NOT NULL,
    [SYNCSTOPTIMETZID] [int] NOT NULL,
    [TERMINAL] [nvarchar](10) NOT NULL,
    [REPLICATIONCOUNTER] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_RETAILOFFLINESYNCLOG] PRIMARY KEY CLUSTERED
(
    [REPLICATIONCOUNTER] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id(N'[dbo].[RETAILOFFLINESYNCLOG]') AND NAME = N'IX_RETAILOFFLINESYNCLOG_SCOPEID')
BEGIN
CREATE NONCLUSTERED INDEX [IX_RETAILOFFLINESYNCLOG_SCOPEID] ON [dbo].[RETAILOFFLINESYNCLOG]
(
    [SCOPEID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id(N'[dbo].[RETAILOFFLINESYNCLOG]') AND NAME = N'IX_RETAILOFFLINESYNCLOG_TERMINALID')
BEGIN
CREATE NONCLUSTERED INDEX [IX_RETAILOFFLINESYNCLOG_TERMINALID] ON [dbo].[RETAILOFFLINESYNCLOG]
(
    [TERMINAL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id(N'[dbo].[RETAILOFFLINESYNCLOG]') AND NAME = N'IX_RETAILOFFLINESYNCLOG_SYNCSTOPTIME')
BEGIN
CREATE NONCLUSTERED INDEX [IX_RETAILOFFLINESYNCLOG_SYNCSTOPTIME] ON [dbo].[RETAILOFFLINESYNCLOG]
(
    [SYNCSTOPTIME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__LOGTI__4BED01A2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__LOGTI__4BED01A2] DEFAULT ('1900-01-01 00:00:00.000') FOR [LOGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__LOGTI__4CE125DB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__LOGTI__4CE125DB] DEFAULT ((37001)) FOR [LOGTIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__SCOPE__4DD54A14]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__SCOPE__4DD54A14] DEFAULT ((0)) FOR [SCOPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__TOTAL__4EC96E4D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__TOTAL__4EC96E4D] DEFAULT ((0)) FOR [TOTALDOWNLOADED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__TOTAL__4FBD9286]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__TOTAL__4FBD9286] DEFAULT ((0)) FOR [TOTALDOWNLOADEDOK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__TOTAL__50B1B6BF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__TOTAL__50B1B6BF] DEFAULT ((0)) FOR [TOTALDOWNLOADEDERR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__TOTAL__51A5DAF8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__TOTAL__51A5DAF8] DEFAULT ((0)) FOR [TOTALUPLOADED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__TOTAL__5299FF31]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__TOTAL__5299FF31] DEFAULT ((0)) FOR [TOTALUPLOADEDOK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__TOTAL__538E236A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__TOTAL__538E236A] DEFAULT ((0)) FOR [TOTALUPLOADEDERR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__SYNCS__548247A3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__SYNCS__548247A3] DEFAULT ('1900-01-01 00:00:00.000') FOR [SYNCSTARTTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__SYNCS__55766BDC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__SYNCS__55766BDC] DEFAULT ((37001)) FOR [SYNCSTARTTIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__SYNCS__566A9015]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__SYNCS__566A9015] DEFAULT ('1900-01-01 00:00:00.000') FOR [SYNCSTOPTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__SYNCS__575EB44E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__SYNCS__575EB44E] DEFAULT ((37001)) FOR [SYNCSTOPTIMETZID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILOFF__TERMI__5852D887]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILOFFLINESYNCLOG] ADD CONSTRAINT [DF__RETAILOFF__TERMI__5852D887] DEFAULT ('') FOR [TERMINAL]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILOFFLINETABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILOFFLINETABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILOFFLINETABLE]
GO
CREATE VIEW [dbo].RETAILOFFLINETABLE AS
(
  SELECT
    [TABLENAME],
    [RECID]
  FROM [ax].RETAILOFFLINETABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILOPERATIONS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILOPERATIONS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILOPERATIONS]
GO
CREATE VIEW [dbo].RETAILOPERATIONS AS
(
  SELECT
    [OPERATIONID],
    [OPERATIONNAME],
    [PERMISSIONID],
    [PERMISSIONID2],
    [CHECKUSERACCESS],
    [USEROPERATION],
    [RECID]
  FROM [ax].RETAILOPERATIONS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPARAMETERS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPARAMETERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPARAMETERS]
GO
CREATE VIEW [dbo].RETAILPARAMETERS AS
(
  SELECT
    [KEY] AS 'KEY_',
    [GIFTCARDITEM],
    CONVERT([int], 0) AS 'SYSTEMINUSE',
    CONVERT([nvarchar](10), '') AS 'LOCALSTOREID',
    [ITEMSALESSTATISTICSON],
    [TERMINALSTATISTICS],
    [STAFFSTATISTICS],
    [PAYMENTSTATISTICS],
    CONVERT([int], 0) AS 'UPDATESTATISTICS',
    CONVERT([int], 0) AS 'REPLICATEUSINGPREACTIONS',
    [MIXANDMATCHACTIVITYTYPE],
    [DISCOUNTOFFERACTIVITYTYPE],
    [MULTIBUYACTIVITYTYPE],
    CONVERT([int], 0) AS 'NUMBEROFRETRIES',
    CONVERT([int], 0) AS 'MINUTESBETWEENTRIES',
    [EANLICENSENO],
    [ITEMLABELSFORNEGATIVESTOCK],
    [DEFAULTCUSTOMERPOSTING],
    CONVERT([int], 0) AS 'DEFAULTITEMTYPE',
    [POSTTOTALDISC],
    [POSTINFOCODEDISC],
    [POSTPERIODICDISC],
    [POSTLINEDISC],
    [POSTCUSTDISC],
    [SHELFLABELLASTACTION],
    [ITEMLABELLASTACTION],
    CONVERT([int], 0) AS 'ITEMLABELS',
    CONVERT([int], 0) AS 'SHELFLABELS',
    CONVERT([int], 0) AS 'ITEMLABELSFORALL',
    CONVERT([int], 0) AS 'SHELFLABELSFORALL',
    CONVERT([bigint], 0) AS 'EXCHANGERATETYPE',
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID],
    [RECEIPTOPTION],
    [DEFAULTORDERTYPE],
    [MINIMUMDEPOSITFORSALESORDER],
    [EXPIRATIONDATE],
    [CANCELLATIONCHARGE],
    CONVERT([numeric](32, 16), 0) AS 'MINIMUMDEPOSITFORQUOTATION',
    [SHIPPINGCHARGECODE],
    [CANCELLATIONCHARGECODE],
    [PICKUPDELIVERYMODECODE],
    [MINIMUMPASSWORDLENGTH],
    [PROCESSRETURNSASINORIGINALSALESHIFT_RU],
    [PROCESSGIFTCARDSASPREPAYMENTS_RU],
    [REQUIRESPECIALCHAR],
    [REQUIRENUMERICCHAR],
    [REQUIREUPPERCASE],
    [AUTOMATICRETURNOFLOYALTYPAYMENT_RU],
    [AWARDPOINTSFORPARTIALREDEMPTION_RU],
    [PROPOSEREFUNDPAYMENTAMOUNT_RU]
  FROM [ax].RETAILPARAMETERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPERIODICDISCOUNT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPERIODICDISCOUNT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPERIODICDISCOUNT]
GO
CREATE VIEW [dbo].RETAILPERIODICDISCOUNT AS
(
  SELECT
    [OFFERID],
    [CONCURRENCYMODE],
    [CURRENCYCODE],
    [DATEVALIDATIONTYPE],
    [NAME],
    [DISCOUNTPERCENTVALUE],
    [INSTANCERELATIONTYPE],
    [PERIODICDISCOUNTTYPE],
    [PRICEDISCGROUP],
    [STATUS],
    [VALIDATIONPERIODID],
    [VALIDFROM],
    [VALIDTO],
    [DATAAREAID],
    [RELATIONTYPE],
    [RECID],
    [ISDISCOUNTCODEREQUIRED]
  FROM [ax].RETAILPERIODICDISCOUNT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPERIODICDISCOUNTLINE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPERIODICDISCOUNTLINE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPERIODICDISCOUNTLINE]
GO
CREATE VIEW [dbo].RETAILPERIODICDISCOUNTLINE AS
(
  SELECT
    [OFFERID],
    [DATAAREAID],
    [RECID],
    [NAME],
    [DISCOUNTPERCENTORVALUE],
    [INSTANCERELATIONTYPE],
    [LINENUM],
    [RETAILGROUPMEMBERLINE],
    [STATUS],
    [UNITOFMEASURE],
    [RELATIONTYPE],
    [ISDISCOUNTCODEREQUIRED]
  FROM [ax].RETAILPERIODICDISCOUNTLINE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPERMISSIONS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPERMISSIONS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPERMISSIONS]
GO
CREATE VIEW [dbo].RETAILPERMISSIONS AS
(
  SELECT
    [PERMISSIONID],
    [PERMISSIONNAME],
    [RECID]
  FROM [ax].RETAILPERMISSIONS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPOSBATCHACCOUNTTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPOSBATCHACCOUNTTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPOSBATCHACCOUNTTRANS]
GO
CREATE VIEW [dbo].RETAILPOSBATCHACCOUNTTRANS AS
(
  SELECT
    [STOREID],
    [TERMINALID],
    [BATCHID],
    [ACCOUNTNUM],
    [ACCOUNTTYPE],
    [AMOUNT],
    [DATAAREAID],
    [REPLICATIONCOUNTER],
    [CHANNEL]
  FROM [ax].RETAILPOSBATCHACCOUNTTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPOSBATCHSTAGINGTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPOSBATCHSTAGINGTABLE]') IS NOT NULL
    DROP VIEW [dbo].[RETAILPOSBATCHSTAGINGTABLE]
GO
CREATE VIEW [dbo].[RETAILPOSBATCHSTAGINGTABLE] AS
(
  SELECT
    [CHANNEL],
    [TERMINALID],
    [STOREID],
    [SHIFTID] AS 'BATCHID',
    [STAFFID],
    [STATUS],
    [CURRENTTERMINALID] AS 'OPENEDATTERMINAL',
    [STARTDATETIMEUTC] AS 'STARTDATETIME',
    [STATUSDATETIMEUTC] AS 'STATUSDATETIME',
    [DATAAREAID],
    [CASHDRAWER]
  FROM [crt].[RETAILSHIFTSTAGINGTABLE]
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPOSBATCHTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPOSBATCHTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPOSBATCHTABLE]
GO
CREATE VIEW [dbo].RETAILPOSBATCHTABLE AS
(
  SELECT
    [STOREID],
    [TERMINALID],
    [BATCHID],
    [STAFFID],
    [STATUS],
    [STARTDATE],
    [STARTTIME],
    [CLOSEDATE],
    [CLOSETIME],
    [STARTDATETIMEUTC],
    [CLOSEDATETIMEUTC],
    [CLOSEDATTERMINAL],
    [SALESTOTAL],
    [RETURNSTOTAL],
    [PAIDTOACCOUNTTOTAL],
    [TAXTOTAL],
    [DISCOUNTTOTAL],
    [ROUNDEDAMOUNTTOTAL],
    [SALESCOUNT],
    [CUSTOMERSCOUNT],
    [VOIDSCOUNT],
    [NOSALECOUNT],
    [LOGONSCOUNT],
    [TRANSACTIONSCOUNT],
    [DATAAREAID],
    [REPLICATIONCOUNTER],
    [CHANNEL]
  FROM [ax].RETAILPOSBATCHTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPOSBATCHTENDERTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPOSBATCHTENDERTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPOSBATCHTENDERTRANS]
GO
CREATE VIEW [dbo].RETAILPOSBATCHTENDERTRANS AS
(
  SELECT
    [STOREID],
    [TERMINALID],
    [BATCHID],
    [TENDERTYPEID],
    [CARDTYPEID],
    [CURRENCY],
    [COUNTINGREQUIRED],
    [STARTINGAMOUNT],
    [STARTINGAMOUNTCUR],
    [ADDTOTENDERAMOUNT],
    [ADDTOTENDERAMOUNTCUR],
    [SAFEDROPAMOUNT],
    [SAFEDROPAMOUNTCUR],
    [BANKDROPAMOUNT],
    [BANKDROPAMOUNTCUR],
    [REMOVETENDERAMOUNT],
    [REMOVETENDERAMOUNTCUR],
    [DECLARETENDERAMOUNT],
    [DECLARETENDERAMOUNTCUR],
    [TENDEREDAMOUNT],
    [TENDEREDAMOUNTCUR],
    [CHANGEAMOUNT],
    [CHANGEAMOUNTCUR],
    [COUNT],
    [DATAAREAID],
    [REPLICATIONCOUNTER],
    [CHANNEL]
  FROM [ax].RETAILPOSBATCHTENDERTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPOSITIONPOSPERMISSION ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPOSITIONPOSPERMISSION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPOSITIONPOSPERMISSION]
GO
CREATE VIEW [dbo].RETAILPOSITIONPOSPERMISSION AS
(
  SELECT
    [RECID],
    [POSITION],
    [POSPERMISSIONGROUP],
    [NAME],
    [ALLOWTRANSACTIONVOIDING],
    [MANAGERPRIVILEGES],
    [ALLOWXREPORTPRINTING],
    [ALLOWTENDERDECLARATION],
    [ALLOWFLOATINGTENDERDECLARATION],
    [ALLOWKITDISASSEMBLY],
    [ALLOWBLINDCLOSE],
    [ALLOWMULTIPLESHIFTLOGON],
    [ALLOWPRICEOVERRIDE],
    [ALLOWCHANGENOVOID],
    [ALLOWCHANGEPERIPHERALSTATION],
    [ALLOWTRANSACTIONSUSPENSION],
    [ALLOWOPENDRAWERONLY],
    [MAXIMUMDISCOUNTPCT],
    [MAXTOTALDISCOUNTPCT],
    [MAXLINEDISCOUNTAMOUNT],
    [MAXTOTALDISCOUNTAMOUNT],
    [MAXLINERETURNAMOUNT],
    [MAXTOTALRETURNAMOUNT],
    [ALLOWZREPORTPRINTING],
    [ALLOWMULTIPLELOGINS],
    [ALLOWSALESTAXCHANGE],
    [USEHANDHELD],
    [ALLOWCREATEORDER],
    [ALLOWEDITORDER],
    [ALLOWRETRIEVEORDER],
    [ALLOWNOTSAMEDATERETURN_RU],
    [ALLOWPASSWORDCHANGE],
    [ALLOWRESETPASSWORD],
    [ALLOWRETURNOFNONRETURNABLEITEM_RU],
    [ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU],
    [VIEWTIMECLOCKENTRIES]
  FROM [ax].RETAILPOSITIONPOSPERMISSION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILPOSPERMISSIONGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILPOSPERMISSIONGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPOSPERMISSIONGROUP]
GO
CREATE VIEW [dbo].RETAILPOSPERMISSIONGROUP AS
(
  SELECT
    [RECID],
    [POSPERMISSIONGROUPID],
    [NAME],
    [ALLOWTRANSACTIONVOIDING],
    [MANAGERPRIVILEGES],
    [ALLOWXREPORTPRINTING],
    [ALLOWTENDERDECLARATION],
    [ALLOWFLOATINGTENDERDECLARATION],
    [ALLOWKITDISASSEMBLY],
    [ALLOWBLINDCLOSE],
    [ALLOWMULTIPLESHIFTLOGON],
    [ALLOWPRICEOVERRIDE],
    [ALLOWCHANGENOVOID],
    [ALLOWCHANGEPERIPHERALSTATION],
    [ALLOWTRANSACTIONSUSPENSION],
    [ALLOWOPENDRAWERONLY],
    [MAXIMUMDISCOUNTPCT],
    [MAXTOTALDISCOUNTPCT],
    [MAXLINEDISCOUNTAMOUNT],
    [MAXTOTALDISCOUNTAMOUNT],
    [MAXLINERETURNAMOUNT],
    [MAXTOTALRETURNAMOUNT],
    [ALLOWZREPORTPRINTING],
    [ALLOWMULTIPLELOGINS],
    [ALLOWSALESTAXCHANGE],
    [USEHANDHELD],
    [ALLOWCREATEORDER],
    [ALLOWEDITORDER],
    [ALLOWRETRIEVEORDER],
    [VIEWTIMECLOCKENTRIES],
    [ALLOWNOTSAMEDATERETURN_RU],
    [ALLOWRETURNOFNONRETURNABLEITEM_RU],
    [ALLOWDIFFERENTPAYMENTMETHODREFUNDS_RU],
    [ALLOWPASSWORDCHANGE],
    [ALLOWRESETPASSWORD]
  FROM [ax].RETAILPOSPERMISSIONGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILRECEIPTMASKS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILRECEIPTMASKS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILRECEIPTMASKS]
GO
CREATE VIEW [dbo].RETAILRECEIPTMASKS AS
(
  SELECT
    [RECID],
    [FUNCPROFILEID],
    [RECEIPTTRANSTYPE],
    [MASK],
    [ISINDEPENDENT]
  FROM [ax].RETAILRECEIPTMASKS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILRECEIPTPROFILE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILRECEIPTPROFILE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILRECEIPTPROFILE]
GO
CREATE VIEW [dbo].RETAILRECEIPTPROFILE AS
(
  SELECT
    [RECID],
    [DESCRIPTION],
    [PROFILEID]
  FROM [ax].RETAILRECEIPTPROFILE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILRECEIPTPROFILELINE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILRECEIPTPROFILELINE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILRECEIPTPROFILELINE]
GO
CREATE VIEW [dbo].RETAILRECEIPTPROFILELINE AS
(
  SELECT
    [RECID],
    [PROFILEID],
    [RECEIPTTYPE],
    [FORMLAYOUTID]
  FROM [ax].RETAILRECEIPTPROFILELINE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILREPORTLOCALIZEDSTRING ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILREPORTLOCALIZEDSTRING]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILREPORTLOCALIZEDSTRING]
GO
CREATE VIEW [dbo].RETAILREPORTLOCALIZEDSTRING AS
(
  SELECT
    [RECID],
    [STRINGID],
    [LOCALECODE],
    [STRINGVALUE]
  FROM [ax].RETAILREPORTLOCALIZEDSTRING
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILREPORTPERMISSIONGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILREPORTPERMISSIONGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILREPORTPERMISSIONGROUP]
GO
CREATE VIEW [dbo].RETAILREPORTPERMISSIONGROUP AS
(
  SELECT
    [RECID],
    [RETAILCHANNELREPORTRECID],
    [RETAILPOSPERMISSIONGROUPRECID]
  FROM [ax].RETAILREPORTPERMISSIONGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSALESTAXOVERRIDE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSALESTAXOVERRIDE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSALESTAXOVERRIDE]
GO
CREATE VIEW [dbo].RETAILSALESTAXOVERRIDE AS
(
  SELECT
    [CODE],
    [DESCRIPTION],
    [STATUS],
    [OVERRIDETYPE],
    [OVERRIDEBY],
    [ADDITIONALDESCRIPTION],
    [SOURCETAXGROUP],
    [DESTINATIONTAXGROUP],
    [SOURCEITEMTAXGROUP],
    [DESTINATIONITEMTAXGROUP],
    [OVERRIDETO],
    [OVERRIDEFROM],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILSALESTAXOVERRIDE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSALESTAXOVERRIDEGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSALESTAXOVERRIDEGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSALESTAXOVERRIDEGROUP]
GO
CREATE VIEW [dbo].RETAILSALESTAXOVERRIDEGROUP AS
(
  SELECT
    [CODE],
    [DESCRIPTION],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILSALESTAXOVERRIDEGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSALESTAXOVERRIDEGROUPMEMBER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSALESTAXOVERRIDEGROUPMEMBER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSALESTAXOVERRIDEGROUPMEMBER]
GO
CREATE VIEW [dbo].RETAILSALESTAXOVERRIDEGROUPMEMBER AS
(
  SELECT
    [RBOSALESTAXOVERRIDEGROUPCODE],
    [RBOSALESTAXOVERRIDECODE],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILSALESTAXOVERRIDEGROUPMEMBER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSHAREDPARAMETERS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSHAREDPARAMETERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSHAREDPARAMETERS]
GO
CREATE VIEW [dbo].RETAILSHAREDPARAMETERS AS
(
  SELECT
    [RECID],
    [EXCHANGERATETYPE],
    [KEY] AS 'KEY_',
    [LOCALSTOREID],
    [EFTPASSWORDENCRYPTION],
    [TSPASSWORDENCRYPTION],
    [STAFFPASSWORDHASH],
    [EARNLOYALTYOFFLINE]
  FROM [ax].RETAILSHAREDPARAMETERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSIZEGROUPTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSIZEGROUPTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSIZEGROUPTABLE](
    [SIZEGROUP] [nvarchar](10) NOT NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20133GROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [SIZEGROUP] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__SIZEG__77E3BFD5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTABLE] ADD  CONSTRAINT [DF__RBOSIZEGR__SIZEG__77E3BFD5]  DEFAULT ('') FOR [SIZEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__DESCR__78D7E40E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTABLE] ADD  CONSTRAINT [DF__RBOSIZEGR__DESCR__78D7E40E]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__DATAA__79CC0847]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTABLE] ADD  CONSTRAINT [DF__RBOSIZEGR__DATAA__79CC0847]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSIZEGROUPTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSIZEGROUPTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSIZEGROUPTRANS](
    [SIZEGROUP] [nvarchar](10) NOT NULL,
    [SIZE_] [nvarchar](4) NOT NULL,
    [NAME] [nvarchar](10) NULL,
    [WEIGHT] [int] NULL,
    [NOINBARCODE] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
    [DESCRIPTION] [ntext] NULL,
 CONSTRAINT [I_20134SIZEGROUPIDIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [SIZEGROUP] ASC,
    [SIZE_] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__SIZEG__7D9C992B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTRANS] ADD  CONSTRAINT [DF__RBOSIZEGR__SIZEG__7D9C992B]  DEFAULT ('') FOR [SIZEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__SIZE___7E90BD64]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTRANS] ADD  CONSTRAINT [DF__RBOSIZEGR__SIZE___7E90BD64]  DEFAULT ('') FOR [SIZE_]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGRO__NAME__7F84E19D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTRANS] ADD  CONSTRAINT [DF__RBOSIZEGRO__NAME__7F84E19D]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__WEIGH__007905D6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTRANS] ADD  CONSTRAINT [DF__RBOSIZEGR__WEIGH__007905D6]  DEFAULT ((0)) FOR [WEIGHT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__NOINB__016D2A0F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTRANS] ADD  CONSTRAINT [DF__RBOSIZEGR__NOINB__016D2A0F]  DEFAULT ('') FOR [NOINBARCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__DATAA__03557281]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTRANS] ADD  CONSTRAINT [DF__RBOSIZEGR__DATAA__03557281]  DEFAULT ('DAT') FOR [DATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSIZEGR__DESCR__02614E48]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSIZEGROUPTRANS] ADD  CONSTRAINT [DF__RBOSIZEGR__DESCR__02614E48]  DEFAULT (NULL) FOR [DESCRIPTION]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSPECIALCATEGORYMEMBER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSPECIALCATEGORYMEMBER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSPECIALCATEGORYMEMBER]
GO
CREATE VIEW [dbo].RETAILSPECIALCATEGORYMEMBER AS
(
  SELECT
    [CATEGORY],
    [RETAILGROUPMEMBER],
    [RECID]
  FROM [ax].RETAILSPECIALCATEGORYMEMBER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTAFFEXTENDEDLOGON ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTAFFEXTENDEDLOGON]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTAFFEXTENDEDLOGON]
GO
CREATE VIEW [dbo].RETAILSTAFFEXTENDEDLOGON AS
(
  SELECT
    [LOGONKEY],
    [LOGONTYPE],
    [STAFF],
    [EXTRADATA],
    [RECID]
  FROM [ax].RETAILSTAFFEXTENDEDLOGON
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTAFFTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTAFFTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTAFFTABLE]
GO
CREATE VIEW [dbo].RETAILSTAFFTABLE AS
(
  SELECT
    [STAFFID],
    [BLOCKED],
    [PASSWORD],
    [PASSWORDDATA],
    [CHANGEPASSWORD],
    [EMPLOYMENTTYPE],
    [NAMEONRECEIPT],
    [CONTINUEONTSERRORS],
    [RECID],
    CONVERT([nvarchar](50), '') AS 'VISUALPROFILE',
    [CULTURENAME],
    [MODIFIEDDATETIME]
  FROM [ax].RETAILSTAFFTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTATEMENTJOUR ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTATEMENTJOUR]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTATEMENTJOUR](
    [STATEMENTID] [nvarchar](20) NOT NULL,
    [STATEMENTDATE] [datetime] NULL,
    [STOREID] [nvarchar](10) NULL,
    [POSTINGDATE] [datetime] NULL,
    [STATEMENTMETHOD] [int] NULL,
    [CLOSINGMETHOD] [int] NULL,
    [TRANSFROMDATE] [datetime] NULL,
    [TRANSFROMTIME] [int] NULL,
    [TRANSTODATE] [datetime] NULL,
    [TRANSTOTIME] [int] NULL,
    [SHIFTID] [nvarchar](10) NULL,
    [SHIFTDATE] [datetime] NULL,
    [STAFFTERMINAL] [nvarchar](10) NULL,
    [POSTEDDATE] [datetime] NULL,
    [POSTEDTIME] [int] NULL,
    [CALCULATEDDATE] [datetime] NULL,
    [CALCULATEDTIME] [datetime] NULL,
    [NUMBEROFBLOCKEDITEMS] [int] NULL,
    [NUMBEROFITEMSBARCODESNOTONFILE] [int] NULL,
    [NUMBEROFWRONGSHIFTTRANSACTIONS] [int] NULL,
    [SALESAMOUNT] [numeric](28, 12) NULL,
    [TAXAMOUNT] [numeric](28, 12) NULL,
    [TOTALDISCAMOUNT] [numeric](28, 12) NULL,
    [LOYALTYDISCAMOUNT_RU] [numeric](28, 12) NULL,
    [LINEDISCAMOUNT] [numeric](28, 12) NULL,
    [INCOMEAMOUNT] [numeric](28, 12) NULL,
    [EXPENSESAMOUNT] [numeric](28, 12) NULL,
    [SKIPCONFIRMATION] [int] NULL,
    [NUMBERSEQUENCECODE] [nvarchar](10) NULL,
    [NUMBEROFBLOCKEDCUSTOMERS] [int] NULL,
    [NUMBEROFSALESPAYMENTDIFFE20030] [int] NULL,
    [REPLICATIONCOUNTER] [int] NULL,
    [CREATEDDATE] [datetime] NULL,
    [CREATEDTIME] [int] NULL,
    [CREATEDBY] [nvarchar](8) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20138STATEMENTIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STATEMENTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__470B7E50]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__470B7E50]  DEFAULT ('') FOR [STATEMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__47FFA289]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__47FFA289]  DEFAULT ('1900-01-01 00:00:00.000') FOR [STATEMENTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STORE__48F3C6C2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__STORE__48F3C6C2]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTI__49E7EAFB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__POSTI__49E7EAFB]  DEFAULT ('1900-01-01 00:00:00.000') FOR [POSTINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__4ADC0F34]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__4ADC0F34]  DEFAULT ((0)) FOR [STATEMENTMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CLOSI__4BD0336D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__CLOSI__4BD0336D]  DEFAULT ((0)) FOR [CLOSINGMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__4CC457A6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__4CC457A6]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSFROMDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__4DB87BDF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__4DB87BDF]  DEFAULT ((0)) FOR [TRANSFROMTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__4EACA018]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__4EACA018]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSTODATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__4FA0C451]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__4FA0C451]  DEFAULT ((0)) FOR [TRANSTOTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__SHIFT__5094E88A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__SHIFT__5094E88A]  DEFAULT ('') FOR [SHIFTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__SHIFT__51890CC3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__SHIFT__51890CC3]  DEFAULT ('1900-01-01 00:00:00.000') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STAFF__527D30FC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__STAFF__527D30FC]  DEFAULT ('') FOR [STAFFTERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTE__53715535]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__POSTE__53715535]  DEFAULT ('1900-01-01 00:00:00.000') FOR [POSTEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTE__5465796E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__POSTE__5465796E]  DEFAULT ((0)) FOR [POSTEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CALCU__55599DA7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__CALCU__55599DA7]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CALCULATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CALCU__564DC1E0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__CALCU__564DC1E0]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CALCULATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__NUMBE__5741E619]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__NUMBE__5741E619]  DEFAULT ((0)) FOR [NUMBEROFBLOCKEDITEMS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__NUMBE__58360A52]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__NUMBE__58360A52]  DEFAULT ((0)) FOR [NUMBEROFITEMSBARCODESNOTONFILE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__NUMBE__592A2E8B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__NUMBE__592A2E8B]  DEFAULT ((0)) FOR [NUMBEROFWRONGSHIFTTRANSACTIONS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__SALES__5A1E52C4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__SALES__5A1E52C4]  DEFAULT ((0)) FOR [SALESAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TAXAM__5B1276FD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__TAXAM__5B1276FD]  DEFAULT ((0)) FOR [TAXAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TOTAL__5C069B36]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__TOTAL__5C069B36]  DEFAULT ((0)) FOR [TOTALDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_RETAILSTATEMENTJOUR_LOYALTYDISCAMOUNT_RU]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF_RETAILSTATEMENTJOUR_LOYALTYDISCAMOUNT_RU]  DEFAULT ((0)) FOR [LOYALTYDISCAMOUNT_RU]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__LINED__5CFABF6F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__LINED__5CFABF6F]  DEFAULT ((0)) FOR [LINEDISCAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__INCOM__5DEEE3A8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__INCOM__5DEEE3A8]  DEFAULT ((0)) FOR [INCOMEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__EXPEN__5EE307E1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__EXPEN__5EE307E1]  DEFAULT ((0)) FOR [EXPENSESAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__SKIPC__5FD72C1A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__SKIPC__5FD72C1A]  DEFAULT ((0)) FOR [SKIPCONFIRMATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__NUMBE__60CB5053]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__NUMBE__60CB5053]  DEFAULT ('') FOR [NUMBERSEQUENCECODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__NUMBE__61BF748C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__NUMBE__61BF748C]  DEFAULT ((0)) FOR [NUMBEROFBLOCKEDCUSTOMERS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__NUMBE__62B398C5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__NUMBE__62B398C5]  DEFAULT ((0)) FOR [NUMBEROFSALESPAYMENTDIFFE20030]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REPLI__63A7BCFE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__REPLI__63A7BCFE]  DEFAULT ((0)) FOR [REPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CREAT__649BE137]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__CREAT__649BE137]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CREATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CREAT__65900570]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__CREAT__65900570]  DEFAULT ((0)) FOR [CREATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CREAT__668429A9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__CREAT__668429A9]  DEFAULT ('?') FOR [CREATEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DATAA__67784DE2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTJOUR] ADD  CONSTRAINT [DF__RBOSTATEM__DATAA__67784DE2]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTATEMENTLINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTATEMENTLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTATEMENTLINE](
    [STATEMENTID] [nvarchar](20) NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [STATEMENTCODE] [nvarchar](10) NULL,
    [STAFFID] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [TENDERTYPEID] [nvarchar](10) NULL,
    [CARDTYPEID] [nvarchar](10) NULL,
    [CURRENCY] [nvarchar](3) NULL,
    [COUNTEDAMOUNT] [numeric](28, 12) NULL,
    [COUNTEDAMOUNTMST] [numeric](28, 12) NULL,
    [REALEXCHRATE] [numeric](28, 12) NULL,
    [POSTEDDATE] [datetime] NULL,
    [TRANSAMOUNTMST] [numeric](28, 12) NULL,
    [TRANSAMOUNT] [numeric](28, 12) NULL,
    [DIFFERENCEAMOUNT] [numeric](28, 12) NULL,
    [DIFFERENCEAMOUNTMST] [numeric](28, 12) NULL,
    [STOREID] [nvarchar](10) NULL,
    [ADDEDTODRAWER] [numeric](28, 12) NULL,
    [REMOVEDFROMDRAWER] [numeric](28, 12) NULL,
    [CHANGETENDER] [numeric](28, 12) NULL,
    [REPLICATIONCOUNTER] [int] NULL,
    [TENDERDECLARATION] [int] NULL,
    [COUNTINGREQUIRED] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20139STATEMENTLINEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STATEMENTID] ASC,
    [LINENUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__6B48DEC6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__6B48DEC6]  DEFAULT ('') FOR [STATEMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__LINEN__6C3D02FF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__LINEN__6C3D02FF]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__6D312738]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__6D312738]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STAFF__6E254B71]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__STAFF__6E254B71]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TERMI__6F196FAA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__TERMI__6F196FAA]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TENDE__700D93E3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__TENDE__700D93E3]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CARDT__7101B81C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__CARDT__7101B81C]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CURRE__71F5DC55]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__CURRE__71F5DC55]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__COUNT__72EA008E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__COUNT__72EA008E]  DEFAULT ((0)) FOR [COUNTEDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__COUNT__73DE24C7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__COUNT__73DE24C7]  DEFAULT ((0)) FOR [COUNTEDAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REALE__74D24900]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__REALE__74D24900]  DEFAULT ((0)) FOR [REALEXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTE__75C66D39]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__POSTE__75C66D39]  DEFAULT ('1900-01-01 00:00:00.000') FOR [POSTEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__76BA9172]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__76BA9172]  DEFAULT ((0)) FOR [TRANSAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__77AEB5AB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__77AEB5AB]  DEFAULT ((0)) FOR [TRANSAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DIFFE__78A2D9E4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__DIFFE__78A2D9E4]  DEFAULT ((0)) FOR [DIFFERENCEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DIFFE__7996FE1D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__DIFFE__7996FE1D]  DEFAULT ((0)) FOR [DIFFERENCEAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STORE__7A8B2256]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__STORE__7A8B2256]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__ADDED__7B7F468F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__ADDED__7B7F468F]  DEFAULT ((0)) FOR [ADDEDTODRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REMOV__7C736AC8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__REMOV__7C736AC8]  DEFAULT ((0)) FOR [REMOVEDFROMDRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CHANG__7D678F01]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__CHANG__7D678F01]  DEFAULT ((0)) FOR [CHANGETENDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REPLI__7E5BB33A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__REPLI__7E5BB33A]  DEFAULT ((0)) FOR [REPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TENDE__7F4FD773]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__TENDE__7F4FD773]  DEFAULT ((0)) FOR [TENDERDECLARATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__COUNT__0043FBAC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__COUNT__0043FBAC]  DEFAULT ((0)) FOR [COUNTINGREQUIRED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DATAA__01381FE5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTLINE] ADD  CONSTRAINT [DF__RBOSTATEM__DATAA__01381FE5]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTATEMENTTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTATEMENTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTATEMENTTABLE](
    [STATEMENTID] [nvarchar](20) NOT NULL,
    [STATEMENTDATE] [datetime] NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [POSTINGDATE] [datetime] NULL,
    [POSTEDDATE] [datetime] NULL,
    [POSTEDTIME] [int] NULL,
    [STATEMENTMETHOD] [int] NULL,
    [CLOSINGMETHOD] [int] NULL,
    [CALCULATEDDATE] [datetime] NULL,
    [CALCULATEDTIME] [int] NULL,
    [TRANSFROMDATE] [datetime] NULL,
    [TRANSFROMTIME] [int] NULL,
    [TRANSTODATE] [datetime] NULL,
    [TRANSTOTIME] [int] NULL,
    [SHIFTID] [nvarchar](10) NULL,
    [SHIFTDATE] [datetime] NULL,
    [STAFFORTERMINAL] [nvarchar](20) NULL,
    [SKIPCONFIRMATION] [int] NULL,
    [DEBUGMODE] [int] NULL,
    [RECALCULATE] [int] NULL,
    [STATUS] [int] NULL,
    [REPLICATIONCOUNTER] [int] NULL,
    [DIMENSION] [nvarchar](10) NULL,
    [DIMENSION2_] [nvarchar](10) NULL,
    [DIMENSION3_] [nvarchar](10) NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [MODIFIEDTRANSACTIONID] [bigint] NULL,
    [CREATEDDATE] [datetime] NULL,
    [CREATEDTIME] [int] NULL,
    [CREATEDBY] [nvarchar](8) NULL,
    [CREATEDTRANSACTIONID] [bigint] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20140STATEMENTIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STATEMENTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__0508B0C9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__0508B0C9]  DEFAULT ('') FOR [STATEMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__05FCD502]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__05FCD502]  DEFAULT ('1900-01-01 00:00:00.000') FOR [STATEMENTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STORE__06F0F93B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__STORE__06F0F93B]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTI__07E51D74]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__POSTI__07E51D74]  DEFAULT ('1900-01-01 00:00:00.000') FOR [POSTINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTE__08D941AD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__POSTE__08D941AD]  DEFAULT ('1900-01-01 00:00:00.000') FOR [POSTEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTE__09CD65E6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__POSTE__09CD65E6]  DEFAULT ((0)) FOR [POSTEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__0AC18A1F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__0AC18A1F]  DEFAULT ((0)) FOR [STATEMENTMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CLOSI__0BB5AE58]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__CLOSI__0BB5AE58]  DEFAULT ((0)) FOR [CLOSINGMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CALCU__0CA9D291]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__CALCU__0CA9D291]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CALCULATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CALCU__0D9DF6CA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__CALCU__0D9DF6CA]  DEFAULT ((0)) FOR [CALCULATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__0E921B03]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__0E921B03]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSFROMDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__0F863F3C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__0F863F3C]  DEFAULT ((0)) FOR [TRANSFROMTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__107A6375]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__107A6375]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSTODATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__116E87AE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__116E87AE]  DEFAULT ((0)) FOR [TRANSTOTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__SHIFT__1262ABE7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__SHIFT__1262ABE7]  DEFAULT ('') FOR [SHIFTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__SHIFT__1356D020]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__SHIFT__1356D020]  DEFAULT ('1900-01-01 00:00:00.000') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STAFF__144AF459]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__STAFF__144AF459]  DEFAULT ('') FOR [STAFFORTERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__SKIPC__153F1892]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__SKIPC__153F1892]  DEFAULT ((0)) FOR [SKIPCONFIRMATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DEBUG__16333CCB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__DEBUG__16333CCB]  DEFAULT ((0)) FOR [DEBUGMODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__RECAL__17276104]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__RECAL__17276104]  DEFAULT ((0)) FOR [RECALCULATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATU__181B853D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__STATU__181B853D]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REPLI__190FA976]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__REPLI__190FA976]  DEFAULT ((0)) FOR [REPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DIMEN__1A03CDAF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__DIMEN__1A03CDAF]  DEFAULT ('') FOR [DIMENSION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DIMEN__1AF7F1E8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__DIMEN__1AF7F1E8]  DEFAULT ('') FOR [DIMENSION2_]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DIMEN__1BEC1621]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__DIMEN__1BEC1621]  DEFAULT ('') FOR [DIMENSION3_]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__MODIF__1CE03A5A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__MODIF__1CE03A5A]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__MODIF__1DD45E93]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__MODIF__1DD45E93]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__MODIF__1EC882CC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__MODIF__1EC882CC]  DEFAULT ('?') FOR [MODIFIEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__MODIF__1FBCA705]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__MODIF__1FBCA705]  DEFAULT ((0)) FOR [MODIFIEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CREAT__20B0CB3E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__CREAT__20B0CB3E]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CREATEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CREAT__21A4EF77]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__CREAT__21A4EF77]  DEFAULT ((0)) FOR [CREATEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CREAT__229913B0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__CREAT__229913B0]  DEFAULT ('?') FOR [CREATEDBY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CREAT__238D37E9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__CREAT__238D37E9]  DEFAULT ((0)) FOR [CREATEDTRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DATAA__24815C22]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTABLE] ADD  CONSTRAINT [DF__RBOSTATEM__DATAA__24815C22]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTATEMENTTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTATEMENTTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTATEMENTTRANS](
    [STATEMENTID] [nvarchar](20) NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [STATEMENTCODE] [nvarchar](10) NULL,
    [TERMINALID] [nvarchar](10) NULL,
    [STAFFID] [nvarchar](10) NULL,
    [CARDTYPEID] [nvarchar](10) NULL,
    [TENDERTYPEID] [nvarchar](10) NULL,
    [REALEXCHRATE] [numeric](28, 12) NULL,
    [COUNTEDAMOUNTMST] [numeric](28, 12) NULL,
    [COUNTEDAMOUNT] [numeric](28, 12) NULL,
    [CURRENCY] [nvarchar](3) NULL,
    [POSTEDDATE] [datetime] NULL,
    [DIFFERENCEAMOUNTMST] [numeric](28, 12) NULL,
    [STOREID] [nvarchar](10) NULL,
    [TRANSAMOUNT] [numeric](28, 12) NULL,
    [TRANSAMOUNTINMST] [numeric](28, 12) NULL,
    [DIFFERENCEAMOUNT] [numeric](28, 12) NULL,
    [ADDEDTODRAWER] [numeric](28, 12) NULL,
    [REMOVEDFROMDRAWER] [numeric](28, 12) NULL,
    [CHANGETENDER] [numeric](28, 12) NULL,
    [REPLICATIONCOUNTER] [int] NULL,
    [INDRAWERATENDOFDAY] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20141STATEMENTLINEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STATEMENTID] ASC,
    [LINENUM] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__2851ED06]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__2851ED06]  DEFAULT ('') FOR [STATEMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__LINEN__2946113F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__LINEN__2946113F]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STATE__2A3A3578]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__STATE__2A3A3578]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TERMI__2B2E59B1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__TERMI__2B2E59B1]  DEFAULT ('') FOR [TERMINALID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STAFF__2C227DEA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__STAFF__2C227DEA]  DEFAULT ('') FOR [STAFFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CARDT__2D16A223]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__CARDT__2D16A223]  DEFAULT ('') FOR [CARDTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TENDE__2E0AC65C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__TENDE__2E0AC65C]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REALE__2EFEEA95]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__REALE__2EFEEA95]  DEFAULT ((0)) FOR [REALEXCHRATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__COUNT__2FF30ECE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__COUNT__2FF30ECE]  DEFAULT ((0)) FOR [COUNTEDAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__COUNT__30E73307]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__COUNT__30E73307]  DEFAULT ((0)) FOR [COUNTEDAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CURRE__31DB5740]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__CURRE__31DB5740]  DEFAULT ('') FOR [CURRENCY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__POSTE__32CF7B79]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__POSTE__32CF7B79]  DEFAULT ('1900-01-01 00:00:00.000') FOR [POSTEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DIFFE__33C39FB2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__DIFFE__33C39FB2]  DEFAULT ((0)) FOR [DIFFERENCEAMOUNTMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__STORE__34B7C3EB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__STORE__34B7C3EB]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__35ABE824]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__35ABE824]  DEFAULT ((0)) FOR [TRANSAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__TRANS__36A00C5D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__TRANS__36A00C5D]  DEFAULT ((0)) FOR [TRANSAMOUNTINMST]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DIFFE__37943096]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__DIFFE__37943096]  DEFAULT ((0)) FOR [DIFFERENCEAMOUNT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__ADDED__388854CF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__ADDED__388854CF]  DEFAULT ((0)) FOR [ADDEDTODRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REMOV__397C7908]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__REMOV__397C7908]  DEFAULT ((0)) FOR [REMOVEDFROMDRAWER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__CHANG__3A709D41]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__CHANG__3A709D41]  DEFAULT ((0)) FOR [CHANGETENDER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__REPLI__3B64C17A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__REPLI__3B64C17A]  DEFAULT ((0)) FOR [REPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__INDRA__3C58E5B3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__INDRA__3C58E5B3]  DEFAULT ((0)) FOR [INDRAWERATENDOFDAY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATEM__DATAA__3D4D09EC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATEMENTTRANS] ADD  CONSTRAINT [DF__RBOSTATEM__DATAA__3D4D09EC]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTATISTICSTIMESETUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTATISTICSTIMESETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTATISTICSTIMESETUP](
    [FROMTIME] [int] NOT NULL,
    [TOTIME] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20143FROMIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [FROMTIME] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATIS__FROMT__43FA077B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATISTICSTIMESETUP] ADD  CONSTRAINT [DF__RBOSTATIS__FROMT__43FA077B]  DEFAULT ((0)) FOR [FROMTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATIS__TOTIM__44EE2BB4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATISTICSTIMESETUP] ADD  CONSTRAINT [DF__RBOSTATIS__TOTIM__44EE2BB4]  DEFAULT ((0)) FOR [TOTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTATIS__DATAA__45E24FED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTATISTICSTIMESETUP] ADD  CONSTRAINT [DF__RBOSTATIS__DATAA__45E24FED]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTOREADDRESSBOOK ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTOREADDRESSBOOK]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTOREADDRESSBOOK]
GO
CREATE VIEW [dbo].RETAILSTOREADDRESSBOOK AS
(
  SELECT
    [STORERECID],
    [ADDRESSBOOK],
    [ADDRESSBOOKTYPE],
    [RECID]
  FROM [ax].RETAILSTOREADDRESSBOOK
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTORECASHDECLARATIONTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTORECASHDECLARATIONTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTORECASHDECLARATIONTABLE]
GO
CREATE VIEW [dbo].RETAILSTORECASHDECLARATIONTABLE AS
(
  SELECT
    [STOREID],
    [TYPE],
    [CURRENCY],
    [AMOUNT],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILSTORECASHDECLARATIONTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTORELOCATORGROUP ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTORELOCATORGROUP]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTORELOCATORGROUP]
GO
CREATE VIEW [dbo].RETAILSTORELOCATORGROUP AS
(
  SELECT
    [NAME],
    [DESCRIPTION],
    [RECID]
  FROM [ax].RETAILSTORELOCATORGROUP
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTORELOCATORGROUPMEMBER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTORELOCATORGROUPMEMBER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTORELOCATORGROUPMEMBER]
GO
CREATE VIEW [dbo].RETAILSTORELOCATORGROUPMEMBER AS
(
  SELECT
    [RECID],
    [STORE],
    [LOCATORGROUP]
  FROM [ax].RETAILSTORELOCATORGROUPMEMBER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTORELOCATORGROUPOWNER ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTORELOCATORGROUPOWNER]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTORELOCATORGROUPOWNER]
GO
CREATE VIEW [dbo].RETAILSTORELOCATORGROUPOWNER AS
(
  SELECT
    [RECID],
    [LOCATORGROUP],
    [CHANNEL]
  FROM [ax].RETAILSTORELOCATORGROUPOWNER
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTORESECTION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTORESECTION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTORESECTION](
    [STOREID] [nvarchar](10) NOT NULL,
    [SECTIONID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [LASTCHECKEDSTOCK] [datetime] NULL,
    [SIZE_] [numeric](28, 12) NULL,
    [SIZEUNIT] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20145STORESECTIONIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [SECTIONID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__STORE__51540299]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESECTION] ADD  CONSTRAINT [DF__RBOSTORES__STORE__51540299]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__SECTI__524826D2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESECTION] ADD  CONSTRAINT [DF__RBOSTORES__SECTI__524826D2]  DEFAULT ('') FOR [SECTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORESE__NAME__533C4B0B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESECTION] ADD  CONSTRAINT [DF__RBOSTORESE__NAME__533C4B0B]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__LASTC__54306F44]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESECTION] ADD  CONSTRAINT [DF__RBOSTORES__LASTC__54306F44]  DEFAULT ('1900-01-01 00:00:00.000') FOR [LASTCHECKEDSTOCK]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__SIZE___5524937D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESECTION] ADD  CONSTRAINT [DF__RBOSTORES__SIZE___5524937D]  DEFAULT ((0)) FOR [SIZE_]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__SIZEU__5618B7B6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESECTION] ADD  CONSTRAINT [DF__RBOSTORES__SIZEU__5618B7B6]  DEFAULT ((0)) FOR [SIZEUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__DATAA__570CDBEF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESECTION] ADD  CONSTRAINT [DF__RBOSTORES__DATAA__570CDBEF]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTORESHELF ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTORESHELF]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTORESHELF](
    [STOREID] [nvarchar](10) NOT NULL,
    [SECTIONID] [nvarchar](10) NOT NULL,
    [SHELFID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [SECTIONPCT] [numeric](28, 12) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20146STORESECTIONSHELFIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [SECTIONID] ASC,
    [SHELFID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__STORE__5ADD6CD3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESHELF] ADD  CONSTRAINT [DF__RBOSTORES__STORE__5ADD6CD3]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__SECTI__5BD1910C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESHELF] ADD  CONSTRAINT [DF__RBOSTORES__SECTI__5BD1910C]  DEFAULT ('') FOR [SECTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__SHELF__5CC5B545]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESHELF] ADD  CONSTRAINT [DF__RBOSTORES__SHELF__5CC5B545]  DEFAULT ('') FOR [SHELFID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORESH__NAME__5DB9D97E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESHELF] ADD  CONSTRAINT [DF__RBOSTORESH__NAME__5DB9D97E]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__SECTI__5EADFDB7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESHELF] ADD  CONSTRAINT [DF__RBOSTORES__SECTI__5EADFDB7]  DEFAULT ((0)) FOR [SECTIONPCT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTORES__DATAA__5FA221F0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTORESHELF] ADD  CONSTRAINT [DF__RBOSTORES__DATAA__5FA221F0]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTORETABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTORETABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTORETABLE]
GO
CREATE VIEW [dbo].RETAILSTORETABLE AS
(
  SELECT
    [STORENUMBER],
    CONVERT([nvarchar](60), '') AS 'NAME',
    [PHONE],
    [OPENFROM],
    [OPENTO],
    CONVERT([nvarchar](10), '') AS 'DIMENSION',
    CONVERT([nvarchar](10), '') AS 'DIMENSION2_',
    CONVERT([nvarchar](10), '') AS 'DIMENSION3_',
    [STATEMENTMETHOD],
    [ONESTATEMENTPERDAY],
    [CLOSINGMETHOD],
    CONVERT([nvarchar](10), '') AS 'ROUNDINGACCOUNT',
    [MAXIMUMPOSTINGDIFFERENCE],
    [MAXROUNDINGAMOUNT],
    [MAXSHIFTDIFFERENCEAMOUNT],
    [MAXTRANSACTIONDIFFERENCEAMOUNT],
    [FUNCTIONALITYPROFILE],
    [CREATELABELSFORZEROPRICE],
    CONVERT([nvarchar](10), '') AS 'ITEMNUMSEQ',
    [INVENTORYLOOKUP],
    [REMOVEADDTENDER],
    [TENDERDECLARATIONCALCULATION],
    [MAXIMUMTEXTLENGTHONRECEIPT],
    [NUMBEROFTOPORBOTTOMLINES],
    [ITEMIDONRECEIPT],
    [SERVICECHARGEPCT],
    [SERVICECHARGEPROMPT],
    [TAXGROUP],
    [TAXGROUPDATAAREAID],
    [REPLICATIONCOUNTER],
    [ROUNDINGTAXACCOUNT],
    [MAXROUNDINGTAXAMOUNT],
    [CULTURENAME],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID],
    [SQLSERVERNAME],
    [DATABASENAME],
    [USERNAME],
    [PASSWORD],
    [USEDEFAULTCUSTACCOUNT],
    CONVERT([int], 0) AS 'WINDOWSAUTHENTICATION',
    [HIDETRAININGMODE],
    [TAXOVERRIDEGROUP],
    [USEDESTINATIONBASEDTAX],
    [USECUSTOMERBASEDTAX],
    [TAXIDENTIFICATIONNUMBER],
    [OFFLINEPROFILE],
    [INVENTLOCATIONIDFORCUSTOMERORDER],
    [STMTPOSTASBUSINESSDAY],
    [STMTCALCBATCHENDTIME]
  FROM [ax].RETAILSTORETABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTORETENDERTYPECARDTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTORETENDERTYPECARDTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTORETENDERTYPECARDTABLE]
GO
CREATE VIEW [dbo].RETAILSTORETENDERTYPECARDTABLE AS
(
  SELECT
    [TENDERTYPEID],
    [CARDTYPEID],
    [NAME],
    [ACCOUNTTYPE],
    CONVERT([nvarchar](20), '') AS 'ACCOUNTRELATION',
    [COUNTINGREQUIRED],
    CONVERT([nvarchar](10), '') AS 'DIFFERENCEACCOUNT',
    [CASHBACKLIMIT],
    [MANUALAUTHORIZATION],
    [CARDNUMBERSWIPED],
    [SAMECARDALLOWED],
    [MODIFIEDDATETIME] AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID],
    CONVERT([nvarchar](10), '') AS 'DIFFERENCEACCOUNTFORBIGDI20017',
    [MAXNORMALDIFFERENCEAMOUNT],
    [ENTERFLEETINFO],
    [CARDFEE],
    CONVERT([nvarchar](10), '') AS 'CARDFEEACCOUNT',
    [CHECKMODULUS],
    [CHECKEXPIREDDATE],
    [PROCESSLOCALLY],
    [ALLOWMANUALINPUT],
    [CHANNEL]
  FROM [ax].RETAILSTORETENDERTYPECARDTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILSTORETENDERTYPETABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILSTORETENDERTYPETABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTORETENDERTYPETABLE]
GO
CREATE VIEW [dbo].RETAILSTORETENDERTYPETABLE AS
(
  SELECT
    [TENDERTYPEID],
    [NAME],
    [FUNCTION] AS 'FUNCTION_',
    [COUNTINGREQUIRED],
    [LINENUMINTRANSACTION],
    [CHANGETENDERID],
    [ABOVEMINIMUMTENDERID],
    [MINIMUMCHANGEAMOUNT],
    [ROUNDINGMETHOD],
    [ROUNDING],
    [MINIMUMAMOUNTENTERED],
    [MAXIMUMAMOUNTENTERED],
    [MINIMUMAMOUNTALLOWED],
    [MAXIMUMAMOUNTALLOWED],
    [ALLOWOVERTENDER],
    [MAXIMUMOVERTENDERAMOUNT],
    [ALLOWUNDERTENDER],
    [UNDERTENDERAMOUNT],
    [OPENDRAWER],
    [ENDORSECHECK],
    [ASKFORDATE],
    [SEEKAUTHORIZATION],
    [FRONTOFCHECK],
    [PAYACCOUNTBILL],
    [ACCOUNTTYPE],
    CONVERT([nvarchar](20), '') AS 'ACCOUNTRELATION',
    CONVERT([nvarchar](10), '') AS 'DIFFERENCEACCOUNT',
    [ALLOWFLOAT],
    [ENDORSMENTLINE1],
    [ENDORSMENTLINE2],
    [CHECKPAYEE],
    [SLIPBACKINPRINTER],
    [SLIPFRONTINPRINTER],
    [CHANGELINEONRECEIPT],
    [POSCOUNTENTRIES],
    [TAKENTOBANK],
    [MULTIPLYINTENDEROPERATIONS],
    [COMPRESSPAYMENTENTRIES],
    [ALLOWRETURNNEGATIVE],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID],
    [POSOPERATION],
    [TAKENTOSAFE],
    [MAXRECOUNT],
    [MAXCOUNTINGDIFFERENCE],
    [SIGCAPENABLED],
    [SIGCAPMINAMOUNT],
    [FISCALPRINTERTENDERTYPE_BR],
    [CHANNEL]
  FROM [ax].RETAILSTORETENDERTYPETABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTOREWORKSHIFTTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTOREWORKSHIFTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE](
    [STOREID] [nvarchar](10) NOT NULL,
    [SHIFTID] [nvarchar](1) NOT NULL,
    [STARTINGTIME] [int] NULL,
    [ENDINGTIME] [int] NULL,
    [ENDINGDATE] [datetime] NULL,
    [STARTINGDATE] [datetime] NULL,
    [WORKSHIFTSTATUS] [int] NULL,
    [REPLICATIONCOUNTER] [int] NULL,
    [SHIFTDATE] [datetime] NOT NULL,
    [STATEMENTID] [nvarchar](20) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20150STORESHIFTDATESHIFTID] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [SHIFTDATE] ASC,
    [SHIFTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__STORE__6431CCE3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__STORE__6431CCE3]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__SHIFT__6525F11C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__SHIFT__6525F11C]  DEFAULT ('') FOR [SHIFTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__START__661A1555]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__START__661A1555]  DEFAULT ((0)) FOR [STARTINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__ENDIN__670E398E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__ENDIN__670E398E]  DEFAULT ((0)) FOR [ENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__ENDIN__68025DC7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__ENDIN__68025DC7]  DEFAULT ('1900-01-01 00:00:00.000') FOR [ENDINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__START__68F68200]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__START__68F68200]  DEFAULT ('1900-01-01 00:00:00.000') FOR [STARTINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__WORKS__69EAA639]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__WORKS__69EAA639]  DEFAULT ((0)) FOR [WORKSHIFTSTATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__REPLI__6ADECA72]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__REPLI__6ADECA72]  DEFAULT ((0)) FOR [REPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__SHIFT__6BD2EEAB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__SHIFT__6BD2EEAB]  DEFAULT ('1900-01-01 00:00:00.000') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__STATE__6CC712E4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__STATE__6CC712E4]  DEFAULT ('') FOR [STATEMENTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__DATAA__6DBB371D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTABLE] ADD  CONSTRAINT [DF__RBOSTOREW__DATAA__6DBB371D]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTOREWORKSHIFTTRANS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTOREWORKSHIFTTRANS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS](
    [SHIFTDATE] [datetime] NOT NULL,
    [SHIFTID] [nvarchar](1) NOT NULL,
    [STATEMENTCODE] [nvarchar](20) NOT NULL,
    [STATUS] [int] NULL,
    [OPENINGDATE] [datetime] NULL,
    [OPENINGTIME] [int] NULL,
    [CLOSINGDATE] [datetime] NULL,
    [CLOSINGTIME] [int] NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [STATEMENTMETHOD] [int] NULL,
    [REPLICATIONCOUNTER] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__SHIFT__718BC801]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__SHIFT__718BC801]  DEFAULT ('1900-01-01 00:00:00.000') FOR [SHIFTDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__SHIFT__727FEC3A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__SHIFT__727FEC3A]  DEFAULT ('') FOR [SHIFTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__STATE__73741073]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__STATE__73741073]  DEFAULT ('') FOR [STATEMENTCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__STATU__746834AC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__STATU__746834AC]  DEFAULT ((0)) FOR [STATUS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__OPENI__755C58E5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__OPENI__755C58E5]  DEFAULT ('1900-01-01 00:00:00.000') FOR [OPENINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__OPENI__76507D1E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__OPENI__76507D1E]  DEFAULT ((0)) FOR [OPENINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__CLOSI__7744A157]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__CLOSI__7744A157]  DEFAULT ('1900-01-01 00:00:00.000') FOR [CLOSINGDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__CLOSI__7838C590]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__CLOSI__7838C590]  DEFAULT ((0)) FOR [CLOSINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__STORE__792CE9C9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__STORE__792CE9C9]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__STATE__7A210E02]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__STATE__7A210E02]  DEFAULT ((0)) FOR [STATEMENTMETHOD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__REPLI__7B15323B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__REPLI__7B15323B]  DEFAULT ((0)) FOR [REPLICATIONCOUNTER]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTOREW__DATAA__7C095674]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTOREWORKSHIFTTRANS] ADD  CONSTRAINT [DF__RBOSTOREW__DATAA__7C095674]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSTYLEGROUPTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSTYLEGROUPTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSTYLEGROUPTABLE](
    [STYLEGROUP] [nvarchar](10) NOT NULL,
    [DESCRIPTION] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20152GROUPIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STYLEGROUP] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTYLEG__STYLE__7EE5C31F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTYLEGROUPTABLE] ADD  CONSTRAINT [DF__RBOSTYLEG__STYLE__7EE5C31F]  DEFAULT ('') FOR [STYLEGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTYLEG__DESCR__7FD9E758]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTYLEGROUPTABLE] ADD  CONSTRAINT [DF__RBOSTYLEG__DESCR__7FD9E758]  DEFAULT ('') FOR [DESCRIPTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOSTYLEG__DATAA__00CE0B91]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILSTYLEGROUPTABLE] ADD  CONSTRAINT [DF__RBOSTYLEG__DATAA__00CE0B91]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILSUSPENDEDTRANSACTIONS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILSUSPENDEDTRANSACTIONS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILSUSPENDEDTRANSACTIONS](
    [SUSPENDEDTRANSACTIONID] [nvarchar](10) NOT NULL,
    [BYTELENGTH] [int] NOT NULL,
    [TRANSACTIONDATA] [varbinary](max) NULL,
    [TRANSDATE] [datetime] NOT NULL,
    [STAFF] [nvarchar](25) NOT NULL,
    [NETAMOUNT] [numeric](32, 16) NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
 CONSTRAINT [PK_RETAILSUSPENDEDTRANSACTIONS] PRIMARY KEY CLUSTERED
(
    [SUSPENDEDTRANSACTIONID] ASC,
    [STOREID] ASC,
    [TERMINALID] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTAXFILTERS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTAXFILTERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTAXFILTERS]
GO
CREATE VIEW [dbo].RETAILTAXFILTERS AS
(
  SELECT
    [CITY],
    [COUNTRYREGIONID],
    [COUNTYID],
    [DISTRICT],
    [STATEID],
    [TAXGROUPHEADING],
    [ZIPCODE],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILTAXFILTERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTENDERTYPECARDNUMBERS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTENDERTYPECARDNUMBERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTENDERTYPECARDNUMBERS]
GO
CREATE VIEW [dbo].RETAILTENDERTYPECARDNUMBERS AS
(
  SELECT
    [CARDTYPEID],
    [CARDNUMBERFROM],
    [CARDNUMBERTO],
    [CARDNUMBERLENGTH],
    [MODIFIEDDATETIME] AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID]
  FROM [ax].RETAILTENDERTYPECARDNUMBERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTENDERTYPECARDTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTENDERTYPECARDTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTENDERTYPECARDTABLE]
GO
CREATE VIEW [dbo].RETAILTENDERTYPECARDTABLE AS
(
  SELECT
    [CARDTYPEID],
    [NAME],
    [CARDTYPES],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATETIME',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID],
    [CARDISSUER]
  FROM [ax].RETAILTENDERTYPECARDTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILTENDERTYPETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILTENDERTYPETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILTENDERTYPETABLE](
    [TENDERTYPEID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DEFAULTFUNCTION] [int] NULL,
    [MODIFIEDDATE] [datetime] NULL,
    [MODIFIEDTIME] [int] NULL,
    [MODIFIEDBY] [nvarchar](8) NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20155TENDERTYPEIDX] PRIMARY KEY CLUSTERED
(
    [TENDERTYPEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTENDER__TENDE__14D5043E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTENDERTYPETABLE] ADD  CONSTRAINT [DF__RBOTENDER__TENDE__14D5043E]  DEFAULT ('') FOR [TENDERTYPEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTENDERT__NAME__15C92877]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTENDERTYPETABLE] ADD  CONSTRAINT [DF__RBOTENDERT__NAME__15C92877]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTENDER__DEFAU__16BD4CB0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTENDERTYPETABLE] ADD  CONSTRAINT [DF__RBOTENDER__DEFAU__16BD4CB0]  DEFAULT ((0)) FOR [DEFAULTFUNCTION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTENDER__MODIF__17B170E9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTENDERTYPETABLE] ADD  CONSTRAINT [DF__RBOTENDER__MODIF__17B170E9]  DEFAULT ('1900-01-01 00:00:00.000') FOR [MODIFIEDDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTENDER__MODIF__18A59522]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTENDERTYPETABLE] ADD  CONSTRAINT [DF__RBOTENDER__MODIF__18A59522]  DEFAULT ((0)) FOR [MODIFIEDTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOTENDER__MODIF__1999B95B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTENDERTYPETABLE] ADD  CONSTRAINT [DF__RBOTENDER__MODIF__1999B95B]  DEFAULT ('?') FOR [MODIFIEDBY]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTERMINALCUSTOMFIELD ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTERMINALCUSTOMFIELD]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTERMINALCUSTOMFIELD]
GO
CREATE VIEW [dbo].RETAILTERMINALCUSTOMFIELD AS
(
  SELECT
    [RECID],
    [NAME],
    [TYPE],
    [CAPTIONTEXTID]
  FROM [ax].RETAILTERMINALCUSTOMFIELD
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILTERMINALRECEIPTTXT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILTERMINALRECEIPTTXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILTERMINALRECEIPTTXT](
    [RELATION] [int] NOT NULL,
    [RELATIONCODE] [nvarchar](10) NOT NULL,
    [LINENUM] [numeric](28, 12) NOT NULL,
    [TYPE] [int] NOT NULL,
    [RECEIPTTXT] [nvarchar](50) NULL,
    [STOREID] [nvarchar](10) NULL,
    [ALIGNMENT] [int] NULL,
    [WIDE] [int] NULL,
    [HIGH] [int] NULL,
    [BOLD] [int] NULL,
    [ITALIC] [int] NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20080RELATIONLINETYPEIDX] PRIMARY KEY NONCLUSTERED
(
    [DATAAREAID] ASC,
    [RELATION] ASC,
    [RELATIONCODE] ASC,
    [LINENUM] ASC,
    [TYPE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__RELAT__3EF55B3C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__RELAT__3EF55B3C]  DEFAULT ((0)) FOR [RELATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__RELAT__3FE97F75]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__RELAT__3FE97F75]  DEFAULT ('') FOR [RELATIONCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__LINEN__40DDA3AE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__LINEN__40DDA3AE]  DEFAULT ((0)) FOR [LINENUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMINA__TYPE__41D1C7E7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMINA__TYPE__41D1C7E7]  DEFAULT ((0)) FOR [TYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__RECEI__42C5EC20]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__RECEI__42C5EC20]  DEFAULT ('') FOR [RECEIPTTXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__STORE__43BA1059]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__STORE__43BA1059]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__ALIGN__44AE3492]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__ALIGN__44AE3492]  DEFAULT ((0)) FOR [ALIGNMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMINA__WIDE__45A258CB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMINA__WIDE__45A258CB]  DEFAULT ((0)) FOR [WIDE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMINA__HIGH__46967D04]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMINA__HIGH__46967D04]  DEFAULT ((0)) FOR [HIGH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMINA__BOLD__478AA13D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMINA__BOLD__478AA13D]  DEFAULT ((0)) FOR [BOLD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__ITALI__487EC576]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__ITALI__487EC576]  DEFAULT ((0)) FOR [ITALIC]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTERMIN__DATAA__4972E9AF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTERMINALRECEIPTTXT] ADD  CONSTRAINT [DF__POSTERMIN__DATAA__4972E9AF]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILTERMINALSYNCSTATUS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILTERMINALSYNCSTATUS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILTERMINALSYNCSTATUS](
    [TERMINALID] [nchar](10) NOT NULL,
    [ISOFFLINE] [int] NOT NULL,
 CONSTRAINT [PK_RETAILTERMINALSYNCSTATUS] PRIMARY KEY CLUSTERED
(
    [TERMINALID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTERMINALTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTERMINALTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTERMINALTABLE]
GO
CREATE VIEW [dbo].RETAILTERMINALTABLE AS
(
  SELECT
    [TERMINALID],
    [NAME],
    [STORERECID],
    [LOCATION],
    [STATEMENTMETHOD],
    [TERMINALSTATEMENT],
    [NOTACTIVE],
    [CLOSINGSTATUS],
    [MANAGERKEYONRETURN],
    [SLIPIFRETURN],
    [OPENDRAWERATLILO],
    [ONLYTOTALINSUSPENDEDTRANSACTION] AS 'ONLYTOTALINSUSPENDEDTRANS20015',
    [EXITAFTEREACHTRANSACTION],
    [AUTOLOGOFFTIMEOUT],
    [RETURNINTRANSACTION],
    [ITEMIDONRECEIPT],
    [EFTSTORERECID],
    [EFTTENDERTYPEIDDEFAULT],
    [EFTTERMINALID],
    [MAXRECEIPTTEXTLENGTH],
    [NUMBEROFTOPBOTTOMLINES],
    [RECEIPTSETUPLOCATION],
    [MAXDISPLAYTEXTLENGTH],
    [CUSTOMERDISPLAYTEXT1],
    [CUSTOMERDISPLAYTEXT2],
    [HARDWAREPROFILE],
    [VISUALPROFILE],
    [PRINTVATREFUNDCHECKS],
    [RECEIPTPRINTINGDEFAULTOFF],
    [RECEIPTBARCODE],
    [LAYOUTID],
    [UPDATESERVICEPORT],
    [IPADDRESS],
    [MODIFIEDDATETIME] AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID],
    CONVERT([nvarchar](10), '') AS 'FUNCTIONALITYPROFILE',
    [STANDALONE],
    CONVERT([nvarchar](50), '') AS 'TRANSACTIONIDNUMBERSEQUENCE'
  FROM [ax].RETAILTERMINALTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTILLLAYOUT ..'
GO
IF OBJECT_ID(N'[crt].[RETAILIMAGEZONEPIVOT]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILIMAGEZONEPIVOT]
GO
CREATE VIEW [crt].[RETAILIMAGEZONEPIVOT] AS
(
    SELECT
        [LAYOUTID],
        [LOGOPICTUREID],
        [LOGOPICTUREID2],
        [LOGOPICTUREID3],
        [LOGOPICTUREID4],
        [LOGOPICTUREID5]
    FROM
    (
        SELECT LAYOUTID, PICTUREID AS ZONEPICTUREID, ZONEID FROM crt.RETAILTILLLAYOUTIMAGEZONEVIEW
    ) AS IMAGEZONEPIVOT
    PIVOT
    (
        MAX(ZONEPICTUREID) FOR ZONEID IN ([LOGOPICTUREID], [LOGOPICTUREID2],[LOGOPICTUREID3],[LOGOPICTUREID4],[LOGOPICTUREID5])
    ) AS IMAGEZONEPIVOT
)
GO

PRINT 'Creating view RETAILBUTTONGRIDZONEPIVOT ..'
IF OBJECT_ID(N'[crt].[RETAILBUTTONGRIDZONEPIVOT]', N'V') IS NOT NULL
    DROP VIEW [crt].[RETAILBUTTONGRIDZONEPIVOT]
GO
CREATE VIEW [crt].[RETAILBUTTONGRIDZONEPIVOT] AS
(
    SELECT
        [LAYOUTID],
        [BUTTONGRID1],
        [BUTTONGRID2],
        [BUTTONGRID3],
        [BUTTONGRID4],
        [BUTTONGRID5]
    FROM
    (
        SELECT LAYOUTID, BUTTONGRIDID, ZONEID FROM crt.RETAILTILLLAYOUTBUTTONGRIDZONEVIEW
    ) AS BUTTONGRIDZONEPIVOT
    PIVOT
    (
        MAX(BUTTONGRIDID) FOR ZONEID IN ([BUTTONGRID1], [BUTTONGRID2],[BUTTONGRID3],[BUTTONGRID4],[BUTTONGRID5])
    ) AS BUTTONGRIDZONEPIVOT
)
GO

PRINT 'Creating view RETAILTILLLAYOUT ..'
IF OBJECT_ID(N'[dbo].[RETAILTILLLAYOUT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTILLLAYOUT]
GO
CREATE VIEW [dbo].RETAILTILLLAYOUT AS
(
  SELECT
    rtl.[LAYOUTID],
    rtl.[NAME],
    rtl.[WIDTH],
    rtl.[HEIGHT],
    rtl.[RECEIPTID],
    rtl.[TOTALID],
    rtl.[CUSTOMERLAYOUTID],
    rtl.[RECID],
    CONVERT([image], NULL) AS 'IMG_CUSTOMERLAYOUTXML',
    CONVERT([image], NULL) AS 'IMG_RECEIPTITEMSLAYOUTXML',
    CONVERT([image], NULL) AS 'IMG_RECEIPTPAYMENTLAYOUTXML',
    CONVERT([image], NULL) AS 'IMG_TOTALSLAYOUTXML',
    CONVERT([image], NULL) AS 'IMG_LAYOUTXML',
    rtl.[IMG_CASHCHANGERLAYOUTXML],
    rtl.[CASHCHANGERLAYOUTXML],
    rtl.[CUSTOMERLAYOUTXML],
    rtl.[LAYOUTXML],
    rtl.[RECEIPTITEMSLAYOUTXML],
    rtl.[RECEIPTPAYMENTLAYOUTXML],
    rtl.[TOTALSLAYOUTXML],
    rbgzp.[BUTTONGRID1],
    rbgzp.[BUTTONGRID2],
    rbgzp.[BUTTONGRID3],
    rbgzp.[BUTTONGRID4],
    rbgzp.[BUTTONGRID5],
    rizp.[LOGOPICTUREID],
    rizp.[LOGOPICTUREID2],
    rizp.[LOGOPICTUREID3],
    rizp.[LOGOPICTUREID4],
    rizp.[LOGOPICTUREID5]
  FROM [ax].RETAILTILLLAYOUT AS rtl
    LEFT JOIN [crt].[RETAILBUTTONGRIDZONEPIVOT] AS rbgzp ON
        rbgzp.LAYOUTID = rtl.LAYOUTID
    LEFT JOIN [crt].[RETAILIMAGEZONEPIVOT] AS rizp ON
        rizp.LAYOUTID = rtl.LAYOUTID
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILTRANSACTION ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILTRANSACTION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILTRANSACTION](
    [BYTELENGTH] [int] NOT NULL,
    [TRANSACTIONDATA] [image] NOT NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [TERMINALID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
    [TRANSACTIONID] [uniqueidentifier] NOT NULL,
    [DELETEDDATE] [datetime] NULL,
 CONSTRAINT [PK_RETAILTRANSACTION] PRIMARY KEY CLUSTERED
(
    [STOREID] ASC,
    [TERMINALID] ASC,
    [DATAAREAID] ASC,
    [TRANSACTIONID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RETAILTRA__TRANS__29ECEF59]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTION] ADD CONSTRAINT [DF__RETAILTRA__TRANS__29ECEF59] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TRANSACTIONID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONAFFILIATIONTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONAFFILIATIONTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONAFFILIATIONTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONAFFILIATIONTRANS AS
(
  SELECT
    [AFFILIATION],
    [CHANNEL],
    [LOYALTYTIER],
    [RECEIPTID],
    [STAFFID],
    [STOREID],
    [TERMINALID],
    [TRANSACTIONID],
    [DATAAREAID]
  FROM [ax].RETAILTRANSACTIONAFFILIATIONTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONBANKEDTENDERTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONBANKEDTENDERTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONBANKEDTENDERTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONBANKEDTENDERTRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [STATEMENTCODE],
    [BANKBAGNO],
    [CARDTYPEID],
    [EXCHRATE],
    [TENDERTYPE],
    [AMOUNTTENDERED],
    [CURRENCY],
    [AMOUNTCUR],
    [CARDORACCOUNT],
    [TRANSDATE],
    [TRANSTIME],
    [SHIFT],
    [SHIFTDATE],
    [STAFF],
    [STORE],
    [TERMINAL],
    [TRANSACTIONSTATUS],
    [MANAGERSKEYLIVE],
    [CHANGELINE],
    [COUNTER],
    [MESSAGENUM],
    [REPLICATED],
    [QTY],
    [DATAAREAID],
    [STATUSTYPE],
    [AMOUNTCURPOS],
    [AMOUNTTENDEREDPOS],
    [AMOUNTMST],
    [EXCHRATEMST],
    [AMOUNTMSTPOS],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONBANKEDTENDERTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONDISCOUNTTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONDISCOUNTTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONDISCOUNTTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONDISCOUNTTRANS AS
(
  SELECT
    [AMOUNT],
    [DEALPRICE],
    [DISCOUNTAMOUNT],
    [PERCENTAGE],
    [PERIODICDISCOUNTOFFERID],
    [DISCOUNTCODE],
    [STOREID],
    [TERMINALID],
    [TRANSACTIONID],
    [SALELINENUM],
    [LINENUM],
    [DATAAREAID],
    [CHANNEL],
    [DISCOUNTORIGINTYPE],
    [CUSTOMERDISCOUNTTYPE],
    [MANUALDISCOUNTTYPE]
  FROM [ax].RETAILTRANSACTIONDISCOUNTTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONINCOMEEXPENSETRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONINCOMEEXPENSETRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONINCOMEEXPENSETRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONINCOMEEXPENSETRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [RECEIPTID],
    [INCOMEEXEPENSEACCOUNT],
    [STORE],
    [TERMINAL],
    [STAFF],
    [TRANSACTIONSTATUS],
    [AMOUNT],
    [ACCOUNTTYPE],
    [STATEMENTCODE],
    [COUNTER],
    [TRANSDATE],
    [TRANSTIME],
    [SHIFT],
    [SHIFTDATE],
    [REPLICATED],
    [DATAAREAID],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONINCOMEEXPENSETRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONINFOCODETRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONINFOCODETRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONINFOCODETRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONINFOCODETRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [TYPE],
    [INFOCODEID],
    [INFORMATION],
    [INFOAMOUNT],
    [TRANSDATE],
    [TRANSTIME],
    [STORE],
    [TERMINAL],
    [STAFF],
    [ITEMTENDER],
    [AMOUNT],
    [INPUTTYPE],
    [SUBINFOCODEID],
    [STATEMENTCODE],
    [SOURCECODE],
    [COUNTER],
    [REPLICATED],
    [DATAAREAID],
    [SOURCECODE2],
    [SOURCECODE3],
    [CHANNEL],
    [PARENTLINENUM]
  FROM [ax].RETAILTRANSACTIONINFOCODETRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONKITSDISASSEMBLYTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONKITSDISASSEMBLYTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONKITSDISASSEMBLYTRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [ITEMID],
    [VARIANTID],
    [QTY],
    [REPLICATIONCOUNTER],
    [STOREID] AS 'STORE',
    [TERMINALID],
    [DATAAREAID],
    [CHANNEL],
    [TRANSACTIONSTATUS]
  FROM [ax].RETAILTRANSACTIONKITSDISASSEMBLYTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILTRANSACTIONLINEVOIDED ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILTRANSACTIONLINEVOIDED]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILTRANSACTIONLINEVOIDED](
    [RECEIPTID] [nvarchar](18) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__RECEI__61156916]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONLINEVOIDED] ADD  CONSTRAINT [DF__POSTRANSA__RECEI__61156916]  DEFAULT ('') FOR [RECEIPTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSTRANSA__DATAA__62098D4F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONLINEVOIDED] ADD  CONSTRAINT [DF__POSTRANSA__DATAA__62098D4F]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONMARKUPTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONMARKUPTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONMARKUPTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONMARKUPTRANS AS
(
  SELECT
    [DATAAREAID],
    CONVERT([bigint], 0) AS 'RECID',
    [CURRENCYCODE],
    [TAXGROUP],
    [TAXITEMGROUP],
    [VALUE],
    [MARKUPCODE],
    [STORE],
    [TERMINALID],
    [TRANSACTIONID],
    [SALELINENUM],
    CONVERT([int], 0) AS 'REPLICATIONCOUNTER',
    [MARKUPLINENUM],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONMARKUPTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONORDERINVOICETRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONORDERINVOICETRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONORDERINVOICETRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONORDERINVOICETRANS AS
(
  SELECT
    [TRANSACTIONID],
    [SALESID],
    [INVOICEID],
    [AMOUNTCUR],
    [SALESORDERINVOICETYPE],
    [LINENUM],
    [STOREID],
    [TERMINALID],
    [DATAAREAID],
    CONVERT([bigint], 0) AS 'RECID',
    CONVERT([int], 0) AS 'REPLICATIONCOUNTER',
    CONVERT([int], 0) AS 'REPLICATED',
    [TRANSACTIONSTATUS],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONORDERINVOICETRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONPAYMENTTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONPAYMENTTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONPAYMENTTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONPAYMENTTRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [RECEIPTID],
    [STATEMENTCODE],
    [CARDTYPEID],
    [EXCHRATE],
    [TENDERTYPE],
    [AMOUNTTENDERED],
    [CURRENCY],
    [AMOUNTCUR],
    [CARDORACCOUNT],
    [TRANSDATE],
    [TRANSTIME],
    [SHIFT],
    [SHIFTDATE],
    [STAFF],
    [STORE],
    [TERMINAL],
    [TRANSACTIONSTATUS],
    [MANAGERKEYLIVE],
    [CHANGELINE],
    [COUNTER],
    [MESSAGENUM],
    [REPLICATED],
    [QTY],
    [DATAAREAID],
    [AUTHENTICATIONCODE],
    [GIFTCARDID],
    [CREDITVOUCHERID],
    [LOYALTYCARDID],
    [EXCHRATEMST],
    [AMOUNTMST],
    [SIGCAPDATA],
    [ISPREPAYMENT],
    [PAYMENTAUTHORIZATION],
    [CHANNEL],
    [CASHDOCID_RU],
    [REPLICATIONCOUNTERFROMORIGIN] AS 'REPLICATIONCOUNTER'
  FROM [ax].RETAILTRANSACTIONPAYMENTTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONSAFETENDERTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONSAFETENDERTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONSAFETENDERTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONSAFETENDERTRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [STATEMENTCODE],
    [CARDTYPEID],
    [EXCHRATE],
    [TENDERTYPE],
    [AMOUNTTENDERED],
    [CURRENCY],
    [AMOUNTCUR],
    [CARDORACCOUNT],
    [TRANSDATE],
    [TRANSTIME],
    [SHIFT],
    [SHIFTDATE],
    [STAFF],
    [STORE],
    [TERMINAL],
    [TRANSACTIONSTATUS],
    [MANAGERSKEYLIVE],
    [CHANGELINE],
    [COUNTER],
    [MESSAGENUM],
    [REPLICATED],
    [QTY],
    [STATUSTYPE],
    [AMOUNTCURPOS],
    [AMOUNTTENDEREDPOS],
    [AMOUNTMST],
    [EXCHRATEMST],
    [AMOUNTMSTPOS],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    CONVERT([bigint], 0) AS 'MODIFIEDTRANSACTIONID',
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'CREATEDDATE',
    CONVERT([int], 0) AS 'CREATEDTIME',
    CONVERT([bigint], 0) AS 'CREATEDTRANSACTIONID',
    [DATAAREAID],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONSAFETENDERTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONSALESTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONSALESTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONSALESTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONSALESTRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [RECEIPTID],
    [BARCODE],
    [ITEMID],
    --CONVERT([nvarchar](10), '') AS 'ITEMDEPARTMENTID',
    --CONVERT([nvarchar](10), '') AS 'ITEMGROUPID',
    [PRICE],
    [NETPRICE],
    [QTY],
    [TAXGROUP],
    [TRANSACTIONSTATUS],
    [DISCAMOUNT],
    [COSTAMOUNT],
    [TRANSDATE],
    [TRANSTIME],
    [SHIFT],
    [SHIFTDATE],
    [NETAMOUNT],
    [DISCOFFERID],
    [DISCGROUPID],
    [STDNETPRICE],
    [DISCAMOUNTFROMSTDPRICE],
    [CUSTACCOUNT],
    [SECTION],
    [SHELF],
    [STATEMENTCODE],
    [TRANSACTIONCODE],
    [STORE],
    [ITEMIDSCANNED],
    [KEYBOARDITEMENTRY],
    [PRICEINBARCODE],
    [PRICECHANGE],
    [WEIGHTMANUALLYENTERED],
    [LINEWASDISCOUNTED],
    [SCALEITEM],
    [WEIGHTITEM],
    [RETURNNOSALE],
    [ITEMCORRECTEDLINE],
    --CONVERT([int], 0) AS 'SALESTYPE',
    [LINKEDITEMNOTORIGINAL],
    [ORIGINALOFLINKEDITEMLIST],
    [TERMINALID],
    [ITEMPOSTINGGROUP],
    [TOTALROUNDEDAMOUNT],
    [COUNTER],
    --CONVERT([int], 0) AS 'REPLICATIONCOUNTER',
    [VARIANTID],
    [LINEDSCAMOUNT],
    [REPLICATED],
    [CUSTDISCAMOUNT],
    [INFOCODEDISCAMOUNT],
    [CUSTINVOICEDISCAMOUNT],
    [UNIT],
    [UNITQTY],
    [UNITPRICE],
    [TAXAMOUNT],
    [TOTALDISCAMOUNT],
    [TOTALDISCPCT],
    [LOYALTYDISCAMOUNT_RU],
    [LOYALTYDISCPCT_RU],
    [TOTALDISCINFOCODELINENUM],
    [PERIODICDISCTYPE],
    [PERIODICDISCAMOUNT],
    [LINEMANUALDISCOUNTAMOUNT],
    [LINEMANUALDISCOUNTPERCENTAGE],
    [PERIODICPERCENTAGEDISCOUNT],
    [DISCOUNTAMOUNTFORPRINTING],
    [STAFFID],
    [PERIODICDISCGROUP],
    [INVENTTRANSID],
    [INVENTDIMID],
    [PURCHID],
    [FILELOGID],
    [MODIFIEDTRANSACTIONID],
    [CREATEDTRANSACTIONID],
    [DATAAREAID],
    [PRESCRIPTIONID],
    [COMMENT],
    [ORIGINALPRICE],
    --CONVERT([numeric](28, 12), 0) AS 'LINEDISCPCT',
    --CONVERT([numeric](28, 12), 0) AS 'WHOLEDISCAMOUNTWITHTAX',
    --CONVERT([numeric](28, 12), 0) AS 'TOTALDISCAMOUNTWITHTAX',
    --CONVERT([numeric](28, 12), 0) AS 'LINEDISCAMOUNTWITHTAX',
    --CONVERT([numeric](28, 12), 0) AS 'PERIODICDISCAMOUNTWITHTAX',
    [INVENTBATCHID],
    [GIFTCARD],
    [INVENTSERIALID],
    [RFIDTAGID],
    [RETURNTRANSACTIONID],
    [RETURNQTY],
    [TAXITEMGROUP],
    [ORIGINALTAXGROUP],
    [ORIGINALTAXITEMGROUP],
    [NETAMOUNTINCLTAX],
    [INVENTLOCATIONID],
    [INVENTSITEID],
    [DLVMODE],
    [RECEIPTDATEREQUESTED],
    [SHIPPINGDATEREQUESTED],
    [LISTINGID],
    [LOGISTICSPOSTALADDRESS],
    [RETURNLINENUM],
    [RETURNSTORE],
    [RETURNTERMINALID],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONSALESTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONSERVICEPROFILE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONSERVICEPROFILE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONSERVICEPROFILE]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONSERVICEPROFILE AS
(
  SELECT
    [PROFILEID],
    [NAME],
    [TSSTAFF],
    [LANGUAGE],
    [CENTRALTABLESERVER],
    [CENTRALTABLESERVERPORT],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID],
    [RETAILTSDATA] AS 'POSTSDATA',
    [SERVERCERTIFICATEDNS],
    [SERVERSERVICENAME],
    [PROTOCOL],
    [SECURITYOFF]
  FROM [ax].RETAILTRANSACTIONSERVICEPROFILE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONTABLE]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONTABLE AS
(
  SELECT
    [TRANSACTIONID],
    [TYPE],
    [RECEIPTID],
    [STORE],
    [TERMINAL],
    [STAFF],
    [TRANSDATE],
    [TRANSTIME],
    [SHIFT],
    [SHIFTDATE],
    [WRONGSHIFT],
    [INFOCODEDISCGROUP],
    [CUSTACCOUNT],
    [TRANSCODE],
    [SALESPAYMENTDIFFERENCE],
    [NETAMOUNT],
    [COSTAMOUNT],
    [GROSSAMOUNT],
    [PAYMENTAMOUNT],
    [DISCAMOUNT],
    [CUSTDISCAMOUNT],
    [TOTALMANUALDISCOUNTAMOUNT],
    [TOTALMANUALDISCOUNTPERCENTAGE],
    [TOTALDISCAMOUNT],
    [LOYALTYDISCAMOUNT_RU],
    [NUMBEROFITEMS],
    [AMOUNTTOACCOUNT],
    [ROUNDEDAMOUNT],
    [ENTRYSTATUS],
    [NUMBEROFINVOICES],
    [NUMBEROFITEMLINES],
    [STATEMENTCODE],
    [REFUNDRECEIPTID],
    [INCOMEEXPENSEAMOUNT],
    [TOACCOUNT],
    [NUMBEROFPAYMENTLINES],
    [SALEISRETURNSALE],
    [COUNTER],
    [TIMEWHENTOTALPRESSED],
    [TIMEWHENTRANSCLOSED],
    [CURRENCY],
    [TRANSTABLEID],
    [OPENDRAWER],
    [REPLICATED],
    --CONVERT([int], 0) AS 'REPLICATIONCOUNTER',
    [INCLUDEDINSTATISTICS],
    [RETRIEVEDFROMRECEIPTID],
    [CREATEDONPOSTERMINAL],
    [POSTASSHIPMENT],
    [ITEMSPOSTED],
    [DATAAREAID],
    [DESCRIPTION],
    [CUSTPURCHASEORDER],
    [COMMENT],
    [INVOICECOMMENT],
    [SALESORDERAMOUNT],
    [SALESINVOICEAMOUNT],
    [RECEIPTEMAIL],
    [EXCHRATE],
    [BATCHTERMINALID],
    [BATCHID],
    [FISCALSERIALID],
    [FISCALDOCUMENTID],
    [CREATEDOFFLINE],
    [INVENTLOCATIONID],
    [INVENTSITEID],
    [DLVMODE],
    [RECEIPTDATEREQUESTED],
    [SHIPPINGDATEREQUESTED],
    [SKIPAGGREGATION],
    [CHANNELREFERENCEID],
    [LOGISTICSPOSTALADDRESS],
    [CHANNEL],
    [SALESORDERID],
    [CREATEDDATETIME] AS 'CREATEDDATE',
    [BUSINESSDATE],
    [LOYALTYCARDID]
  FROM [ax].RETAILTRANSACTIONTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONTABLE_RU ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONTABLE_RU]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONTABLE_RU]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONTABLE_RU AS
(
  SELECT
    [CHANNEL],
    [DATAAREAID],
    [KPKNUMBER],
    [EKLZSERIALNUMBER],
    [FISCALDOCUMENTSERIALNUMBER],
    [FISCALPRINTERSERIALNUMBER],
    [FISCALPRINTERSHIFTID],
    [REPLICATIONCOUNTERFROMORIGIN],
    [STORE],
    [TERMINAL],
    [TRANSACTIONID]
  FROM [ax].RETAILTRANSACTIONTABLE_RU
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILTRANSACTIONTABLEEX5 ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILTRANSACTIONTABLEEX5]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILTRANSACTIONTABLEEX5](
    [TRANSACTIONID] [nvarchar](10) NOT NULL,
    [BYTELENGTH] [int] NOT NULL,
    [TRANSACTIONDATA] [image] NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [STORE] [nvarchar](10) NOT NULL,
    [TERMINAL] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_RETAILTRANSACTIONTABLEEX5] PRIMARY KEY CLUSTERED
(
    [TRANSACTIONID] ASC,
    [DATAAREAID] ASC,
    [STORE] ASC,
    [TERMINAL] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__POSISTRAN__TRANS__5129E567]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONTABLEEX5] ADD  CONSTRAINT [DF__POSISTRAN__TRANS__5129E567]  DEFAULT ('') FOR [TRANSACTIONID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table RETAILTRANSACTIONRETURNENTRYSUM ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILTRANSACTIONRETURNENTRYSUM]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM](
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [STORE] [nvarchar](10) NOT NULL,
    [TERMINAL] [nvarchar](10) NOT NULL,
    [TRANSACTIONID] [nvarchar](44) NOT NULL,
    [ENTRYTYPE] [int] NOT NULL,
    [ENTRYID] [nvarchar](10) NOT NULL,
    [ISLOYALTYPAYMENT] [bit] NOT NULL,
    [AMOUNT] [numeric](32, 16) NOT NULL,
 CONSTRAINT [PK_RETAILTRANSACTIONRETURNENTRYSUM] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STORE] ASC,
    [TERMINAL] ASC,
    [TRANSACTIONID] ASC,
    [ENTRYTYPE] ASC,
    [ENTRYID] ASC,
    [ISLOYALTYPAYMENT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'DF_RETAILTRANSACTIONRETURNENTRYSUM_TRANSACTIONID') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM] ADD  CONSTRAINT [DF_RETAILTRANSACTIONRETURNENTRYSUM_TRANSACTIONID]  DEFAULT ('') FOR [TRANSACTIONID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'DF_RETAILTRANSACTIONRETURNENTRYSUM_STORE') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM] ADD  CONSTRAINT [DF_RETAILTRANSACTIONRETURNENTRYSUM_STORE]  DEFAULT ('') FOR [STORE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'DF_RETAILTRANSACTIONRETURNENTRYSUM_TERMINAL') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM] ADD  CONSTRAINT [DF_RETAILTRANSACTIONRETURNENTRYSUM_TERMINAL]  DEFAULT ('') FOR [TERMINAL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'DF_RETAILTRANSACTIONRETURNENTRYSUM_DATAAREAID') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM] ADD  CONSTRAINT [DF_RETAILTRANSACTIONRETURNENTRYSUM_DATAAREAID]  DEFAULT ('') FOR [DATAAREAID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'DF_RETAILTRANSACTIONRETURNENTRYSUM_ISLOYALTYPAYMENT') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM] ADD  CONSTRAINT [DF_RETAILTRANSACTIONRETURNENTRYSUM_ISLOYALTYPAYMENT]  DEFAULT ((0)) FOR [ISLOYALTYPAYMENT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'DF_RETAILTRANSACTIONRETURNENTRYSUM_ENTRYTYPE') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM] ADD  CONSTRAINT [DF_RETAILTRANSACTIONRETURNENTRYSUM_ENTRYTYPE]  DEFAULT ((0)) FOR [ENTRYTYPE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'DF_RETAILTRANSACTIONRETURNENTRYSUM_ENTRYID') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILTRANSACTIONRETURNENTRYSUM] ADD  CONSTRAINT [DF_RETAILTRANSACTIONRETURNENTRYSUM_ENTRYID]  DEFAULT ('') FOR [ENTRYID]
END
GO

-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONTAXTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONTAXTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONTAXTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONTAXTRANS AS
(
  SELECT
    [TAXCODE],
    [AMOUNT],
    [ISINCLUDEDINPRICE],
    [SALELINENUM],
    [TRANSACTIONID],
    [TERMINALID],
    [STOREID],
    [DATAAREAID],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONTAXTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILTRANSACTIONTENDERDECLARATIONTRANS ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILTRANSACTIONTENDERDECLARATIONTRANS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILTRANSACTIONTENDERDECLARATIONTRANS]
GO
CREATE VIEW [dbo].RETAILTRANSACTIONTENDERDECLARATIONTRANS AS
(
  SELECT
    [TRANSACTIONID],
    [LINENUM],
    [RECEIPTID],
    [POSCURRENCY],
    [CARDID],
    [TENDERTYPE],
    [AMOUNTTENDERED],
    [CURRENCY],
    [AMOUNTCUR],
    [TRANSDATE],
    [TRANSTIME],
    [SHIFT],
    [SHIFTDATE],
    [STAFF],
    [STORE],
    [TERMINAL],
    [TRANSACTIONSTATUS],
    [QTY],
    [REPLICATED],
    [STATEMENTCODE],
    [DATAAREAID],
    [EXCHRATE],
    [EXCHRATEMST],
    [AMOUNTMST],
    [CHANNEL]
  FROM [ax].RETAILTRANSACTIONTENDERDECLARATIONTRANS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILUNIT ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILUNIT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILUNIT]
GO
CREATE VIEW [dbo].RETAILUNIT AS
(
  SELECT
    [UNITID],
    [MINDENOMINATOR],
    [WEIGHTUNITOFMEASURE],
    [DATAAREAID],
    [RECID]
  FROM [ax].RETAILUNIT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view RETAILVISUALPROFILE ..'
GO
IF OBJECT_ID(N'[dbo].[RETAILVISUALPROFILE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILVISUALPROFILE]
GO
CREATE VIEW [dbo].RETAILVISUALPROFILE AS
(
  SELECT
    [PROFILEID],
    [NAME],
    [HIDECURSOR],
    [MODIFIEDDATETIME] AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [RECID],
    [DESIGNALLOWEDONPOS],
    [SCREENHEIGHT],
    [SCREENWIDTH],
    [PICTUREID],
    [FULLSCREENMODE],
    [POSSKINNAME],
    [SKINFILE],
    [FONTSCHEME]
  FROM [ax].RETAILVISUALPROFILE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table RETAILWORKSHIFTSETUP ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RETAILWORKSHIFTSETUP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RETAILWORKSHIFTSETUP](
    [NAME] [nvarchar](30) NULL,
    [STARTTIME] [int] NULL,
    [ENDINGTIME] [int] NULL,
    [STOREID] [nvarchar](10) NOT NULL,
    [DATEREFERENCE] [int] NULL,
    [WORKSHIFTID] [nvarchar](1) NOT NULL,
    [ABBREVIATIONTEXT] [nvarchar](15) NULL,
    [ABBREVIATION] [nvarchar](1) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_20168STORESHIFTIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [STOREID] ASC,
    [WORKSHIFTID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSHI__NAME__7A7613BD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSHI__NAME__7A7613BD]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__START__7B6A37F6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__START__7B6A37F6]  DEFAULT ((0)) FOR [STARTTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__ENDIN__7C5E5C2F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__ENDIN__7C5E5C2F]  DEFAULT ((0)) FOR [ENDINGTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__STORE__7D528068]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__STORE__7D528068]  DEFAULT ('') FOR [STOREID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__DATER__7E46A4A1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__DATER__7E46A4A1]  DEFAULT ((0)) FOR [DATEREFERENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__WORKS__7F3AC8DA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__WORKS__7F3AC8DA]  DEFAULT ('') FOR [WORKSHIFTID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__ABBRE__002EED13]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__ABBRE__002EED13]  DEFAULT ('') FOR [ABBREVIATIONTEXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__ABBRE__0123114C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__ABBRE__0123114C]  DEFAULT ('') FOR [ABBREVIATION]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RBOWORKSH__DATAA__02173585]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RETAILWORKSHIFTSETUP] ADD  CONSTRAINT [DF__RBOWORKSH__DATAA__02173585]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view SALESPARAMETERS ..'
GO
IF OBJECT_ID(N'[dbo].[SALESPARAMETERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[SALESPARAMETERS]
GO
CREATE VIEW [dbo].SALESPARAMETERS AS
(
  SELECT
    [PICKINGLISTDEFAULTLANGUAGE],
    [DELETELINE],
    [DELETEHEADING],
    [QUOTATIONNUMOFDAYSFOLLOWUPDATE],
    [REDUCEPACKINGSLIP],
    [REDUCEINVOICE],
    CONVERT([int], 0) AS 'LATESTORDERENTRYSUNDAY',
    CONVERT([int], 0) AS 'LATESTORDERENTRYFRIDAY',
    CONVERT([int], 0) AS 'LATESTORDERENTRYSATURDAY',
    CONVERT([int], 0) AS 'LATESTORDERENTRYWEDNESDAY',
    [CUSTQUOTATIONTYPEID],
    [OVERDELIVERY],
    [SUBDELIVERY],
    [DISC],
    [MARKUPHEADING],
    [MARKUPLINE],
    [DELIVERY2INVOICE],
    CONVERT([int], 0) AS 'DELIVERYDATECONTROL',
    [LEADTIMESALESDEFAULT],
    CONVERT([int], 0) AS 'LATESTORDERENTRYMONDAY',
    CONVERT([int], 0) AS 'LATESTORDERENTRYTUESDAY',
    [CANCELSALES],
    [PROMPTTRANSFER],
    [ORDERTYPE],
    CONVERT([int], 0) AS 'LATESTORDERENTRYTHURSDAY',
    [POSTPACKINGSLIP],
    [ACCESLEVELINVOICED],
    CONVERT([nvarchar](10), '') AS 'RETURNACTIONDEFAULT',
    [VALIDDAYS],
    [KEY] AS 'KEY_',
    [SHIPPINGSTAT],
    [SALESPOOLID],
    [PREPRINTLEVELSHIPPINGLABEL],
    [RESERVATION],
    [SETTLEVOUCHER],
    CONVERT([int], 0) AS 'INVENTTRANSASPICKED',
    [SUMMARYERRORTOLERANCE],
    [SUMMARYUPDATEBY],
    [QUOTATIONNUMOFDAYSEXPIRYDATE],
    [REDUCEPICKINGLIST],
    [SALESORIGINID],
    [USESETTLEEXCHRATE],
    [BILLOFLADING],
    [BOLLANGUAGEID],
    [BOLCARRIERNAME],
    [BOLFREIGHTCHARGETERMS],
    [BOLTRAILERLOADED],
    [BOLFREIGHTCOUNTED],
    [BOLFREIGHTEDBY],
    CONVERT([int], 0) AS 'USEDLVADRASSHIPTOADR',
    CONVERT([int], 0) AS 'SPLITDELIVERYQUOTATION',
    [SPLITDELIVERYCONFIRMATION],
    [SPLITDELIVERYPICKINGLIST],
    [SPLITDELIVERYPACKINGSLIP],
    [SPLITDELIVERYINVOICE],
    [ORDERENTRYSTATISTICS],
    CONVERT([datetime], '1900-01-01 00:00:00.000') AS 'MODIFIEDDATE',
    CONVERT([int], 0) AS 'MODIFIEDTIME',
    [DATAAREAID],
    [RECID]
  FROM [ax].SALESPARAMETERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table STATE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[STATE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[STATE](
    [NAME] [nvarchar](30) NULL,
    [STATEID] [nvarchar](10) NOT NULL,
    [COUNTRYID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_418COUNTRYSTATEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [COUNTRYID] ASC,
    [STATEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__STATE__NAME__09EA341B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[STATE] ADD  CONSTRAINT [DF__STATE__NAME__09EA341B]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__STATE__STATEID__0ADE5854]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[STATE] ADD  CONSTRAINT [DF__STATE__STATEID__0ADE5854]  DEFAULT ('') FOR [STATEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__STATE__COUNTRYID__0BD27C8D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[STATE] ADD  CONSTRAINT [DF__STATE__COUNTRYID__0BD27C8D]  DEFAULT ('') FOR [COUNTRYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__STATE__DATAAREAI__0CC6A0C6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[STATE] ADD  CONSTRAINT [DF__STATE__DATAAREAI__0CC6A0C6]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view TAXCOLLECTLIMIT ..'
GO
IF OBJECT_ID(N'[dbo].[TAXCOLLECTLIMIT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TAXCOLLECTLIMIT]
GO
CREATE VIEW [dbo].TAXCOLLECTLIMIT AS
(
  SELECT
    [TAXCODE],
    [TAXMAX],
    [TAXMIN],
    [TAXTODATE],
    [TAXFROMDATE],
    [DATAAREAID],
    [RECID]
  FROM [ax].TAXCOLLECTLIMIT
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view TAXDATA ..'
GO
IF OBJECT_ID(N'[dbo].[TAXDATA]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TAXDATA]
GO
CREATE VIEW [dbo].TAXDATA AS
(
  SELECT
    [TAXCODE],
    [TAXVALUE],
    [TAXLIMITMIN],
    [TAXLIMITMAX],
    [VATEXEMPTPCT],
    [TAXFROMDATE],
    [TAXTODATE],
    CONVERT([numeric](28, 12), 0) AS 'INVESTMENTTAXPCT',
    [DATAAREAID],
    [RECID],
    [SALESTAXFORMTYPES_IN],
    [TAXREDUCTIONPCT_BR]
  FROM [ax].TAXDATA
)
GO

-------------------------------------------------------------------------------
PRINT 'Creating view TAXFISCALCLASSIFICATION_BR ..'
GO
IF OBJECT_ID(N'[dbo].[TAXFISCALCLASSIFICATION_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].TAXFISCALCLASSIFICATION_BR
GO
CREATE VIEW [dbo].TAXFISCALCLASSIFICATION_BR AS
(
  SELECT
    [APPROXTAXVALUEIMPORTED],
    [APPROXTAXVALUENATIONAL],
    [DATAAREAID],
    [FISCALCLASSIFICATIONID],
    [RECID],
    [ROWVERSION]
  FROM [ax].TAXFISCALCLASSIFICATION_BR
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view TAXGROUPDATA ..'
GO
IF OBJECT_ID(N'[dbo].[TAXGROUPDATA]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TAXGROUPDATA]
GO
CREATE VIEW [dbo].TAXGROUPDATA AS
(
  SELECT
    [TAXGROUP],
    [TAXCODE],
    [EXEMPTTAX],
    [USETAX],
    [DATAAREAID],
    [RECID],
    [TAXATIONCODETABLE_BR]
  FROM [ax].TAXGROUPDATA
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view TAXGROUPHEADING ..'
GO
IF OBJECT_ID(N'[dbo].[TAXGROUPHEADING]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TAXGROUPHEADING]
GO
CREATE VIEW [dbo].TAXGROUPHEADING AS
(
  SELECT
    [TAXGROUP],
    [TAXGROUPNAME],
    [SEARCHFIELD1],
    [SEARCHFIELD2],
    [TAXREVERSEONCASHDISC],
    CONVERT([int], 0) AS 'TAXDIRECTION',
    [DATAAREAID],
    [RECID],
    [TAXPRINTDETAIL],
    [TAXGROUPROUNDING],
    [TAXGROUPSETUP]
  FROM [ax].TAXGROUPHEADING
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view TAXONITEM ..'
GO
IF OBJECT_ID(N'[dbo].[TAXONITEM]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TAXONITEM]
GO
CREATE VIEW [dbo].TAXONITEM AS
(
  SELECT
    [TAXITEMGROUP],
    [TAXCODE],
    [DATAAREAID],
    [RECID],
    [ABATEMENTPERCENT_IN],
    [TAXATIONCODETABLE_BR],
    [WITHOUTTAXCREDIT_BR],
    [EXEMPTTAX_BR]
  FROM [ax].TAXONITEM
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view TAXPARAMETERS ..'
GO
IF OBJECT_ID(N'[dbo].[TAXPARAMETERS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TAXPARAMETERS]
GO
CREATE VIEW [dbo].TAXPARAMETERS AS
(
  SELECT
    [TAXGROUP],
    [TAXITEMGROUP],
    [TAXSPECIFYLINE],
    [JOURNALINCLTAX],
    [CALCULATEPRINCIPLE],
    [PURCHTAXONOPERATIONS],
    [KEY] AS 'KEY_',
    [CASHDISCONINVOICE],
    [TAXLESSCASHDISC],
    [REVERSEONCASHDISC],
    [TAXCALCULATIONDATETYPE],
    [TAXONOVERPAYMENT],
    CONVERT([int], 0) AS 'UNREALIZEDTAX',
    [REPORTADJUSTMENT],
    [CONDITIONALTAX],
    [CHECKINTERSECTION],
    [ALLOWDUPLICATES],
    CONVERT([int], 0) AS 'VATBOOKENABLE',
    [VALIDATETAXCODE],
    [TAXREPORT_JP],
    [MANDATORYTAXDIRECTION],
    [CUSTOMS_IN],
    [SERVICETAX_IN],
    [EXCISE_IN],
    [SALESTAX_IN],
    [VAT_IN],
    [VENDORCALCULATIONDATETYPE_IN],
    [CUSTOMERCALCULATIONDATETYPE_IN],
    [TAXRECOVERABLE_IN],
    [EXIMINCENTIVESCHEMES_IN],
    [MODIFIEDDATETIME],
    CONVERT([int], 0) AS 'DEL_MODIFIEDTIME',
    [DATAAREAID],
    [RECID]
  FROM [ax].TAXPARAMETERS
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view TAXTABLE ..'
GO
IF OBJECT_ID(N'[dbo].[TAXTABLE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TAXTABLE]
GO
CREATE VIEW [dbo].TAXTABLE AS
(
  SELECT
    [TAXCODE],
    [TAXROUNDOFF],
    [TAXROUNDOFFTYPE],
    [DATAAREAID],
    [TAXCURRENCYCODE],
    [TAXBASE],
    [TAXLIMITBASE],
    [TAXCALCMETHOD],
    [TAXONTAX],
    [TAXUNIT],
    [TAXNAME],
    [TAXPERIOD],
    [TAXACCOUNTGROUP],
    [PRINTCODE],
    [REPFIELDBASEINCOMING],
    [REPFIELDBASEOUTGOING],
    [REPFIELDBASEUSETAX],
    [REPFIELDTAXFREEBUY],
    [REPFIELDTAXFREESALES],
    [REPFIELDUSETAXOFFSET],
    [REPFIELDUSETAX],
    [REPFIELDTAXINCOMING],
    [REPFIELDTAXOUTGOING],
    [TAXJURISDICTIONCODE],
    [NEGATIVETAX],
    [TAXCOUNTRYREGIONTYPE],
    [TAXINCLUDEINTAX],
    [TAXPACKAGINGTAX],
    [TAXPACKAGINGSORT],
    [TAXPURCHASETAX],
    [REPFIELDBASEUSETAXOFFSET],
    [REPFIELDTAXINCOMINGCREDITNOTE],
    [REPFIELDBASEOUTGOINGCREDITNOTE],
    [REPFIELDTAXOUTGOINGCREDITNOTE],
    [REPFIELDBASEINCOMINGCREDITNOTE],
    [REPFIELDUSETAXOFFSETCREDITNOTE],
    [REPFIELDUSETAXCREDITNOTE],
    [REPFIELDBASEUSETAXCREDITNOTE],
    [REPFIELDTAXFREESALESCREDITNOTE],
    [REPFIELDTAXFREEBUYCREDITNOTE],
    [REPFIELDBASEUSETAXOFFSETCREDITNOTE],
    [TAXWRITESELECTION],
    CONVERT([int], 0) AS 'INVESTEMENTTAXNULLPERCENT',
    CONVERT([int], 0) AS 'TAXOUTOFAREA',
    [PAYMENTTAXCODE],
    [NOTEUSALESLIST],
    [TAXBORDERNUMREQ_FI],
    [TAXTYPE_SG],
    [CUSTOMSPRACTICE_FI],
    [UNREALIZEDTAX],
    [RECID],
    [TAXTYPE_IN],
    [RETAINEDTAX_BR],
    [INCLUDEDTAX_BR],
    [TAXSUBSTITUTION_BR],
    [TAXTYPE_BR],
    [REVENUECODE_BR],
    [TAXATIONCODETABLE_BR],
    [TAXCOMPONENTTABLE_IN]
  FROM [ax].TAXTABLE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table TESTTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TESTTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TESTTABLE](
    [ID] [nvarchar](10) NOT NULL,
    [TEXTFIELD] [text] NULL,
    [INTFIELD] [int] NULL,
    [DECIMALFIELD] [decimal](18, 0) NULL,
 CONSTRAINT [PK_POSISTESTTABLE] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TESTTABLE__ID__04308F6E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TESTTABLE] ADD CONSTRAINT [DF__TESTTABLE__ID__04308F6E] DEFAULT ('') FOR [ID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table UNITCONVERT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UNITCONVERT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UNITCONVERT](
    [FROMUNIT] [nvarchar](10) NOT NULL,
    [TOUNIT] [nvarchar](10) NOT NULL,
    [FACTOR] [numeric](28, 12) NULL,
    [ROUNDOFF] [int] NULL,
    [ITEMID] [nvarchar](20) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NOT NULL,
    [MARKUP] [numeric](28, 12) NULL,
 CONSTRAINT [I_486RECIDIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [RECID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITCONVE__FROMU__4BB7F778]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITCONVERT] ADD  CONSTRAINT [DF__UNITCONVE__FROMU__4BB7F778]  DEFAULT ('') FOR [FROMUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITCONVE__TOUNI__4CAC1BB1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITCONVERT] ADD  CONSTRAINT [DF__UNITCONVE__TOUNI__4CAC1BB1]  DEFAULT ('') FOR [TOUNIT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITCONVE__FACTO__4DA03FEA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITCONVERT] ADD  CONSTRAINT [DF__UNITCONVE__FACTO__4DA03FEA]  DEFAULT ((0)) FOR [FACTOR]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITCONVE__ROUND__4E946423]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITCONVERT] ADD  CONSTRAINT [DF__UNITCONVE__ROUND__4E946423]  DEFAULT ((0)) FOR [ROUNDOFF]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITCONVE__ITEMI__4F88885C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITCONVERT] ADD  CONSTRAINT [DF__UNITCONVE__ITEMI__4F88885C]  DEFAULT ('') FOR [ITEMID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITCONVE__DATAA__507CAC95]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITCONVERT] ADD  CONSTRAINT [DF__UNITCONVE__DATAA__507CAC95]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating view UNITOFMEASURE ..'
GO
IF OBJECT_ID(N'[dbo].[UNITOFMEASURE]', N'V') IS NOT NULL
    DROP VIEW [dbo].[UNITOFMEASURE]
GO
CREATE VIEW [dbo].UNITOFMEASURE AS
(
  SELECT
    [SYMBOL],
    [UNITOFMEASURECLASS],
    [SYSTEMOFUNITS],
    [DECIMALPRECISION],
    [MODIFIEDDATETIME],
    [RECID]
  FROM [ax].UNITOFMEASURE
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view UNITOFMEASURECONVERSION ..'
GO
IF OBJECT_ID(N'[dbo].[UNITOFMEASURECONVERSION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[UNITOFMEASURECONVERSION]
GO
CREATE VIEW [dbo].UNITOFMEASURECONVERSION AS
(
  SELECT
    [FROMUNITOFMEASURE],
    [TOUNITOFMEASURE],
    [PRODUCT],
    [FACTOR],
    [NUMERATOR],
    [DENOMINATOR],
    [INNEROFFSET],
    [OUTEROFFSET],
    [ROUNDING],
    [MODIFIEDDATETIME],
    [RECID]
  FROM [ax].UNITOFMEASURECONVERSION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view UNITOFMEASURETRANSLATION ..'
GO
IF OBJECT_ID(N'[dbo].[UNITOFMEASURETRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [dbo].[UNITOFMEASURETRANSLATION]
GO
CREATE VIEW [dbo].UNITOFMEASURETRANSLATION AS
(
  SELECT
    [UNITOFMEASURE],
    [LANGUAGEID],
    [DESCRIPTION],
    [MODIFIEDDATETIME],
    [RECID]
  FROM [ax].UNITOFMEASURETRANSLATION
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating table UNITTXT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UNITTXT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UNITTXT](
    [UNITID] [nvarchar](10) NOT NULL,
    [LANGUAGEID] [nvarchar](7) NOT NULL,
    [UNITIDTXT] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_1196UNITLANGUAGEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [UNITID] ASC,
    [LANGUAGEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITTXT__UNITID__5ECB9743]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITTXT] ADD  CONSTRAINT [DF__UNITTXT__UNITID__5ECB9743]  DEFAULT ('') FOR [UNITID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITTXT__LANGUAG__5FBFBB7C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITTXT] ADD  CONSTRAINT [DF__UNITTXT__LANGUAG__5FBFBB7C]  DEFAULT ('') FOR [LANGUAGEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITTXT__UNITIDT__60B3DFB5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITTXT] ADD  CONSTRAINT [DF__UNITTXT__UNITIDT__60B3DFB5]  DEFAULT ('') FOR [UNITIDTXT]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__UNITTXT__DATAARE__61A803EE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[UNITTXT] ADD  CONSTRAINT [DF__UNITTXT__DATAARE__61A803EE]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table WORKCALENDARDATE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WORKCALENDARDATE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[WORKCALENDARDATE](
    [CALENDARID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [WORKTIMECONTROL] [int] NULL,
    [TRANSDATE] [datetime] NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_507CALENDARDATEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [CALENDARID] ASC,
    [TRANSDATE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__CALEN__24BE25E8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATE] ADD  CONSTRAINT [DF__WORKCALEN__CALEN__24BE25E8]  DEFAULT ('') FOR [CALENDARID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEND__NAME__25B24A21]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATE] ADD  CONSTRAINT [DF__WORKCALEND__NAME__25B24A21]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__WORKT__26A66E5A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATE] ADD  CONSTRAINT [DF__WORKCALEN__WORKT__26A66E5A]  DEFAULT ((0)) FOR [WORKTIMECONTROL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__TRANS__279A9293]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATE] ADD  CONSTRAINT [DF__WORKCALEN__TRANS__279A9293]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__DATAA__288EB6CC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATE] ADD  CONSTRAINT [DF__WORKCALEN__DATAA__288EB6CC]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table WORKCALENDARDATELINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WORKCALENDARDATELINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[WORKCALENDARDATELINE](
    [PROPERTYID] [nvarchar](10) NULL,
    [EFFECTIVITY] [numeric](28, 12) NULL,
    [TOTIME] [int] NULL,
    [FROMTIME] [int] NOT NULL,
    [CALENDARID] [nvarchar](10) NOT NULL,
    [TRANSDATE] [datetime] NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_508CALENDARDATEFROMIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [CALENDARID] ASC,
    [TRANSDATE] ASC,
    [FROMTIME] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__PROPE__2C5F47B0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATELINE] ADD  CONSTRAINT [DF__WORKCALEN__PROPE__2C5F47B0]  DEFAULT ('') FOR [PROPERTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__EFFEC__2D536BE9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATELINE] ADD  CONSTRAINT [DF__WORKCALEN__EFFEC__2D536BE9]  DEFAULT ((0)) FOR [EFFECTIVITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__TOTIM__2E479022]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATELINE] ADD  CONSTRAINT [DF__WORKCALEN__TOTIM__2E479022]  DEFAULT ((0)) FOR [TOTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__FROMT__2F3BB45B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATELINE] ADD  CONSTRAINT [DF__WORKCALEN__FROMT__2F3BB45B]  DEFAULT ((0)) FOR [FROMTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__CALEN__302FD894]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATELINE] ADD  CONSTRAINT [DF__WORKCALEN__CALEN__302FD894]  DEFAULT ('') FOR [CALENDARID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__TRANS__3123FCCD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATELINE] ADD  CONSTRAINT [DF__WORKCALEN__TRANS__3123FCCD]  DEFAULT ('1900-01-01 00:00:00.000') FOR [TRANSDATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__DATAA__32182106]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARDATELINE] ADD  CONSTRAINT [DF__WORKCALEN__DATAA__32182106]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table WORKCALENDARTABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WORKCALENDARTABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[WORKCALENDARTABLE](
    [NAME] [nvarchar](30) NULL,
    [BASICCALENDARID] [nvarchar](10) NULL,
    [CALENDARID] [nvarchar](10) NOT NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_509CALENDARIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [CALENDARID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEND__NAME__35E8B1EA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARTABLE] ADD  CONSTRAINT [DF__WORKCALEND__NAME__35E8B1EA]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__BASIC__36DCD623]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARTABLE] ADD  CONSTRAINT [DF__WORKCALEN__BASIC__36DCD623]  DEFAULT ('') FOR [BASICCALENDARID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__CALEN__37D0FA5C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARTABLE] ADD  CONSTRAINT [DF__WORKCALEN__CALEN__37D0FA5C]  DEFAULT ('') FOR [CALENDARID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKCALEN__DATAA__38C51E95]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKCALENDARTABLE] ADD  CONSTRAINT [DF__WORKCALEN__DATAA__38C51E95]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table WORKTIMELINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WORKTIMELINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[WORKTIMELINE](
    [WEEKDAY] [int] NULL,
    [EFFECTIVITY] [numeric](28, 12) NULL,
    [FROMTIME] [int] NULL,
    [TOTIME] [int] NULL,
    [WORKTIMEID] [nvarchar](10) NOT NULL,
    [PROPERTYID] [nvarchar](10) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[WORKTIMELINE]') AND name = N'I_510TIMEDAYIDX')
CREATE CLUSTERED INDEX [I_510TIMEDAYIDX] ON [dbo].[WORKTIMELINE]
(
    [DATAAREAID] ASC,
    [WORKTIMEID] ASC,
    [WEEKDAY] ASC,
    [FROMTIME] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMEL__WEEKD__3C95AF79]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMELINE] ADD  CONSTRAINT [DF__WORKTIMEL__WEEKD__3C95AF79]  DEFAULT ((0)) FOR [WEEKDAY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMEL__EFFEC__3D89D3B2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMELINE] ADD  CONSTRAINT [DF__WORKTIMEL__EFFEC__3D89D3B2]  DEFAULT ((0)) FOR [EFFECTIVITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMEL__FROMT__3E7DF7EB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMELINE] ADD  CONSTRAINT [DF__WORKTIMEL__FROMT__3E7DF7EB]  DEFAULT ((0)) FOR [FROMTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMEL__TOTIM__3F721C24]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMELINE] ADD  CONSTRAINT [DF__WORKTIMEL__TOTIM__3F721C24]  DEFAULT ((0)) FOR [TOTIME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMEL__WORKT__4066405D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMELINE] ADD  CONSTRAINT [DF__WORKTIMEL__WORKT__4066405D]  DEFAULT ('') FOR [WORKTIMEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMEL__PROPE__415A6496]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMELINE] ADD  CONSTRAINT [DF__WORKTIMEL__PROPE__415A6496]  DEFAULT ('') FOR [PROPERTYID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMEL__DATAA__424E88CF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMELINE] ADD  CONSTRAINT [DF__WORKTIMEL__DATAA__424E88CF]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table WORKTIMETABLE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WORKTIMETABLE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[WORKTIMETABLE](
    [WORKTIMEID] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [I_511TIMEIDX] PRIMARY KEY CLUSTERED
(
    [DATAAREAID] ASC,
    [WORKTIMEID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMET__WORKT__452AF57A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMETABLE] ADD  CONSTRAINT [DF__WORKTIMET__WORKT__452AF57A]  DEFAULT ('') FOR [WORKTIMEID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMETA__NAME__461F19B3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMETABLE] ADD  CONSTRAINT [DF__WORKTIMETA__NAME__461F19B3]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__WORKTIMET__DATAA__47133DEC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[WORKTIMETABLE] ADD  CONSTRAINT [DF__WORKTIMET__DATAA__47133DEC]  DEFAULT ('DAT') FOR [DATAAREAID]
END

-------------------------------------------------------------------------------
PRINT 'Creating table XPOBJECTTYPE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[XPOBJECTTYPE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[XPOBJECTTYPE](
    [OID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [TYPENAME] [nvarchar](254) NULL,
    [ASSEMBLYNAME] [nvarchar](254) NULL,
 CONSTRAINT [PK_XPOBJECTTYPE] PRIMARY KEY CLUSTERED
(
    [OID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
-------------------------------------------------------------------------------
PRINT 'Creating table ZIPCODE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ZIPCODE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ZIPCODE](
    [ZIPCODE] [nvarchar](10) NOT NULL,
    [CITY] [nvarchar](30) NULL,
    [STREETNAME] [nvarchar](30) NULL,
    [FROMNUM] [int] NULL,
    [TONUM] [int] NULL,
    [EVENODD] [int] NULL,
    [COUNTY] [nvarchar](10) NULL,
    [COUNTRY] [nvarchar](10) NULL,
    [STATE] [nvarchar](10) NULL,
    [CITYALIAS] [nvarchar](30) NULL,
    [DATAAREAID] [nvarchar](4) NOT NULL,
    [RECID] [bigint] NULL,
 CONSTRAINT [PK_ZIPCODE] PRIMARY KEY NONCLUSTERED
(
    [ZIPCODE] ASC,
    [DATAAREAID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ZIPCODE]') AND name = N'I_517ZIPCODEIDX')
CREATE CLUSTERED INDEX [I_517ZIPCODEIDX] ON [dbo].[ZIPCODE]
(
    [DATAAREAID] ASC,
    [ZIPCODE] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__ZIPCODE__6D38E6D4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__ZIPCODE__6D38E6D4]  DEFAULT ('') FOR [ZIPCODE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__CITY__6E2D0B0D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__CITY__6E2D0B0D]  DEFAULT ('') FOR [CITY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__STREETN__6F212F46]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__STREETN__6F212F46]  DEFAULT ('') FOR [STREETNAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__FROMNUM__7015537F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__FROMNUM__7015537F]  DEFAULT ((0)) FOR [FROMNUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__TONUM__710977B8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__TONUM__710977B8]  DEFAULT ((0)) FOR [TONUM]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__EVENODD__71FD9BF1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__EVENODD__71FD9BF1]  DEFAULT ((0)) FOR [EVENODD]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__COUNTY__72F1C02A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__COUNTY__72F1C02A]  DEFAULT ('') FOR [COUNTY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__COUNTRY__73E5E463]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__COUNTRY__73E5E463]  DEFAULT ('') FOR [COUNTRY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__STATE__74DA089C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__STATE__74DA089C]  DEFAULT ('') FOR [STATE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__CITYALI__75CE2CD5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__CITYALI__75CE2CD5]  DEFAULT ('') FOR [CITYALIAS]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ZIPCODE__DATAARE__76C2510E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ZIPCODE] ADD  CONSTRAINT [DF__ZIPCODE__DATAARE__76C2510E]  DEFAULT ('DAT') FOR [DATAAREAID]
END
-------------------------------------------------------------------------------
PRINT 'Creating table SYSTASKRECORDERFRAMEWORKLINE ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SYSTASKRECORDERFRAMEWORKLINE]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE](
    [RECID] [bigint] IDENTITY(1,1) NOT NULL,
    [DESCRIPTION] [nvarchar](max) NULL,
    [FRAMEWORKLEVEL] [bigint] NOT NULL,
    [INDENTATIONLEVEL] [int] NOT NULL,
    [ISSUPPORTED] [int] NOT NULL,
    [MEASURES] [nvarchar](max) NULL,
    [MODULE] [int] NOT NULL,
    [NAME] [nvarchar](255) NOT NULL,
    [ORIGIN] [nvarchar](10) NOT NULL,
    [PARENTFRAMEWORKLINE] [bigint] NOT NULL,
    [SEQUENCE] [int] NOT NULL,
    [SYNCID] [uniqueidentifier] NOT NULL,
    [TASKRECORDEROPERATIONGROUP] [int] NOT NULL,
    [USAGEPROFILE] [int] NOT NULL,
    [ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [PK_SYSTASKRECORDERFRAMEWORKLINE] PRIMARY KEY CLUSTERED
(
    [RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_FRAMEWORKLEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_FRAMEWORKLEVEL]  DEFAULT ((0)) FOR [FRAMEWORKLEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_INDENTATIONLEVEL]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_INDENTATIONLEVEL]  DEFAULT ((0)) FOR [INDENTATIONLEVEL]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_ISSUPPORTED]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_ISSUPPORTED]  DEFAULT ((0)) FOR [ISSUPPORTED]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_MODULE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_MODULE]  DEFAULT ((0)) FOR [MODULE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_NAME]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_NAME]  DEFAULT ('') FOR [NAME]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_ORIGIN]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_ORIGIN]  DEFAULT ('') FOR [ORIGIN]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_PARENTFRAMEWORKLINE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_PARENTFRAMEWORKLINE]  DEFAULT ((0)) FOR [PARENTFRAMEWORKLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_SEQUENCE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_SEQUENCE]  DEFAULT ((0)) FOR [SEQUENCE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_SYNCID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_SYNCID]  DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SYNCID]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_TASKRECORDEROPERATIONGROUP]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_TASKRECORDEROPERATIONGROUP]  DEFAULT ((0)) FOR [TASKRECORDEROPERATIONGROUP]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERFRAMEWORKLINE_USAGEPROFILE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERFRAMEWORKLINE] ADD  CONSTRAINT [DF_SYSTASKRECORDERFRAMEWORKLINE_USAGEPROFILE]  DEFAULT ((0)) FOR [USAGEPROFILE]
END
-------------------------------------------------------------------------------
PRINT 'Creating table SYSTASKRECORDERLINEARTIFACT ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SYSTASKRECORDERLINEARTIFACT]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[SYSTASKRECORDERLINEARTIFACT](
    [RECID] [bigint] IDENTITY(1,1) NOT NULL,
    [FILEPATH] [nvarchar](259) NOT NULL,
    [FRAMEWORKLINE] [bigint] NOT NULL,
    [SOURCEXML] [nvarchar](max) NULL,
    [TYPE] [int] NOT NULL,
    [ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [PK_SYSTASKRECORDERLINEARTIFACT] PRIMARY KEY CLUSTERED
(
    [RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UQ_SYSTASKRECORDERLINEARTIFACT] UNIQUE NONCLUSTERED
(
    [FRAMEWORKLINE] ASC,
    [TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERLINEARTIFACT_FILEPATH]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERLINEARTIFACT] ADD  CONSTRAINT [DF_SYSTASKRECORDERLINEARTIFACT_FILEPATH]  DEFAULT ('') FOR [FILEPATH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERLINEARTIFACT_FRAMEWORKLINE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERLINEARTIFACT] ADD  CONSTRAINT [DF_SYSTASKRECORDERLINEARTIFACT_FRAMEWORKLINE]  DEFAULT ((0)) FOR [FRAMEWORKLINE]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERLINEARTIFACT_TYPE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERLINEARTIFACT] ADD  CONSTRAINT [DF_SYSTASKRECORDERLINEARTIFACT_TYPE]  DEFAULT ((0)) FOR [TYPE]
END
-------------------------------------------------------------------------------
PRINT 'Creating table SYSTASKRECORDERPARAMETERS ..'
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SYSTASKRECORDERPARAMETERS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[SYSTASKRECORDERPARAMETERS](
    [RECID] [bigint] IDENTITY(1,1) NOT NULL,
    [FILEPATH] [nvarchar](259) NULL,
    [KEY] [int] NOT NULL,
    [TEMPLATEPATH] [nvarchar](259) NULL,
    [ROWVERSION] [timestamp] NOT NULL,
 CONSTRAINT [PK_SYSTASKRECORDERPARAMETERS] PRIMARY KEY CLUSTERED
(
    [RECID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERPARAMETERS_FILEPATH]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERPARAMETERS] ADD  CONSTRAINT [DF_SYSTASKRECORDERPARAMETERS_FILEPATH]  DEFAULT ('') FOR [FILEPATH]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERPARAMETERS_KEY]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERPARAMETERS] ADD  CONSTRAINT [DF_SYSTASKRECORDERPARAMETERS_KEY]  DEFAULT ((0)) FOR [KEY]
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_SYSTASKRECORDERPARAMETERS_TEMPLATEPATH]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[SYSTASKRECORDERPARAMETERS] ADD  CONSTRAINT [DF_SYSTASKRECORDERPARAMETERS_TEMPLATEPATH]  DEFAULT ('') FOR [TEMPLATEPATH]
END
-------------------------------------------------------------------------------
PRINT 'Creating view SYSTASKRECORDERFRAMEWORK ..'
GO
IF  OBJECT_ID(N'[dbo].[SYSTASKRECORDERFRAMEWORK]', N'V') IS NOT NULL
    DROP VIEW [dbo].[SYSTASKRECORDERFRAMEWORK]
GO
CREATE VIEW [dbo].[SYSTASKRECORDERFRAMEWORK] AS
(
    SELECT [RECID]
          ,[FRAMEWORKID]
          ,[NAME]
          ,[PUBLISHER]
          ,[SYNCID]
          ,[ROWVERSION]
      FROM [ax].[SYSTASKRECORDERFRAMEWORK]
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view SYSTASKRECORDERFRAMEWORKINDUSTRYMAP ..'
GO
IF OBJECT_ID(N'[dbo].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP]') IS NOT NULL
    DROP VIEW [dbo].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP]
GO
CREATE VIEW [dbo].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP] AS
(
    SELECT [RECID]
          ,[FRAMEWORK]
          ,[GENERATEPROCESSDATA]
          ,[INDUSTRY]
          ,[ROWVERSION]
      FROM [ax].[SYSTASKRECORDERFRAMEWORKINDUSTRYMAP]
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view SYSTASKRECORDERFRAMEWORKLEVEL ..'
GO
IF  OBJECT_ID(N'[dbo].[SYSTASKRECORDERFRAMEWORKLEVEL]') IS NOT NULL
    DROP VIEW [dbo].[SYSTASKRECORDERFRAMEWORKLEVEL]
GO
CREATE VIEW [dbo].[SYSTASKRECORDERFRAMEWORKLEVEL] AS
(
    SELECT [RECID]
          ,[ALLOWARTIFACTS]
          ,[FRAMEWORKINDUSTRYMAP]
          ,[FRAMEWORKLEVEL]
          ,[SEQUENCE]
          ,[ROWVERSION]
      FROM [ax].[SYSTASKRECORDERFRAMEWORKLEVEL]
)
GO
-------------------------------------------------------------------------------
PRINT 'Creating view SYSTASKRECORDERINDUSTRY ..'
GO
IF  OBJECT_ID(N'[dbo].[SYSTASKRECORDERINDUSTRY]') IS NOT NULL
    DROP VIEW [dbo].[SYSTASKRECORDERINDUSTRY]
GO
CREATE VIEW [dbo].[SYSTASKRECORDERINDUSTRY] AS
(
    SELECT [RECID]
          ,[NAME]
          ,[SYSTASKRECORDERINDUSTRYCODE]
          ,[ROWVERSION]
      FROM [ax].[SYSTASKRECORDERINDUSTRY]
)
GO

-- TVPs

-- Creating tvp [dbo].[FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE]
PRINT N'Creating tvp [dbo].[FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE]';

GO
IF TYPE_ID('[dbo].[FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [dbo].[FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN
CREATE TYPE [dbo].[FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE] AS TABLE
(
    [ACCOUNTRELATION] [nvarchar](20) NOT NULL
)

END
GO
PRINT N'Finished creating tvp [dbo].[FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE]'
GO
-- End creating tvp [dbo].[FINDPRICEAGREEMENT_ACCOUNTRELATIONS_TABLETYPE]



-- Creating tvp [dbo].[FINDPROMOTIONPRICE_PRICEGROUPS_TABLETYPE]
PRINT N'Creating tvp [dbo].[FINDPROMOTIONPRICE_PRICEGROUPS_TABLETYPE]';

GO
IF TYPE_ID('[dbo].[FINDPROMOTIONPRICE_PRICEGROUPS_TABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [dbo].[FINDPROMOTIONPRICE_PRICEGROUPS_TABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN
CREATE TYPE [dbo].[FINDPROMOTIONPRICE_PRICEGROUPS_TABLETYPE] AS TABLE
(
    [PRICEGROUPID] [bigint] NOT NULL
)

END
GO
PRINT N'Finished creating tvp [dbo].[FINDPROMOTIONPRICE_PRICEGROUPS_TABLETYPE]'
GO
-- End creating tvp [dbo].[FINDPROMOTIONPRICE_PRICEGROUPS_TABLETYPE]



-- Creating tvp [dbo].[GETPRICEDISCOUNTDATA_PRICEGROUPS_TABLETYPE]
PRINT N'Creating tvp [dbo].[GETPRICEDISCOUNTDATA_PRICEGROUPS_TABLETYPE]';

GO
IF TYPE_ID('[dbo].[GETPRICEDISCOUNTDATA_PRICEGROUPS_TABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [dbo].[GETPRICEDISCOUNTDATA_PRICEGROUPS_TABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN
CREATE TYPE [dbo].[GETPRICEDISCOUNTDATA_PRICEGROUPS_TABLETYPE] AS TABLE
(
    [PRICEGROUPID] [bigint] NOT NULL
)

END
GO
PRINT N'Finished creating tvp [dbo].[GETPRICEDISCOUNTDATA_PRICEGROUPS_TABLETYPE]'
GO
-- End creating tvp [dbo].[GETPRICEDISCOUNTDATA_PRICEGROUPS_TABLETYPE]



-- Creating tvp [dbo].[KITCOMPONENT_TABLETYPE]
PRINT N'Creating tvp [dbo].[KITCOMPONENT_TABLETYPE]';

GO
IF TYPE_ID('[dbo].[KITCOMPONENT_TABLETYPE]') IS NOT NULL
BEGIN
    PRINT N'TVP [dbo].[KITCOMPONENT_TABLETYPE] already exists, Creation has been skipped.'
END
ELSE
BEGIN
CREATE TYPE [dbo].[KITCOMPONENT_TABLETYPE] AS TABLE(
    [KITLINEIDENTIFIER] [bigint] NOT NULL,
    [PRODUCTID] [bigint] NOT NULL
)

END
GO
PRINT N'Finished creating tvp [dbo].[KITCOMPONENT_TABLETYPE]'
GO
-- End creating tvp [dbo].[KITCOMPONENT_TABLETYPE]


-- FUNCTIONS

-- Creating table function [dbo].[GETASSORTEDPRODUCTS]
PRINT N'Creating table function [dbo].[GETASSORTEDPRODUCTS]';

GO
IF OBJECT_ID(N'[dbo].[GETASSORTEDPRODUCTS]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [dbo].[GETASSORTEDPRODUCTS] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [dbo].[GETASSORTEDPRODUCTS].'
GO

ALTER FUNCTION [dbo].[GETASSORTEDPRODUCTS](@bi_ChannelId BIGINT, @dt_ChannelDate DATE)
RETURNS @ASSORTEDPRODUCTS TABLE
(
    [PRODUCTID] BIGINT NOT NULL,
    [ITEMID] NVARCHAR(20) NOT NULL,
    [DISTINCTPRODUCTVARIANT] BIGINT NOT NULL,
    [ISREMOTE] BIT NOT NULL
)
AS
BEGIN
    DECLARE @tvp_DummyId [crt].[RECORDIDTABLETYPE]
    INSERT INTO @tvp_DummyId SELECT 0;

    -- If VARIANTID=0 is returned for a product master, then it implies that all variants are included.
    WITH
    cte_MergedAssortmentRules AS
    (
        -- Merge all overlapping assortment rules.
        SELECT PRODUCTID, ITEMID, VARIANTID, LINETYPE, VALIDFROM, VALIDTO
        FROM [crt].GETMERGEDASSORTMENTRULES(@bi_ChannelId, @dt_ChannelDate, 0/*IsForwardLooking*/, 0/*ProductIdsPassed*/, @tvp_DummyId) ral
    ),
    cte_ExplicitlyExcludedProductsAndVariants (PRODUCTID, VARIANTID, VALIDFROM, VALIDTO) AS
    (
        SELECT PRODUCTID, VARIANTID, VALIDFROM, VALIDTO
        FROM cte_MergedAssortmentRules
        WHERE LINETYPE = 0
    )

    INSERT @ASSORTEDPRODUCTS
    -- Retrieve explicitly included standalone and product masters that have no variant exclusions.
    SELECT
        ral.PRODUCTID,
        ral.ITEMID,
        0 AS 'VARIANTID',
        0 AS 'ISREMOTE'
    FROM cte_MergedAssortmentRules ral
    WHERE @dt_ChannelDate BETWEEN ral.VALIDFROM AND ral.VALIDTO -- Enforce date effectivity
    GROUP BY ral.PRODUCTID, ral.ITEMID
    HAVING MIN(ral.LINETYPE) = 1 -- Remove products that have any exclusions

    UNION ALL

    -- Retrieve implicitly included product variants for product masters that have variant exclusions.
    SELECT
        pv.PRODUCTMASTER AS 'PRODUCTID',
        ral.ITEMID,
        pv.RECID AS 'VARIANTID',
        0 AS 'ISREMOTE'
    FROM cte_MergedAssortmentRules ral
    INNER JOIN [ax].ECORESDISTINCTPRODUCTVARIANT pv ON pv.PRODUCTMASTER = ral.PRODUCTID -- Include variants only
    LEFT OUTER JOIN cte_ExplicitlyExcludedProductsAndVariants epv ON epv.PRODUCTID = pv.PRODUCTMASTER AND (epv.VARIANTID = 0 OR epv.VARIANTID = pv.RECID)
        AND NOT (ral.VALIDFROM > epv.VALIDTO OR ral.VALIDTO < epv.VALIDFROM)
    WHERE ral.VARIANTID != 0 AND ral.LINETYPE = 0 AND epv.PRODUCTID IS NULL -- Remove excluded products and/or variants

    UNION ALL

    -- Retrieve temporarily assorted products that have been downloaded by way of virtual catalog.
    SELECT
        tap.PRODUCTID AS 'PRODUCTID',
        tap.ITEMID,
        0 AS 'VARIANTID',
        1 AS 'ISREMOTE'
    FROM [crt].TMPASSORTEDPRODUCTS tap
    WHERE tap.CHANNELID = @bi_ChannelId AND @dt_ChannelDate BETWEEN tap.VALIDFROM AND tap.VALIDTO

    RETURN
END;


GO
PRINT N'Finished creating table function [dbo].[GETASSORTEDPRODUCTS]'
-- End creating table function [dbo].[GETASSORTEDPRODUCTS]


-- VIEWS

-- Creating view [dbo].[ECORESCATEGORYANCESTORS]
PRINT N'Creating view [dbo].[ECORESCATEGORYANCESTORS]';

GO
IF OBJECT_ID(N'[dbo].[ECORESCATEGORYANCESTORS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ECORESCATEGORYANCESTORS]
GO
CREATE VIEW [dbo].[ECORESCATEGORYANCESTORS] AS
WITH CATEGORYANCESTORS(NAME, RECID, ANCESTORNAME, ANCESTORRECID) AS
(
    -- select all categories
    SELECT
    CATEGORY.NAME,
    CATEGORY.RECID,
    CATEGORY.NAME,
    CATEGORY.RECID
    FROM [dbo].[ECORESCATEGORY] AS CATEGORY

    -- add records found from moving to next ancestor up the hierarchy
    UNION ALL
    SELECT
        CATEGORY.NAME,
        CATEGORY.RECID,
        NEXTANCESTOR.NAME,
        NEXTANCESTOR.RECID
    FROM [dbo].[ECORESCATEGORY] AS CATEGORY
    JOIN CATEGORYANCESTORS AS RECURSIVECATEGORY ON CATEGORY.PARENTCATEGORY = RECURSIVECATEGORY.RECID
    JOIN [dbo].[ECORESCATEGORY] AS NEXTANCESTOR ON RECURSIVECATEGORY.ANCESTORRECID = NEXTANCESTOR.RECID
)
    SELECT
        NAME AS CATEGORYNAME,
        RECID AS CATEGORYRECID,
        ANCESTORNAME AS ANCESTORNAME,
        ANCESTORRECID AS ANCESTORRECID
    FROM CATEGORYANCESTORS


GO
PRINT N'Finished creating view [dbo].[ECORESCATEGORYANCESTORS]'
GO
-- End creating view [dbo].[ECORESCATEGORYANCESTORS]



-- Creating view [dbo].[GETSUPPORTEDLANGUAGEIDS]
PRINT N'Creating view [dbo].[GETSUPPORTEDLANGUAGEIDS]';

GO
IF OBJECT_ID(N'[dbo].[GETSUPPORTEDLANGUAGEIDS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[GETSUPPORTEDLANGUAGEIDS]
GO
CREATE VIEW GETSUPPORTEDLANGUAGEIDS AS
(
    SELECT [LANGUAGEID], [RECID] FROM [dbo].[LANGUAGETABLE]
)

GO
PRINT N'Finished creating view [dbo].[GETSUPPORTEDLANGUAGEIDS]'
GO
-- End creating view [dbo].[GETSUPPORTEDLANGUAGEIDS]



-- Creating view [dbo].[ITEMSVIEW]
PRINT N'Creating view [dbo].[ITEMSVIEW]';

GO
IF OBJECT_ID(N'[dbo].[ITEMSVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ITEMSVIEW]
GO
CREATE VIEW ITEMSVIEW AS
(
    SELECT
        IT.[RECID],
        IT.[ITEMID],
        ERPT.[NAME],
        ERPT.[DESCRIPTION],
        ITM.[PRICE],
        ITM.[UNITID],
        IT.[PRODUCT],
        ITM.[MARKUPGROUPID],
        ITM.[MARKUP],
        ITM.[ALLOCATEMARKUP],
        ITM.[PRICEQTY],
        ITM.[LINEDISC],
        ITM.[MULTILINEDISC],
        ITM.[ENDDISC],
        RIT.[NODISCOUNTALLOWED]
    FROM INVENTTABLE IT
    INNER JOIN ECORESPRODUCTTRANSLATION ERPT ON ERPT.RECID = IT.PRODUCT
    INNER JOIN INVENTTABLEMODULE ITM ON ITM.MODULETYPE = 2 AND ITM.ITEMID = IT.ITEMID AND ITM.DATAAREAID = IT.DATAAREAID
    INNER JOIN RETAILINVENTTABLE RIT ON RIT.ITEMID = IT.ITEMID AND RIT.DATAAREAID = IT.DATAAREAID
)

GO
PRINT N'Finished creating view [dbo].[ITEMSVIEW]'
GO
-- End creating view [dbo].[ITEMSVIEW]



-- Creating view [dbo].[LOGISTICSPOSTALADDRESSVIEW]
PRINT N'Creating view [dbo].[LOGISTICSPOSTALADDRESSVIEW]';

GO
IF OBJECT_ID(N'[dbo].[LOGISTICSPOSTALADDRESSVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[LOGISTICSPOSTALADDRESSVIEW]
GO
CREATE VIEW [dbo].[LOGISTICSPOSTALADDRESSVIEW] AS
(
    SELECT
        T1.COUNTY AS COUNTY,
        T1.DISTRICT AS DISTRICT,
        T1.POSTBOX AS POSTBOX,
        T1.ADDRESS AS ADDRESS,
        T1.BUILDINGCOMPLIMENT AS BUILDINGCOMPLIMENT,
        T1.CITY AS CITY,
        T1.COUNTRYREGIONID AS COUNTRYREGIONID,
        T1.LATITUDE AS LATITUDE,
        T1.STATE AS STATE,
        T1.STREET AS STREET,
        T1.STREETNUMBER AS STREETNUMBER,
        T1.TIMEZONE AS TIMEZONE,
        T1.LONGITUDE AS LONGITUDE,
        T1.ZIPCODE AS ZIPCODE,
        T1.LOCATION AS LOCATION,
        T1.VALIDFROM AS VALIDFROM,
        T1.VALIDTO AS VALIDTO,
        T1.RECID AS POSTALADDRESSRECID,
        T1.RECID AS POSTALADDRESS,
        T1.DISTRICTNAME AS DISTRICTNAME,
        T1.RECID AS RECID,
        T2.DESCRIPTION AS LOCATIONNAME,
        T3.CURRENCYCODE AS COUNTRYCURRENCYCODE,T3.ISOCODE AS ISOCODE
    FROM LOGISTICSPOSTALADDRESS T1
    CROSS JOIN LOGISTICSLOCATION T2
    CROSS JOIN LOGISTICSADDRESSCOUNTRYREGION T3
    WHERE (T1.LOCATION=T2.RECID) AND (T1.COUNTRYREGIONID=T3.COUNTRYREGIONID)
)

GO
PRINT N'Finished creating view [dbo].[LOGISTICSPOSTALADDRESSVIEW]'
GO
-- End creating view [dbo].[LOGISTICSPOSTALADDRESSVIEW]



-- Creating view [dbo].[MARKUPAUTOCONFIGURATIONVIEW]
PRINT N'Creating view [dbo].[MARKUPAUTOCONFIGURATIONVIEW]';

GO
IF OBJECT_ID(N'[dbo].[MARKUPAUTOCONFIGURATIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[MARKUPAUTOCONFIGURATIONVIEW]
GO
CREATE VIEW [dbo].[MARKUPAUTOCONFIGURATIONVIEW] AS
(
    SELECT
        mat.MODULECATEGORY,
        mat.MODULETYPE,
        mat.ACCOUNTCODE,
        mat.ACCOUNTRELATION,
        mat.ITEMCODE,
        mat.ITEMRELATION,
        mat.DLVMODECODE,
        mat.DLVMODERELATION,
        mal.VALUE,
        mal.CURRENCYCODE,
        mt.MARKUPCODE,
        mal.MARKUPCATEGORY AS MARKUPMETHOD,
        mal.TAXGROUP AS SALESTAXGROUP,
        mt.TAXITEMGROUP AS ITEMTAXGROUP,
        mal.FROMAMOUNT,
        mal.TOAMOUNT,
        mal.RECID
    FROM MARKUPAUTOTABLE AS mat
    JOIN MARKUPAUTOLINE AS mal
    -- join where auto charge lines point to autocharge table
    ON 227 = mal.TABLETABLEID AND mat.RECID = mal.TABLERECID
    JOIN MARKUPTABLE AS mt
    -- join to charge code to get charge code tax group
    ON mal.MARKUPCODE = mt.MARKUPCODE AND mal.MODULETYPE = mt.MODULETYPE
    -- only fetch sales and delivery charges
    WHERE (mat.MODULETYPE = 1 OR mat.MODULETYPE = 3)
)

GO
PRINT N'Finished creating view [dbo].[MARKUPAUTOCONFIGURATIONVIEW]'
GO
-- End creating view [dbo].[MARKUPAUTOCONFIGURATIONVIEW]



-- Creating view [dbo].[RETAILPERIODICDISCOUNTSFLATTENED]
PRINT N'Creating view [dbo].[RETAILPERIODICDISCOUNTSFLATTENED]';

GO
IF OBJECT_ID(N'[dbo].[RETAILPERIODICDISCOUNTSFLATTENED]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPERIODICDISCOUNTSFLATTENED]
GO
CREATE VIEW [dbo].[RETAILPERIODICDISCOUNTSFLATTENED] AS
(
    SELECT pd.[OFFERID], pd.[NAME], pd.[PERIODICDISCOUNTTYPE], pd.[PRICEDISCGROUP],
    pd.[VALIDATIONPERIODID], pd.[DATEVALIDATIONTYPE], pd.[VALIDFROM], pd.[VALIDTO],
    pd.[CONCURRENCYMODE], pd.[CURRENCYCODE], pd.[STATUS], pd.[ISDISCOUNTCODEREQUIRED],
    ISNULL(pdmm.MIXANDMATCHDISCOUNTTYPE, ISNULL(pdmb.MULTIBUYDISCOUNTTYPE, pd.PERIODICDISCOUNTTYPE)) as DISCOUNTTYPE,
    0 as NOOFLINESTOTRIGGER,
    pd.[DISCOUNTPERCENTVALUE],
    ISNULL(pdmm.[DEALPRICEVALUE],0.0) as DEALPRICEVALUE,
    ISNULL(pdmm.[DISCOUNTAMOUNTVALUE],0.0) as DISCOUNTAMOUNTVALUE,
    ISNULL(pdmm.[NOOFLEASTEXPENSIVELINES],0) as NOOFLEASTEXPENSIVELINES,
    ISNULL(pdmm.[NUMBEROFTIMESAPPLICABLE],0) as NUMBEROFTIMESAPPLICABLE,
    pdl.[RETAILGROUPMEMBERLINE],
    pdl.[RECID] as DISCOUNTLINEID,
    pdl.[LINENUM],
    pdl.[DISCOUNTPERCENTORVALUE],
    pdl.[UNITOFMEASURE],
    pdt.[COUNTNONDISCOUNTITEMS],
    pd.[DATAAREAID]
    FROM [dbo].[RETAILPERIODICDISCOUNT] as pd
    JOIN [dbo].[RETAILPERIODICDISCOUNTLINE] as pdl ON pd.OFFERID = pdl.OFFERID AND pd.DATAAREAID = pdl.DATAAREAID
    LEFT OUTER JOIN [dbo].[RETAILDISCOUNTMIXANDMATCH] as pdmm ON pd.RECID = pdmm.RECID
    LEFT OUTER JOIN [dbo].[RETAILDISCOUNTMULTIBUY] as pdmb ON pd.RECID = pdmb.RECID
    LEFT OUTER JOIN [dbo].[RETAILDISCOUNTTHRESHOLD] AS pdt ON pd.RECID = pdt.RECID
)

GO
PRINT N'Finished creating view [dbo].[RETAILPERIODICDISCOUNTSFLATTENED]'
GO
-- End creating view [dbo].[RETAILPERIODICDISCOUNTSFLATTENED]



-- Creating view [dbo].[RETAILSPECIALCATEGORYVARIANT]
PRINT N'Creating view [dbo].[RETAILSPECIALCATEGORYVARIANT]';

GO
IF OBJECT_ID(N'[dbo].[RETAILSPECIALCATEGORYVARIANT]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSPECIALCATEGORYVARIANT]
GO
CREATE VIEW [dbo].[RETAILSPECIALCATEGORYVARIANT] AS
(
    SELECT T3.RECID AS PRODUCT, T1.CATEGORY AS CATEGORY
    FROM dbo.RETAILSPECIALCATEGORYMEMBER AS T1
    INNER JOIN dbo.RETAILGROUPMEMBERLINE AS T2 ON T2.RECID = T1.RETAILGROUPMEMBER
    INNER JOIN dbo.ECORESPRODUCT AS T3 ON T3.RECID = T2.VARIANT
)

GO
PRINT N'Finished creating view [dbo].[RETAILSPECIALCATEGORYVARIANT]'
GO
-- End creating view [dbo].[RETAILSPECIALCATEGORYVARIANT]



-- Creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORY]
PRINT N'Creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORY]';

GO
IF OBJECT_ID(N'[dbo].[RETAILPRODUCTORVARIANTCATEGORY]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPRODUCTORVARIANTCATEGORY]
GO
CREATE VIEW [dbo].[RETAILPRODUCTORVARIANTCATEGORY] AS
(
    SELECT T1.CATEGORY AS CATEGORY,T1.PRODUCT AS PRODUCT
    FROM ECORESPRODUCTCATEGORY T1
    UNION
    SELECT T1.CATEGORY,T1.PRODUCT FROM [RETAILSPECIALCATEGORYVARIANT] T1
)

GO
PRINT N'Finished creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORY]'
GO
-- End creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORY]



-- Creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORYANCESTORS]
PRINT N'Creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORYANCESTORS]';

GO
IF OBJECT_ID(N'[dbo].[RETAILPRODUCTORVARIANTCATEGORYANCESTORS]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILPRODUCTORVARIANTCATEGORYANCESTORS]
GO
CREATE VIEW RETAILPRODUCTORVARIANTCATEGORYANCESTORS AS
(
    SELECT RPC.PRODUCT, RCCL.CATEGORY
    FROM RETAILPRODUCTORVARIANTCATEGORY RPC
    INNER JOIN RETAILCATEGORYCONTAINMENTLOOKUP RCCL ON RCCL.CONTAINEDCATEGORY = RPC.CATEGORY
)

GO
PRINT N'Finished creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORYANCESTORS]'
GO
-- End creating view [dbo].[RETAILPRODUCTORVARIANTCATEGORYANCESTORS]



-- Creating view [dbo].[RETAILSTAFFVIEW]
PRINT N'Creating view [dbo].[RETAILSTAFFVIEW]';

GO
IF OBJECT_ID(N'[dbo].[RETAILSTAFFVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILSTAFFVIEW]
GO
CREATE VIEW [dbo].[RETAILSTAFFVIEW] AS
(
    SELECT
        T1.STAFFID,
        T1.BLOCKED,
        T1.CHANGEPASSWORD,
        T1.CONTINUEONTSERRORS,
        T1.EMPLOYMENTTYPE,
        T1.NAMEONRECEIPT,
        T1.PASSWORD,
        T1.PASSWORDDATA,
        T1.RECID,
        T2.RECID AS RETAILHCMWORKER,
        T1.VISUALPROFILE,
        T1.CULTURENAME
    FROM dbo.RETAILSTAFFTABLE AS T1
    INNER JOIN dbo.HCMWORKER AS T2 ON T1.STAFFID = T2.PERSONNELNUMBER
)

GO
PRINT N'Finished creating view [dbo].[RETAILSTAFFVIEW]'
GO
-- End creating view [dbo].[RETAILSTAFFVIEW]



-- Creating view [dbo].[STOREINFORMATIONVIEW]
PRINT N'Creating view [dbo].[STOREINFORMATIONVIEW]';

GO
IF OBJECT_ID(N'[dbo].[STOREINFORMATIONVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[STOREINFORMATIONVIEW]
GO
CREATE VIEW [dbo].[STOREINFORMATIONVIEW] AS
(
    -- 4326 maps to the WGS 84 spatial reference system. Use link to see more info.
    -- https://msdn.microsoft.com/library/bb964707.aspx
    SELECT
        RST.STORENUMBER,
        RCT2.INVENTLOCATION,
        DPT.NAME,
        RCT2.RECID AS CHANNELID,
        GEOGRAPHY::STGeomFromText('POINT(' + CONVERT(VARCHAR(100), LPA.LONGITUDE) + ' ' +  CONVERT(VARCHAR(100), LPA.LATITUDE) + ')', 4326) AS GEOLOCATION,
        LPA.*
    FROM RETAILSTORETABLE AS RST
    INNER JOIN RETAILCHANNELTABLE AS RCT2 ON RCT2.RECID = RST.RECID
    INNER JOIN OMOPERATINGUNIT AS OU ON OU.RECID = RCT2.OMOPERATINGUNITID
    INNER JOIN DIRPARTYTABLE AS DPT ON DPT.RECID = OU.RECID
    INNER JOIN DIRPARTYLOCATION AS DPL ON DPL.PARTY = DPT.RECID
    INNER JOIN LOGISTICSPOSTALADDRESS AS LPA ON LPA.LOCATION = DPL.LOCATION
    WHERE RST.RECID IN (
        SELECT DISTINCT RSLGM.STORE
        FROM RETAILCHANNELTABLE AS RCT1
        INNER JOIN RETAILSTORELOCATORGROUPOWNER AS RSLGO ON RSLGO.CHANNEL = RCT1.RECID
        INNER JOIN RETAILSTORELOCATORGROUP AS RSLG ON RSLGO.LOCATORGROUP = RSLGO.RECID
        INNER JOIN RETAILSTORELOCATORGROUPMEMBER AS RSLGM ON RSLGM.LOCATORGROUP = RSLG.RECID
    ) AND DPL.IsPrimary = 1
)

GO
PRINT N'Finished creating view [dbo].[STOREINFORMATIONVIEW]'
GO
-- End creating view [dbo].[STOREINFORMATIONVIEW]



-- Creating view [dbo].[DIRPARTYPOSTALADDRESSVIEW]
PRINT N'Creating view [dbo].[DIRPARTYPOSTALADDRESSVIEW]';

GO
IF OBJECT_ID(N'[dbo].[DIRPARTYPOSTALADDRESSVIEW]', N'V') IS NOT NULL
    DROP VIEW [dbo].[DIRPARTYPOSTALADDRESSVIEW]
GO
CREATE VIEW [dbo].[DIRPARTYPOSTALADDRESSVIEW] AS
(
    SELECT
        T1.PARTY AS PARTY,
        T1.RECID AS PARTYLOCATION,
        T1.ISPRIMARY AS ISPRIMARY,
        T1.ISPRIVATE AS ISPRIVATE,
        T1.ISLOCATIONOWNER AS ISLOCATIONOWNER,
        T1.RECID AS RECID,
        T2.LOCATIONNAME AS LOCATIONNAME,
        T2.ADDRESS AS ADDRESS,
        T2.STREETNUMBER AS STREETNUMBER,
        T2.STREET AS STREET,
        T2.CITY AS CITY,
        T2.ZIPCODE AS ZIPCODE,
        T2.STATE AS STATE,
        T2.COUNTY AS COUNTY,
        T2.COUNTRYREGIONID AS COUNTRYREGIONID,
        T2.DISTRICT AS DISTRICT,
        T2.POSTBOX AS POSTBOX,
        T2.BUILDINGCOMPLIMENT AS BUILDINGCOMPLIMENT,
        T2.TIMEZONE AS TIMEZONE,
        T2.LONGITUDE AS LONGITUDE,
        T2.LATITUDE AS LATITUDE,
        T2.LOCATION AS LOCATION,
        T2.VALIDFROM AS VALIDFROM,
        T2.VALIDTO AS VALIDTO,
        T2.COUNTRYCURRENCYCODE AS COUNTRYCURRENCYCODE,
        T2.DISTRICTNAME AS DISTRICTNAME,
        T2.POSTALADDRESS AS POSTALADDRESS,
        T2.ISOCODE AS ISOCODE
    FROM  DIRPARTYLOCATION T1
    LEFT OUTER JOIN LOGISTICSPOSTALADDRESSVIEW T2 ON (T1.LOCATION=T2.LOCATION)
    WHERE (T1.ISPOSTALADDRESS=1)
        AND NOT EXISTS (
            SELECT 'x' FROM DIRPARTYLOCATIONROLE T3
            WHERE (T3.PARTYLOCATION=T1.RECID)
        AND EXISTS (
            SELECT 'x' FROM LOGISTICSLOCATIONROLE T4
            WHERE ((T4.TYPE=16) AND (T3.LOCATIONROLE=T4.RECID))))
)

GO
PRINT N'Finished creating view [dbo].[DIRPARTYPOSTALADDRESSVIEW]'
GO
-- End creating view [dbo].[DIRPARTYPOSTALADDRESSVIEW]



-- Creating view [dbo].[ACCOUNTANT_BR]
PRINT N'Creating view [dbo].[ACCOUNTANT_BR]';

GO
IF OBJECT_ID(N'[dbo].[ACCOUNTANT_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ACCOUNTANT_BR]
GO
CREATE VIEW [dbo].[ACCOUNTANT_BR] AS
(
    SELECT
        CNPJNUM_BR,
        CPFNUM_BR,
        CRCNUM_BR,
        NAME,
        ROWVERSION,
        RECID
    FROM [ax].ACCOUNTANT_BR
)

GO
PRINT N'Finished creating view [dbo].[ACCOUNTANT_BR]'
GO
-- End creating view [dbo].[ACCOUNTANT_BR]



-- Creating view [dbo].[ACCOUNTANTLOGISTICSLOCATION_BR]
PRINT N'Creating view [dbo].[ACCOUNTANTLOGISTICSLOCATION_BR]';

GO
IF OBJECT_ID(N'[dbo].[ACCOUNTANTLOGISTICSLOCATION_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ACCOUNTANTLOGISTICSLOCATION_BR]
GO
CREATE VIEW [dbo].[ACCOUNTANTLOGISTICSLOCATION_BR] AS
(
    SELECT
        ACCOUNTANT,
        ISDEFAULT,
        ISPOSTALADDRESS,
        ISPRIMARY,
        ISPRIVATE,
        LOCATION,
        ROWVERSION,
        RECID
    FROM [ax].ACCOUNTANTLOGISTICSLOCATION_BR
)

GO
PRINT N'Finished creating view [dbo].[ACCOUNTANTLOGISTICSLOCATION_BR]'
GO
-- End creating view [dbo].[ACCOUNTANTLOGISTICSLOCATION_BR]



-- Creating view [dbo].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR]
PRINT N'Creating view [dbo].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR]';

GO
IF OBJECT_ID(N'[dbo].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR]
GO
CREATE VIEW [dbo].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR] AS
(
    SELECT
        ACCOUNTANTLOGISTICSLOCATION,
        LOCATIONROLE,
        ROWVERSION,
        RECID
    FROM [ax].ACCOUNTANTLOGISTICSLOCATIONROLE_BR
)

GO
PRINT N'Finished creating view [dbo].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR]'
GO
-- End creating view [dbo].[ACCOUNTANTLOGISTICSLOCATIONROLE_BR]



-- Creating view [dbo].[FISCALESTABLISHMENT_BR]
PRINT N'Creating view [dbo].[FISCALESTABLISHMENT_BR]';

GO
IF OBJECT_ID(N'[dbo].[FISCALESTABLISHMENT_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[FISCALESTABLISHMENT_BR]
GO
CREATE VIEW [dbo].[FISCALESTABLISHMENT_BR] AS
(
    SELECT
        ACCOUNTANT_BR,
        CCMNUM_BR,
        CNPJCPFNUM_BR,
        DIRPARTYLOCATION,
        FISCALESTABLISHMENTID,
        IENUM_BR,
        NAME,
        DATAAREAID,
        ROWVERSION,
        RECID
    FROM [ax].FISCALESTABLISHMENT_BR
)

GO
PRINT N'Finished creating view [dbo].[FISCALESTABLISHMENT_BR]'
GO
-- End creating view [dbo].[FISCALESTABLISHMENT_BR]



-- Creating view [dbo].[FISCALESTABLISHMENTINVENTSITE_BR]
PRINT N'Creating view [dbo].[FISCALESTABLISHMENTINVENTSITE_BR]';

GO
IF OBJECT_ID(N'[dbo].[FISCALESTABLISHMENTINVENTSITE_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[FISCALESTABLISHMENTINVENTSITE_BR]
GO
CREATE VIEW [dbo].[FISCALESTABLISHMENTINVENTSITE_BR] AS
(
    SELECT
        FISCALESTABLISHMENT_BR,
        INVENTSITE,
        DATAAREAID,
        ROWVERSION,
        RECID
    FROM [ax].FISCALESTABLISHMENTINVENTSITE_BR
)

GO
PRINT N'Finished creating view [dbo].[FISCALESTABLISHMENTINVENTSITE_BR]'
GO
-- End creating view [dbo].[FISCALESTABLISHMENTINVENTSITE_BR]



-- Creating view [dbo].[RETAILFISCALDOCUMENTMODEL2_BR]
PRINT N'Creating view [dbo].[RETAILFISCALDOCUMENTMODEL2_BR]';

GO
IF OBJECT_ID(N'[dbo].[RETAILFISCALDOCUMENTMODEL2_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILFISCALDOCUMENTMODEL2_BR]
GO
CREATE VIEW [dbo].[RETAILFISCALDOCUMENTMODEL2_BR] AS
(
    SELECT
        CONSUMERCNPJCPFNUMBER AS CONSUMERCNPJCPFNUMBER,
        FISCALDOCUMENTACCOUNTNUM AS FISCALDOCUMENTACCOUNTNUM,
        FISCALDOCUMENTDATE AS FISCALDOCUMENTDATE,
        FISCALDOCUMENTNUMBER AS FISCALDOCUMENTNUMBER,
        FISCALDOCUMENTSERIES AS FISCALDOCUMENTSERIES,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STATUS AS STATUS,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TOTALAMOUNT AS TOTALAMOUNT,
        TOTALDISCOUNTAMOUNT AS TOTALDISCOUNTAMOUNT,
        TOTALSURCHARGEAMOUNT AS TOTALSURCHARGEAMOUNT,
        TRANSACTIONID AS TRANSACTIONID,
        DATAAREAID,
        ROWVERSION
    FROM [ax].RETAILFISCALDOCUMENTMODEL2_BR
)

GO
PRINT N'Finished creating view [dbo].[RETAILFISCALDOCUMENTMODEL2_BR]'
GO
-- End creating view [dbo].[RETAILFISCALDOCUMENTMODEL2_BR]



-- Creating view [dbo].[RETAILFISCALDOCUMENTMODEL2LINE_BR]
PRINT N'Creating view [dbo].[RETAILFISCALDOCUMENTMODEL2LINE_BR]';

GO
IF OBJECT_ID(N'[dbo].[RETAILFISCALDOCUMENTMODEL2LINE_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILFISCALDOCUMENTMODEL2LINE_BR]
GO
CREATE VIEW [dbo].[RETAILFISCALDOCUMENTMODEL2LINE_BR] AS
(
    SELECT
        CFOP AS CFOP,
        ITEMID AS ITEMID,
        LINEAMOUNT AS LINEAMOUNT,
        LINEDISCOUNT AS LINEDISCOUNT,
        LINENUM AS LINENUM,
        LINESURCHARGE AS LINESURCHARGE,
        QUANTITY AS QUANTITY,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TRANSACTIONID AS TRANSACTIONID,
        UNIT AS UNIT,
        UNITPRICE AS UNITPRICE,
        DATAAREAID,
        ROWVERSION
    FROM [ax].RETAILFISCALDOCUMENTMODEL2LINE_BR
)

GO
PRINT N'Finished creating view [dbo].[RETAILFISCALDOCUMENTMODEL2LINE_BR]'
GO
-- End creating view [dbo].[RETAILFISCALDOCUMENTMODEL2LINE_BR]



-- Creating view [dbo].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR]
PRINT N'Creating view [dbo].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR]';

GO
IF OBJECT_ID(N'[dbo].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR]
GO
CREATE VIEW [dbo].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR] AS
(
    SELECT
        FISCALVALUE AS FISCALVALUE,
        LINENUM AS LINENUM,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STOREID AS STOREID,
        TAXAMOUNT AS TAXAMOUNT,
        TAXATIONCODE AS TAXATIONCODE,
        TAXATIONORIGIN AS TAXATIONORIGIN,
        TAXBASEAMOUNT AS TAXBASEAMOUNT,
        TAXCODE AS TAXCODE,
        TAXREDUCTIONPCT AS TAXREDUCTIONPCT,
        TAXTYPE AS TAXTYPE,
        TAXVALUE AS TAXVALUE,
        TERMINALID AS TERMINALID,
        TRANSACTIONID AS TRANSACTIONID,
        DATAAREAID,
        ROWVERSION
    FROM [ax].RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR
)

GO
PRINT N'Finished creating view [dbo].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR]'
GO
-- End creating view [dbo].[RETAILFISCALDOCUMENTMODEL2TAXTRANS_BR]



-- Creating view [dbo].[RetailFiscalPrinter_BR]
PRINT N'Creating view [dbo].[RetailFiscalPrinter_BR]';

GO
IF OBJECT_ID(N'[dbo].[RetailFiscalPrinter_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RetailFiscalPrinter_BR]
GO
CREATE VIEW [dbo].[RetailFiscalPrinter_BR] AS
(
    SELECT
        ADDITIONALFISCALMEMORYINDEX AS ADDITIONALFISCALMEMORYINDEX,
        FISCALESTABLISHMENT AS FISCALESTABLISHMENT,
        FISCALRECEIPTMODEL AS FISCALRECEIPTMODEL,
        MANUFACTURER AS MANUFACTURER,
        MODELNUMBER AS MODELNUMBER,
        NATIONALCODE AS NATIONALCODE,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        RESTARTOPERATIONNUMBER AS RESTARTOPERATIONNUMBER,
        SERIALNUMBER AS SERIALNUMBER,
        SOFTWAREDATE AS SOFTWAREDATE,
        SOFTWAREVERSION AS SOFTWAREVERSION,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TERMINALNUMBER AS TERMINALNUMBER,
        TYPE AS TYPE,
        DATAAREAID,
        ROWVERSION
    FROM [ax].RetailFiscalPrinter_BR
)

GO
PRINT N'Finished creating view [dbo].[RetailFiscalPrinter_BR]'
GO
-- End creating view [dbo].[RetailFiscalPrinter_BR]



-- Creating view [DBO].[RETAILFISCALPRINTERREPORT_BR]
PRINT N'Creating view [DBO].[RETAILFISCALPRINTERREPORT_BR]';

GO
IF OBJECT_ID(N'[DBO].[RETAILFISCALPRINTERREPORT_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RETAILFISCALPRINTERREPORT_BR]
GO
CREATE VIEW [DBO].[RETAILFISCALPRINTERREPORT_BR] AS
(
    SELECT
        ADDITIONALFISCALMEMORYINDEX AS ADDITIONALFISCALMEMORYINDEX,
        CREDITDEBITRECEIPTNUMBER AS CREDITDEBITRECEIPTNUMBER,
        FISCALPRINTERSERIALNUMBER AS FISCALPRINTERSERIALNUMBER,
        MANAGEMENTREPORTNUMBER AS MANAGEMENTREPORTNUMBER,
        NONFISCALOPERATIONNUMBER AS NONFISCALOPERATIONNUMBER,
        RECEIPTNUMBER AS RECEIPTNUMBER,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        REPORTDATETIME AS REPORTDATETIME,
        REPORTDATETIMETZID,
        REPORTTYPE AS REPORTTYPE,
        RESTARTOPERATIONNUMBER AS RESTARTOPERATIONNUMBER,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TRANSACTIONDATETIME AS TRANSACTIONDATETIME,
        TRANSACTIONID AS TRANSACTIONID,
        DATAAREAID,
        ROWVERSION
    FROM [AX].RETAILFISCALPRINTERREPORT_BR
)

GO
PRINT N'Finished creating view [DBO].[RETAILFISCALPRINTERREPORT_BR]'
GO
-- End creating view [DBO].[RETAILFISCALPRINTERREPORT_BR]



-- Creating view [DBO].[RETAILFISCALRECEIPT_BR]
PRINT N'Creating view [DBO].[RETAILFISCALRECEIPT_BR]';

GO
IF OBJECT_ID(N'[DBO].[RETAILFISCALRECEIPT_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RETAILFISCALRECEIPT_BR]
GO
CREATE VIEW [DBO].[RETAILFISCALRECEIPT_BR] AS
(
    SELECT
        ACCOUNTINGDATE AS ACCOUNTINGDATE,
        ADDITIONALFISCALMEMORYINDEX AS ADDITIONALFISCALMEMORYINDEX,
        CONSUMERCNPJCPFNUMBER AS CONSUMERCNPJCPFNUMBER,
        CONSUMERNAME AS CONSUMERNAME,
        FISCALESTABLISHMENT AS FISCALESTABLISHMENT,
        FISCALPRINTERSERIALNUMBER AS FISCALPRINTERSERIALNUMBER,
        FISCALRECEIPTDATETIME AS FISCALRECEIPTDATETIME,
        FISCALRECEIPTDATETIMETZID,
        FISCALRECEIPTMODEL AS FISCALRECEIPTMODEL,
        FISCALRECEIPTNUMBER AS FISCALRECEIPTNUMBER,
        PRINTEDTOTALDISCOUNTAMOUNT AS PRINTEDTOTALDISCOUNTAMOUNT,
        PRINTEDTOTALSURCHARGEAMOUNT AS PRINTEDTOTALSURCHARGEAMOUNT,
        QUANTITYDECIMALS AS QUANTITYDECIMALS,
        RECEIPTNUMBER AS RECEIPTNUMBER,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STATUS AS STATUS,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TOTALAMOUNT AS TOTALAMOUNT,
        TOTALDISCOUNTAMOUNT AS TOTALDISCOUNTAMOUNT,
        TOTALSURCHARGEAMOUNT AS TOTALSURCHARGEAMOUNT,
        TRANSACTIONID AS TRANSACTIONID,
        UNITDECIMALS AS UNITDECIMALS,
        VOIDEDAFTERENDRECEIPT AS VOIDEDAFTERENDRECEIPT,
        ZREPORTNUMBER AS ZREPORTNUMBER,
        DATAAREAID,
        ROWVERSION
    FROM [AX].RETAILFISCALRECEIPT_BR
)

GO
PRINT N'Finished creating view [DBO].[RETAILFISCALRECEIPT_BR]'
GO
-- End creating view [DBO].[RETAILFISCALRECEIPT_BR]



-- Creating view [DBO].[RETAILFISCALRECEIPTLINE_BR]
PRINT N'Creating view [DBO].[RETAILFISCALRECEIPTLINE_BR]';

GO
IF OBJECT_ID(N'[DBO].[RETAILFISCALRECEIPTLINE_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RETAILFISCALRECEIPTLINE_BR]
GO
CREATE VIEW [DBO].[RETAILFISCALRECEIPTLINE_BR] AS
(
    SELECT
        CANCELLEDQUANTITY AS CANCELLEDQUANTITY,
        CFOP AS CFOP,
        ITEMID AS ITEMID,
        ITEMTYPE AS ITEMTYPE,
        LINEAMOUNT AS LINEAMOUNT,
        LINEDISCOUNTAMOUNT AS LINEDISCOUNTAMOUNT,
        LINENUM AS LINENUM,
        LINESURCHARGEAMOUNT AS LINESURCHARGEAMOUNT,
        PRINTEDLINEDISCOUNTAMOUNT AS PRINTEDLINEDISCOUNTAMOUNT,
        PRINTEDLINESURCHARGEAMOUNT AS PRINTEDLINESURCHARGEAMOUNT,
        QUANTITY AS QUANTITY,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TRANSACTIONID AS TRANSACTIONID,
        UNIT AS UNIT,
        UNITPRICE AS UNITPRICE,
    DATAAREAID
    FROM [AX].RETAILFISCALRECEIPTLINE_BR
)

GO
PRINT N'Finished creating view [DBO].[RETAILFISCALRECEIPTLINE_BR]'
GO
-- End creating view [DBO].[RETAILFISCALRECEIPTLINE_BR]



-- Creating view [DBO].[RetailFiscalReceiptTaxTrans_BR]
PRINT N'Creating view [DBO].[RetailFiscalReceiptTaxTrans_BR]';

GO
IF OBJECT_ID(N'[DBO].[RetailFiscalReceiptTaxTrans_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RetailFiscalReceiptTaxTrans_BR]
GO
CREATE VIEW [DBO].[RetailFiscalReceiptTaxTrans_BR] AS
(
    SELECT
        FISCALVALUE AS FISCALVALUE,
        LINENUM AS LINENUM,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STOREID AS STOREID,
        TAXAMOUNT AS TAXAMOUNT,
        TAXATIONCODE AS TAXATIONCODE,
        TAXBASEAMOUNT AS TAXBASEAMOUNT,
        TAXCODE AS TAXCODE,
        TAXTYPE AS TAXTYPE,
        TAXVALUE AS TAXVALUE,
        TERMINALID AS TERMINALID,
        TOTALIZERINDEX AS TOTALIZERINDEX,
        TOTALIZERNAME AS TOTALIZERNAME,
        TRANSACTIONID AS TRANSACTIONID,
    DATAAREAID
    FROM [AX].RetailFiscalReceiptTaxTrans_BR
)

GO
PRINT N'Finished creating view [DBO].[RetailFiscalReceiptTaxTrans_BR]'
GO
-- End creating view [DBO].[RetailFiscalReceiptTaxTrans_BR]



-- Creating view [DBO].[RetailTransactionPaymentTrans_BR]
PRINT N'Creating view [DBO].[RetailTransactionPaymentTrans_BR]';

GO
IF OBJECT_ID(N'[DBO].[RetailTransactionPaymentTrans_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RetailTransactionPaymentTrans_BR]
GO
CREATE VIEW [DBO].[RetailTransactionPaymentTrans_BR] AS
(
    SELECT
        AMOUNTCUR AS AMOUNTCUR,
        AMOUNTTENDERED AS AMOUNTTENDERED,
        LINENUM AS LINENUM,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STOREID AS STOREID,
        TENDERTYPE AS TENDERTYPE,
        TERMINALID AS TERMINALID,
        TRANSACTIONID AS TRANSACTIONID,
        TRANSACTIONSTATUS AS TRANSACTIONSTATUS,
        TRANSDATE AS TRANSDATE,
        TRANSTIME AS TRANSTIME,
    DATAAREAID
    FROM [AX].RetailTransactionPaymentTrans_BR
)

GO
PRINT N'Finished creating view [DBO].[RetailTransactionPaymentTrans_BR]'
GO
-- End creating view [DBO].[RetailTransactionPaymentTrans_BR]



-- Creating view [DBO].[RetailZReport_BR]
PRINT N'Creating view [DBO].[RetailZReport_BR]';

GO
IF OBJECT_ID(N'[DBO].[RetailZReport_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RetailZReport_BR]
GO
CREATE VIEW [DBO].[RetailZReport_BR] AS
(
    SELECT
        ACCOUNTINGDATE AS ACCOUNTINGDATE,
        ADDITIONALFISCALMEMORYINDEX AS ADDITIONALFISCALMEMORYINDEX,
        COFINSAMOUNT AS COFINSAMOUNT,
        FINALGRANDTOTALAMOUNT AS FINALGRANDTOTALAMOUNT,
        FIRSTRECEIPTNUMBER AS FIRSTRECEIPTNUMBER,
        FISCALESTABLISHMENT AS FISCALESTABLISHMENT,
        FISCALPRINTERSERIALNUMBER AS FISCALPRINTERSERIALNUMBER,
        FISCALRECEIPTMODEL AS FISCALRECEIPTMODEL,
        GROSSDAILYSALE AS GROSSDAILYSALE,
        INITIALGRANDTOTALAMOUNT AS INITIALGRANDTOTALAMOUNT,
        ISSDISCOUNT AS ISSDISCOUNT,
        LASTRECEIPTNUMBER AS LASTRECEIPTNUMBER,
        NETAMOUNT AS NETAMOUNT,
        PISAMOUNT AS PISAMOUNT,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        RESTARTOPERATIONNUMBER AS RESTARTOPERATIONNUMBER,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TERMINALNUMBER AS TERMINALNUMBER,
        ZREPORTDATETIME AS ZREPORTDATETIME,
        ZREPORTDATETIMETZID,
        ZREPORTNUMBER AS ZREPORTNUMBER,
        VERSION AS VERSION,
        DATAAREAID
    FROM [AX].RetailZReport_BR
)

GO
PRINT N'Finished creating view [DBO].[RetailZReport_BR]'
GO
-- End creating view [DBO].[RetailZReport_BR]



-- Creating view [DBO].[RetailZReportTotalizer_BR]
PRINT N'Creating view [DBO].[RetailZReportTotalizer_BR]';

GO
IF OBJECT_ID(N'[DBO].[RetailZReportTotalizer_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RetailZReportTotalizer_BR]
GO
CREATE VIEW [DBO].[RetailZReportTotalizer_BR] AS
(
    SELECT
        ADDITIONALFISCALMEMORYINDEX AS ADDITIONALFISCALMEMORYINDEX,
        FISCALPRINTERSERIALNUMBER AS FISCALPRINTERSERIALNUMBER,
        REPLICATIONCOUNTERFROMORIGIN AS REPLICATIONCOUNTER,
        STOREID AS STOREID,
        TERMINALID AS TERMINALID,
        TOTALIZERAMOUNT AS TOTALIZERAMOUNT,
        TOTALIZERNAME AS TOTALIZERNAME,
        TOTALIZERSINTEGRANAME AS TOTALIZERSINTEGRANAME,
        ZREPORTNUMBER AS ZREPORTNUMBER,
    DATAAREAID
    FROM [AX].RetailZReportTotalizer_BR
)

GO
PRINT N'Finished creating view [DBO].[RetailZReportTotalizer_BR]'
GO
-- End creating view [DBO].[RetailZReportTotalizer_BR]



-- Creating view [DBO].[TaxationCodeSetup_BR]
PRINT N'Creating view [DBO].[TaxationCodeSetup_BR]';

GO
IF OBJECT_ID(N'[DBO].[TaxationCodeSetup_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[TaxationCodeSetup_BR]
GO
CREATE VIEW [DBO].[TaxationCodeSetup_BR] AS
(
    SELECT
        RECID,
        MANDATORY,
        TAXTYPE,
        DATAAREAID
    FROM [AX].TaxationCodeSetup_BR
)

GO
PRINT N'Finished creating view [DBO].[TaxationCodeSetup_BR]'
GO
-- End creating view [DBO].[TaxationCodeSetup_BR]



-- Creating view [DBO].[TAXATIONCODETABLE_BR]
PRINT N'Creating view [DBO].[TAXATIONCODETABLE_BR]';

GO
IF OBJECT_ID(N'[DBO].[TAXATIONCODETABLE_BR]', N'V') IS NOT NULL
    DROP VIEW [DBO].[TAXATIONCODETABLE_BR]
GO
CREATE VIEW [DBO].[TAXATIONCODETABLE_BR] AS
(
    SELECT
        RECID,
        ATOCOTEPETAXCODE
        DESCRIPTION,
        FISCALVALUE,
        FROMDATE,
        INPUTCODE,
        OUTPUTCODE,
        TAXATIONCODE,
        TAXTYPE,
        TODATE,
        DATAAREAID
    FROM [AX].TAXATIONCODETABLE_BR
)

GO
PRINT N'Finished creating view [DBO].[TAXATIONCODETABLE_BR]'
GO
-- End creating view [DBO].[TAXATIONCODETABLE_BR]



-- Creating view [DBO].[PlFiscalTaxTable]
PRINT N'Creating view [DBO].[PlFiscalTaxTable]';

GO
IF OBJECT_ID(N'[DBO].[PlFiscalTaxTable]', N'V') IS NOT NULL
    DROP VIEW [DBO].[PlFiscalTaxTable]
GO
CREATE VIEW [DBO].[PlFiscalTaxTable] AS
(
    SELECT
        RECID,
        FISCALPRINTERCODE,
        FISCALTAXCODE,
        TAXCODE,
        DATAAREAID
    FROM [AX].PlFiscalTaxTable
)

GO
PRINT N'Finished creating view [DBO].[PlFiscalTaxTable]'
GO
-- End creating view [DBO].[PlFiscalTaxTable]



-- Creating view [DBO].[FORMULADESIGNER_IN]
PRINT N'Creating view [DBO].[FORMULADESIGNER_IN]';

GO
IF OBJECT_ID(N'[DBO].[FORMULADESIGNER_IN]', N'V') IS NOT NULL
    DROP VIEW [DBO].[FORMULADESIGNER_IN]
GO
CREATE VIEW [DBO].[FORMULADESIGNER_IN] AS
(
    SELECT
        RECID,
        CALCEXP,
        CALCEXP1,
        ID,
        PRICEINCLTAX,
        TAXABLEBASIS,
        TAXCODE,
        TAXITEMGROUP,
        DATAAREAID
    FROM [AX].FORMULADESIGNER_IN
)

GO
PRINT N'Finished creating view [DBO].[FORMULADESIGNER_IN]'
GO
-- End creating view [DBO].[FORMULADESIGNER_IN]



-- Creating view [DBO].[RetailStoreTable_IN]
PRINT N'Creating view [DBO].[RetailStoreTable_IN]';

GO
IF OBJECT_ID(N'[DBO].[RetailStoreTable_IN]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RetailStoreTable_IN]
GO
CREATE VIEW [DBO].[RetailStoreTable_IN] AS
(
    SELECT
        RECID,
        RETAILSTORETABLE,
        SALESTAXFORMTYPES,
        SHOWTAXONTAX,
        TAXDETAILSTYPE
    FROM [AX].RetailStoreTable_IN
)

GO
PRINT N'Finished creating view [DBO].[RetailStoreTable_IN]'
GO
-- End creating view [DBO].[RetailStoreTable_IN]



-- Creating view [DBO].[TaxComponentTable_IN]
PRINT N'Creating view [DBO].[TaxComponentTable_IN]';

GO
IF OBJECT_ID(N'[DBO].[TaxComponentTable_IN]', N'V') IS NOT NULL
    DROP VIEW [DBO].[TaxComponentTable_IN]
GO
CREATE VIEW [DBO].[TaxComponentTable_IN] AS
(
    SELECT
        RECID,
        TAXTYPE,
        COMPONENT,
        DATAAREAID
    FROM [AX].TaxComponentTable_IN
)

GO
PRINT N'Finished creating view [DBO].[TaxComponentTable_IN]'
GO
-- End creating view [DBO].[TaxComponentTable_IN]



-- Creating view [DBO].[TaxInformation_IN]
PRINT N'Creating view [DBO].[TaxInformation_IN]';

GO
IF OBJECT_ID(N'[DBO].[TaxInformation_IN]', N'V') IS NOT NULL
    DROP VIEW [DBO].[TaxInformation_IN]
GO
CREATE VIEW [DBO].[TaxInformation_IN] AS
(
    SELECT
        RECID,
        ECCNUMBER,
        ISPRIMARY,
        REGISTRATIONLOCATION,
        STCREGISTRATIONNUMBERTABLE,
        TIN
    FROM [AX].TaxInformation_IN
)

GO
PRINT N'Finished creating view [DBO].[TaxInformation_IN]'
GO
-- End creating view [DBO].[TaxInformation_IN]



-- Creating view [DBO].[TaxInformationLegalEntity_IN]
PRINT N'Creating view [DBO].[TaxInformationLegalEntity_IN]';

GO
IF OBJECT_ID(N'[DBO].[TaxInformationLegalEntity_IN]', N'V') IS NOT NULL
    DROP VIEW [DBO].[TaxInformationLegalEntity_IN]
GO
CREATE VIEW [DBO].[TaxInformationLegalEntity_IN] AS
(
    SELECT
        RECID,
        LEGALENTITY,
        PANNUMBER,
        DATAAREAID
    FROM [AX].TaxInformationLegalEntity_IN
)

GO
PRINT N'Finished creating view [DBO].[TaxInformationLegalEntity_IN]'
GO
-- End creating view [DBO].[TaxInformationLegalEntity_IN]



-- Creating view [DBO].[TaxRegistrationNumbers_IN]
PRINT N'Creating view [DBO].[TaxRegistrationNumbers_IN]';

GO
IF OBJECT_ID(N'[DBO].[TaxRegistrationNumbers_IN]', N'V') IS NOT NULL
    DROP VIEW [DBO].[TaxRegistrationNumbers_IN]
GO
CREATE VIEW [DBO].[TaxRegistrationNumbers_IN] AS
(
    SELECT
        RECID,
        REGISTRATIONNUMBER
    FROM [AX].TaxRegistrationNumbers_IN
)

GO
PRINT N'Finished creating view [DBO].[TaxRegistrationNumbers_IN]'
GO
-- End creating view [DBO].[TaxRegistrationNumbers_IN]



-- Creating stored procedure [dbo].[BATCH_HISTORY]
PRINT N'Creating stored procedure [dbo].[BATCH_HISTORY]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[dbo].[BATCH_HISTORY]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [dbo].[BATCH_HISTORY] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [dbo].[BATCH_HISTORY].';
END
GO

ALTER PROCEDURE [dbo].[BATCH_HISTORY]
    @BATCHID INT,
    @POSID NVARCHAR(10),
    @TRANSACTIONID NVARCHAR(10),
    @MESSAGE NVARCHAR(100),
    @LATESTBATCHID INT,
    @FLOWID INT,
    @MESSAGEDATE DATETIME,
    @DATAAREAID NVARCHAR(4)
AS
BEGIN
    DECLARE @NEXTID INT
    SELECT @NEXTID = ID FROM POSISREPLICATORHISTORY WHERE DATAAREAID = @DATAAREAID

    IF @NEXTID IS NULL
    SELECT @NEXTID = 0

    SELECT @NEXTID = @NEXTID + 1

    INSERT INTO POSISREPLICATORHISTORY
    (
        ID,
        BATCHID,
        POSID,
        TRANSACTIONID,
        MESSAGE,
        LATESTBATCHID,
        FLOWID,
        MESSAGEDATE,
        DATAAREAID
    )
    VALUES
    (
        @NEXTID,
        @BATCHID,
        @POSID,
        @TRANSACTIONID,
        @MESSAGE,
        @LATESTBATCHID,
        @FLOWID,
        @MESSAGEDATE,
        @DATAAREAID
    )
END;

GO
PRINT N'Finished creating stored procedure [dbo].[BATCH_HISTORY]'
GO
-- End creating stored procedure [dbo].[BATCH_HISTORY]



-- Creating stored procedure [dbo].[CASH_CALC]
PRINT N'Creating stored procedure [dbo].[CASH_CALC]';
SET QUOTED_IDENTIFIER ON;

GO
IF OBJECT_ID(N'[dbo].[CASH_CALC]', N'P') IS NULL
BEGIN
    EXEC ('CREATE PROC [dbo].[CASH_CALC] AS RAISERROR(''Empty Stored Procedure!!'', 16, 1) WITH SETERROR');
    IF (@@ERROR != 0)
        PRINT N'FAILED to create procedure [dbo].[CASH_CALC].';
END
GO

ALTER PROCEDURE [dbo].[CASH_CALC]
    @TERMINAL NVARCHAR(10)
AS
BEGIN
    SELECT
        TA.TRANSACTIONID,
        TA.STORE,
        TERMINAL,
        TERMINALID,
        TA.REPLICATIONCOUNTERFROMORIGIN AS 'REPLICATIONCOUNTER',
        TR.REPLICATIONCOUNTERFROMORIGIN AS 'REPLICATIONCOUNTER',
        TA.DATAAREAID
    FROM  ax.RETAILTRANSACTIONTABLE TA,  ax.RETAILTRANSACTIONSALESTRANS TR
    WHERE
        TA.TRANSACTIONID = TR.TRANSACTIONID
        AND TERMINAL = TERMINALID
        AND TR.DATAAREAID = TA.DATAAREAID
        AND TA.STORE = TR.STORE
        AND TERMINAL = @TERMINAL
END

GO
PRINT N'Finished creating stored procedure [dbo].[CASH_CALC]'
GO
-- End creating stored procedure [dbo].[CASH_CALC]



-- Creating stored procedure GetAddressFormatting
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetAddressFormatting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Returns only active field (INACTIVE == 0) with proper formatting metadata
CREATE PROCEDURE [dbo].[GetAddressFormatting]
@CountryRegionId NVARCHAR(10)
AS
BEGIN

SET NOCOUNT ON

SELECT   LAFL.ELEMENT, CAST(LAFL.LINENUM AS INT) AS LINEINDEX, LAFL.DATAENTRYONLY
FROM DBO.LOGISTICSADDRESSCOUNTRYREGION LACR
INNER JOIN DBO.LOGISTICSADDRESSFORMATHEADING LAFH ON LACR.ADDRFORMAT = LAFH.ADDRFORMAT
INNER JOIN DBO.LOGISTICSADDRESSFORMATLINES LAFL ON LAFH.ADDRFORMAT = LAFL.ADDRFORMAT
WHERE  LAFL.INACTIVE = 0 AND LACR.COUNTRYREGIONID = @CountryRegionId
ORDER BY LINEINDEX ASC
END
'
END
GO

-- Creating stored procedure GetCities
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCities]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetCities]
@CountryRegionId NVARCHAR(10),
@StateProvinceID NVARCHAR(10) = NULL,
@CountyId        NVARCHAR(10) = NULL
AS
BEGIN

SET NOCOUNT ON

SELECT LCITY.NAME AS CITYNAME, LCITY.DESCRIPTION, LCITY.COUNTYID, LCITY.COUNTRYREGIONID, LCITY.STATEID
FROM DBO.LOGISTICSADDRESSSCITY LCITY
WHERE LCITY.COUNTRYREGIONID = @CountryRegionId
AND (@StateProvinceID IS NULL OR LCITY.STATEID = @StateProvinceID)
AND (@CountyId IS NULL OR LCITY.COUNTYID = @CountyId)

END
'
END
GO

-- Creating stored procedure GetCounties
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCounties]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetCounties]
@CountryRegionId NVARCHAR(10),
@StateProvinceID NVARCHAR(10) = NULL
AS
BEGIN

SET NOCOUNT ON

SELECT LCNTY.COUNTYID, LCNTY.NAME, LCNTY.COUNTYCODE_SP, LCNTY.COUNTRYREGIONID, LCNTY.STATEID
FROM DBO.LOGISTICSADDRESSCOUNTY LCNTY
WHERE LCNTY.COUNTRYREGIONID = @CountryRegionId
AND (@STATEPROVINCEID IS NULL OR LCNTY.STATEID = @STATEPROVINCEID)

END
'
END
GO

-- Creating stored procedure GetCountryRegions
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCountryRegions]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetCountryRegions]
@LANGUAGEID NVARCHAR(10)
AS
BEGIN

SET NOCOUNT ON

SELECT LCNTRY.COUNTRYREGIONID, LCNTRY.ISOCODE, LCNTRY.TIMEZONE, LTRANS.SHORTNAME, LTRANS.LONGNAME, LTRANS.LANGUAGEID
FROM DBO.LOGISTICSADDRESSCOUNTRYREGION LCNTRY
INNER JOIN DBO.LOGISTICSADDRESSCOUNTRYREGIONTRANSLATION LTRANS ON LTRANS.COUNTRYREGIONID = LCNTRY.COUNTRYREGIONID
WHERE (LTRANS.LANGUAGEID = @LANGUAGEID OR @LANGUAGEID IS NULL)


END
'
END
GO

-- Creating stored procedure GETDBSIZES
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETDBSIZES]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GETDBSIZES]
AS
DECLARE @DATABASE NVARCHAR(50)
, @GETDB CURSOR
, @SQLSTMT NVARCHAR(4000)

CREATE TABLE #RESULT (DBNAME NVARCHAR(100),DBSIZE DECIMAL(18,2))

SET @GETDB = CURSOR FOR SELECT NAME FROM SYS.DATABASES
OPEN @GETDB
FETCH NEXT FROM @GETDB INTO @DATABASE

WHILE (@@FETCH_STATUS = 0)
BEGIN

SELECT @SQLSTMT = ''INSERT INTO #RESULT(DBNAME,DBSIZE)
SELECT '''''' + @DATABASE + '''''',CONVERT(DECIMAL(18,2),(SIZE*8)/1048576.0)
FROM '' + @DATABASE + ''.SYS.SYSFILES WHERE GROUPID=1''
EXEC (@SQLSTMT)

FETCH NEXT FROM @GETDB INTO @DATABASE
END

CLOSE @GETDB
DEALLOCATE @GETDB

INSERT INTO DBCAPACITY(DBNAME,SIZEINGB)
SELECT DBNAME,DBSIZE FROM #RESULT

DROP TABLE #RESULT
'
END
GO

-- Creating stored procedure GetDistricts
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDistricts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetDistricts]
@CountryRegionId NVARCHAR(10),
@StateProvinceID NVARCHAR(10) = NULL,
@CountyId        NVARCHAR(10) = NULL,
@City            NVARCHAR(60) = NULL
AS
BEGIN

SET NOCOUNT ON

SELECT LDIST.NAME AS DISTRICTNAME, LDIST.DESCRIPTION, LCITY.NAME AS CITYNAME, LCITY.COUNTYID, LCITY.STATEID, LCITY.COUNTRYREGIONID
FROM dbo.LOGISTICSADDRESSDISTRICT LDIST INNER JOIN dbo.LOGISTICSADDRESSSCITY LCITY ON LDIST.CITY = LCITY.RECID
WHERE LCITY.COUNTRYREGIONID = @CountryRegionId
AND (@StateProvinceID IS NULL OR LCITY.STATEID = @StateProvinceID)
AND (@CountyId IS NULL OR LCITY.COUNTYID = @CountyId)
AND (@City IS NULL OR LCITY.NAME = @City)

END
'
END
GO

-- Creating stored procedure GetFromZipCode
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetFromZipCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetFromZipCode]
@CountryRegionId NVARCHAR(10),
@ZipCode NVARCHAR(10)
AS
BEGIN

SET NOCOUNT ON

SELECT LZIP.ZIPCODE, LZIP.STREETNAME, LZIP.TIMEZONE, LZIP.CITY AS CITYNAME, LZIP.CITYALIAS, LZIP.COUNTY AS COUNTYID, LZIP.DISTRICTNAME, LZIP.STATE AS STATEID, LZIP.COUNTRYREGIONID
FROM DBO.LOGISTICSADDRESSZIPCODE LZIP
WHERE LZIP.COUNTRYREGIONID = @CountryRegionId
AND LZIP.ZIPCODE = @ZipCode

END
'
END
GO

-- Creating stored procedure GetStateProvinces
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetStateProvinces]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetStateProvinces]
@CountryRegionId NVARCHAR(10)
AS
BEGIN

SET NOCOUNT ON

SELECT LCNTRY.COUNTRYREGIONID, LSTATE.STATEID, LSTATE.NAME AS STATENAME, LSTATE.INTRASTATCODE
FROM DBO.LOGISTICSADDRESSSTATE LSTATE
INNER JOIN DBO.LOGISTICSADDRESSCOUNTRYREGION LCNTRY ON LSTATE.COUNTRYREGIONID = LCNTRY.COUNTRYREGIONID
WHERE LSTATE.COUNTRYREGIONID = @CountryRegionId

END
'
END
GO

-- Creating stored procedure GETTAXREGIME
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETTAXREGIME]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GETTAXREGIME]
@COUNTRYREGIONID NVARCHAR(10),
@STATEID NVARCHAR(10) = NULL,
@COUNTYID NVARCHAR(10)        = NULL,
@CITY NVARCHAR(60)            = NULL,
@DISTRICT NVARCHAR(60)        = NULL,
@ZIPCODE NVARCHAR(10)   = NULL
AS
BEGIN
SET NOCOUNT ON

-- CountryId is mandatory
IF (@COUNTRYREGIONID IS NULL)
BEGIN
RAISERROR (N''COUNTRY/REGIONID MANDATORY'', 16, 1)
RETURN;
END

-- For Optional Columns, there is three possible state we can run into
-- 1) a value is passed in (like @STATEPROVINCEID = ''WA'' )--> For this case, only match is possible when @STATEPROVINCEID = STATEPROVINCEID
-- 2) a value is NOT passed in (like @STATEPROVINCEID = NULL )--> For this case, we do have two sub-cases
-- 2a) @STATEPROVINCEID = NULL and STATEPROVINCEID is also NULL --> This is a match
-- 2b) @STATEPROVINCEID = NULL but STATEPROVINCEID != NULL, i.e. has a value in it --> This is no match. The data in the table is more complete than what it is passed in
SELECT * FROM DBO.RETAILTAXFILTERS RTF
WHERE
COUNTRYREGIONID   = @COUNTRYREGIONID
AND (STATEID         = @STATEID OR (@STATEID IS NULL AND STATEID IS NULL))
AND (COUNTYID        = @COUNTYID OR (@COUNTYID IS NULL AND COUNTYID IS NULL))
AND (CITY            = @CITY OR (@CITY IS NULL AND CITY IS NULL))
AND (DISTRICT        = @DISTRICT OR (@DISTRICT IS NULL AND DISTRICT IS NULL))
AND (ZIPCODE         = @ZIPCODE OR (@ZIPCODE IS NULL AND ZIPCODE IS NULL))
END
'
END
GO

-- Creating stored procedure GetZipCodes
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetZipCodes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetZipCodes]
@CountryRegionId NVARCHAR(10),
@StateProvinceID NVARCHAR(10) = NULL,
@CountyId        NVARCHAR(10) = NULL,
@City            NVARCHAR(60) = NULL,
@District        NVARCHAR(60) = NULL
AS
BEGIN

SET NOCOUNT ON

SELECT LZIP.ZIPCODE, LZIP.STREETNAME, LZIP.TIMEZONE, LZIP.CITY AS CITYNAME, LZIP.CITYALIAS, LZIP.COUNTY AS COUNTYID, LZIP.DISTRICTNAME, LZIP.STATE AS STATEID, LZIP.COUNTRYREGIONID
FROM DBO.LOGISTICSADDRESSZIPCODE LZIP
WHERE LZIP.COUNTRYREGIONID = @CountryRegionId
AND (@StateProvinceID IS NULL OR LZIP.STATE = @StateProvinceID)
AND (@CountyId IS NULL OR LZIP.COUNTY = @CountyId)
AND (@City IS NULL OR LZIP.CITY = @City)
AND (@District IS NULL OR LZIP.DISTRICTNAME = @District)

END
'
END
GO


-- Creating stored procedure POSCONTROLLER_LOGINSERT
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSCONTROLLER_LOGINSERT]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'

CREATE PROCEDURE [dbo].[POSCONTROLLER_LOGINSERT]
(
    @DATE DATETIME,
    @CODEUNIT NVARCHAR(100),
    @LOGSTRING NVARCHAR(1000),
    @LOGLEVEL INT,
    @STOREID NVARCHAR(10),
    @DURATIONINMILLISEC INT,
    @DATAAREAID NVARCHAR(4)
)

AS

INSERT INTO dbo.RETAILLOG
(
    LOGDATE,
    CODEUNIT,
    LOGSTRING,
    LOGLEVEL,
    STOREID,
    DURATIONINMILLISEC,
    DATAAREAID
)
VALUES
(
    @DATE,
    @CODEUNIT,
    @LOGSTRING,
    @LOGLEVEL,
    @STOREID,
    @DURATIONINMILLISEC,
    @DATAAREAID
)


/* SET NOCOUNT ON */
RETURN
'
END
GO

-- Creating stored procedure POSIS_GETERRORMESSAGEID
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSIS_GETERRORMESSAGEID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[POSIS_GETERRORMESSAGEID]

(
@ERRORID INT
)

AS
SELECT [ERRORMESSAGEID] FROM RETAILERRORS WHERE ERRORID = @ERRORID
'
END
GO

-- Creating stored procedure POSIS_GETSUSPENDEDCOUNTER
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSIS_GETSUSPENDEDCOUNTER]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[POSIS_GETSUSPENDEDCOUNTER]
(
@STOREID NVARCHAR(10),
@DATAAREAID NVARCHAR(4))
AS
SELECT COUNT(SUSPENDEDTRANSACTIONID) AS SUSPENDEDCOUNT
FROM dbo.RETAILSUSPENDEDTRANSACTIONS
WHERE STOREID = @STOREID AND DATAAREAID = @DATAAREAID
'
END
GO

-- Creating stored procedure POSIS_GETTRANSLATION
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSIS_GETTRANSLATION]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[POSIS_GETTRANSLATION]
(
@LANGUAGEID NVARCHAR(7),
@TEXTID INT)
AS
SELECT [TEXT]
FROM RETAILLANGUAGETEXT
WHERE LANGUAGEID = @LANGUAGEID
AND TEXTID = @TEXTID

IF @@ROWCOUNT = 0
BEGIN
DECLARE @NEW_LANGUAGEID NVARCHAR(7)
SET @NEW_LANGUAGEID = @LANGUAGEID + ''%''

SELECT TOP 1 [TEXT]
FROM RETAILLANGUAGETEXT
WHERE LANGUAGEID LIKE @NEW_LANGUAGEID
AND TEXTID = @TEXTID

IF @@ROWCOUNT = 0
BEGIN
SELECT [TEXT]
FROM RETAILLANGUAGETEXT
WHERE LANGUAGEID = ''EN-US''
AND TEXTID = @TEXTID
END
END
'
END
GO

-- Creating stored procedure POSIS_LOGINSERT
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[POSIS_LOGINSERT]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[POSIS_LOGINSERT]
(
    @RETAILLOGID BIGINT,
    @DATE DATETIME,
    @CODEUNIT NVARCHAR(100),
    @LOGSTRING NTEXT,
    @LOGLEVEL INT,
    @STOREID NVARCHAR(10),
    @TERMINALID NVARCHAR(10),
    @DURATIONINMILLISEC INT,
    @DATAAREAID NVARCHAR(4)
)
AS
INSERT INTO [dbo].[RETAILLOG]
(
    RETAILLOGID,
    LOGDATE,
    CODEUNIT,
    LOGSTRING,
    LOGLEVEL,
    STOREID,
    TERMINALID,
    DURATIONINMILLISEC,
    DATAAREAID
)
VALUES
(
    @RETAILLOGID,
    @DATE,
    @CODEUNIT,
    @LOGSTRING,
    @LOGLEVEL,
    @STOREID,
    @TERMINALID,
    @DURATIONINMILLISEC,
    @DATAAREAID
)

/* SET NOCOUNT ON */
RETURN
'
END
GO


-- Creating stored procedure TENDERREPORT
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TENDERREPORT]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- AUTHOR:      <AUTHOR,,NAME>
-- CREATE DATE: <CREATE DATE,,>
-- DESCRIPTION: <DESCRIPTION,,>
-- =============================================
CREATE PROCEDURE [dbo].[TENDERREPORT]
@DATEFROM NVARCHAR(10), @DATETO NVARCHAR(10)
AS
BEGIN
-- SET NOCOUNT ON ADDED TO PREVENT EXTRA RESULT SETS FROM
-- INTERFERING WITH SELECT STATEMENTS.
SET NOCOUNT ON;
SELECT * FROM RETAILSTAFFTABLE

END
'
END
GO


-- Creating stored procedure VALIDATEADDRESS
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VALIDATEADDRESS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[VALIDATEADDRESS]
@COUNTRYREGIONID NVARCHAR(10),
@STATEPROVINCEID NVARCHAR(10) = NULL,
@COUNTYID NVARCHAR(10)        = NULL,
@CITY NVARCHAR(60)            = NULL,
@DISTRICT NVARCHAR(60)        = NULL,
@ZIPPOSTALCODE NVARCHAR(10)   = NULL
AS
BEGIN
SET NOCOUNT ON


DECLARE @i_ReturnCode               INT;
DECLARE @i_TransactionIsOurs        INT;
DECLARE @i_Error                    INT;

-- CountryId is mandatory according to Ax schema
IF (@COUNTRYREGIONID IS NULL)
BEGIN
SET @i_ReturnCode           = 1 ; -- invalid countryid
GOTO exit_label;
END

IF NOT EXISTS(SELECT 1 FROM DBO.LOGISTICSADDRESSCOUNTRYREGION LCNTRY WHERE LCNTRY.COUNTRYREGIONID = @COUNTRYREGIONID)
BEGIN
SET @i_ReturnCode           = 1 ; -- invalid country
GOTO exit_label;
END

-- Validate State, if exists
IF (@STATEPROVINCEID IS NOT NULL)
BEGIN
IF NOT EXISTS(SELECT 1 FROM DBO.LOGISTICSADDRESSSTATE LSTATE WHERE LSTATE.STATEID = @STATEPROVINCEID AND LSTATE.COUNTRYREGIONID = @COUNTRYREGIONID)
BEGIN
SET @i_ReturnCode           = 2 ; -- invalid stateid
GOTO exit_label;
END
END

-- Validate County, if exists
IF (@COUNTYID IS NOT NULL)
BEGIN
IF NOT EXISTS(SELECT 1 FROM DBO.LOGISTICSADDRESSCOUNTY LCNTY WHERE LCNTY.COUNTYID = @COUNTYID
AND LCNTY.COUNTRYREGIONID = @COUNTRYREGIONID
AND ( @STATEPROVINCEID IS NULL OR LCNTY.STATEID = @STATEPROVINCEID ))
BEGIN
SET @i_ReturnCode           = 3 ; -- invalid countyid
GOTO exit_label;
END
END

-- Validate City, if exists
IF (@CITY IS NOT NULL)
BEGIN
IF NOT EXISTS(SELECT 1 FROM DBO.LOGISTICSADDRESSSCITY LCITY
INNER JOIN DBO.LOGISTICSADDRESSCOUNTRYREGION LCNTRY ON LCNTRY.COUNTRYREGIONID = LCITY.COUNTRYREGIONID
WHERE LCITY.NAME = @CITY
AND LCITY.COUNTRYREGIONID = LCNTRY.COUNTRYREGIONID
AND ( @STATEPROVINCEID IS NULL OR LCITY.STATEID = @STATEPROVINCEID)
AND ( @COUNTYID IS NULL OR LCITY.COUNTYID = @COUNTYID))
BEGIN
SET @i_ReturnCode           = 4 ; -- invalid city
GOTO exit_label;
END
END

-- Validate District, if exists
IF (@DISTRICT IS NOT NULL)
BEGIN
IF NOT EXISTS(SELECT 1 FROM DBO.LOGISTICSADDRESSDISTRICT LDIST
LEFT OUTER JOIN DBO.LOGISTICSADDRESSSCITY LCITY ON LCITY.RECID = LDIST.CITY
WHERE LDIST.NAME = @DISTRICT
AND ( @CITY IS NULL OR LCITY.NAME = @CITY )
AND ( @COUNTYID IS NULL OR LCITY.COUNTYID = @COUNTYID)
AND ( @STATEPROVINCEID IS NULL OR LCITY.STATEID = @STATEPROVINCEID)
AND ( LCITY.COUNTRYREGIONID  = @COUNTRYREGIONID ))
BEGIN
SET @i_ReturnCode           = 5 ; -- invalid district
GOTO exit_label;
END
END


-- Validate ZipCode, if exists
IF (@ZIPPOSTALCODE IS NOT NULL)
BEGIN
IF NOT EXISTS(SELECT 1 FROM DBO.LOGISTICSADDRESSZIPCODE LZIP
WHERE LZIP.ZIPCODE = @ZIPPOSTALCODE
AND LZIP.COUNTRYREGIONID = @COUNTRYREGIONID
AND ( @STATEPROVINCEID IS NULL OR LZIP.STATE = @STATEPROVINCEID)
AND ( @COUNTYID IS NULL OR LZIP.COUNTY = @COUNTYID)
AND ( @CITY IS NULL OR LZIP.CITY  = @CITY)
AND ( @DISTRICT IS NULL OR LZIP.DISTRICTNAME = @DISTRICT))
BEGIN
SET @i_ReturnCode           = 6 ; -- invalid zipcode
GOTO exit_label;
END
END

SET @i_ReturnCode = 0;

exit_label:

RETURN @i_ReturnCode;
END
'
END
GO

-- Creating stored procedure CUSTOMERSEARCH
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CUSTOMERSEARCH]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CUSTOMERSEARCH]
GO
CREATE PROCEDURE [dbo].[CUSTOMERSEARCH]
(
    @SEARCHVALUE    NVARCHAR(50),
    @ORDERBY        NVARCHAR(50),
    @STORERECID     BIGINT,
    @ASCENDING      BIT             = 1,
    @SKIP           INT             = 0,
    @TOP            INT             = 200,
    @SEARCHACROSSCOMPANY BIT        = 1
)
AS
BEGIN

    DECLARE @PARTYIDS TABLE (PARTY BIGINT)
    DECLARE @UNIQUEPARTYIDS TABLE (PARTY BIGINT)
    DECLARE @tvp_QueryResultSettings [crt].[QUERYRESULTSETTINGSTYPE];
    DECLARE @RC INT;
    DECLARE @nvc_DataAreaId nvarchar(4);

    SET NOCOUNT ON

    INSERT INTO @tvp_QueryResultSettings ([SKIP], [TOP], [ORDERBY], [ASCENDING])
    VALUES  (@SKIP, @TOP, @ORDERBY, @ASCENDING);

    SELECT @nvc_DataAreaId = [INVENTLOCATIONDATAAREAID]
    FROM ax.RETAILCHANNELTABLE
    WHERE RECID = @STORERECID;

    EXECUTE @RC = [crt].[CUSTOMERSEARCH] @tvp_QueryResultSettings, @SEARCHVALUE, @SEARCHACROSSCOMPANY, @STORERECID, @nvc_DataAreaId

    SET NOCOUNT OFF
    RETURN
END
GO

-- Creating stored procedure PRODUCTSEARCH
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPRODUCTSBYSEARCHNAME]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETPRODUCTSBYSEARCHNAME]
GO
CREATE PROCEDURE [dbo].[GETPRODUCTSBYSEARCHNAME]
    @SEARCHVALUE    NVARCHAR(50)
AS
BEGIN
    DECLARE @FULLTEXTENABLED INT = COLUMNPROPERTY(OBJECT_ID('ax.ECORESPRODUCT'), 'SEARCHNAME', 'IsFulltextIndexed')

    IF (@FULLTEXTENABLED = 1)
    BEGIN
        SET @SEARCHVALUE = '"' + @SEARCHVALUE + '*"';
        SELECT PR.RECID AS PRODUCT
         FROM  ax.ECORESPRODUCT PR
         WHERE CONTAINS(SEARCHNAME, @SEARCHVALUE);
    END
    ELSE
    BEGIN
        SET @SEARCHVALUE = '%' + @SEARCHVALUE + '%';
        SELECT PR.RECID AS PRODUCT
         FROM  ax.ECORESPRODUCT PR
         WHERE SEARCHNAME LIKE @SEARCHVALUE
    END

    RETURN
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPRODUCTSBYNAME]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETPRODUCTSBYNAME]
GO
CREATE PROCEDURE [dbo].[GETPRODUCTSBYNAME]
    @SEARCHVALUE    NVARCHAR(50),
    @CULTUREID      NVARCHAR(7)
AS
BEGIN
    DECLARE @FULLTEXTENABLED INT = COLUMNPROPERTY(OBJECT_ID('ax.ECORESPRODUCTTRANSLATION'), 'NAME', 'IsFulltextIndexed')

    IF (@FULLTEXTENABLED = 1)
    BEGIN
        SET @SEARCHVALUE = '"' + @SEARCHVALUE + '*"'
        SELECT PRODUCT
         FROM ax.ECORESPRODUCT PR
         JOIN ax.ECORESPRODUCTTRANSLATION AS TR ON PR.RECID = TR.PRODUCT AND TR.LANGUAGEID = @CULTUREID
        WHERE CONTAINS(TR.NAME, @SEARCHVALUE)
    END
    ELSE
    BEGIN
        SET @SEARCHVALUE =  '%' + @SEARCHVALUE + '%'
        SELECT PRODUCT
         FROM ax.ECORESPRODUCT PR
         JOIN ax.ECORESPRODUCTTRANSLATION AS TR ON PR.RECID = TR.PRODUCT AND TR.LANGUAGEID = @CULTUREID
        WHERE TR.NAME LIKE @SEARCHVALUE;
    END

    RETURN
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPRODUCTSBYITEMID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETPRODUCTSBYITEMID]
GO
CREATE PROCEDURE [dbo].[GETPRODUCTSBYITEMID]
    @SEARCHVALUE    NVARCHAR(50)
AS
BEGIN
    DECLARE @FULLTEXTENABLED INT = COLUMNPROPERTY(OBJECT_ID('ax.INVENTTABLE'), 'ITEMID ', 'IsFulltextIndexed')

    IF (@FULLTEXTENABLED = 1)
    BEGIN
        SET @SEARCHVALUE =  '"' + @SEARCHVALUE + '*"';
        SELECT IT.PRODUCT AS PRODUCT
         FROM ax.INVENTTABLE IT
         WHERE CONTAINS(ITEMID , @SEARCHVALUE);
    END
    ELSE
    BEGIN
        SET @SEARCHVALUE =  @SEARCHVALUE + '%';
        SELECT IT.PRODUCT AS PRODUCT
         FROM ax.INVENTTABLE IT
         WHERE ITEMID LIKE @SEARCHVALUE;
    END

    RETURN
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PRODUCTSEARCH]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PRODUCTSEARCH]
GO
CREATE PROCEDURE [dbo].[PRODUCTSEARCH]
(
    @SEARCHVALUE        NVARCHAR(50),
    @ORDERBY            NVARCHAR(50),
    @CULTUREID          NVARCHAR(7),
    @STORERECID         BIGINT,
    @ASCENDING          BIT             = 1,
    @FROMROW            INT             = 0,
    @PAGESIZE           INT             = 200
)
AS
BEGIN

    DECLARE @PRODUCTS TABLE (PRODUCT BIGINT)
    DECLARE @UNIQUEPRODUCTS TABLE (PRODUCT BIGINT)

    SET NOCOUNT ON

    INSERT @PRODUCTS
    Exec GETPRODUCTSBYITEMID @SEARCHVALUE

    INSERT @PRODUCTS
    Exec GETPRODUCTSBYSEARCHNAME @SEARCHVALUE

    INSERT @PRODUCTS
    Exec GETPRODUCTSBYNAME @SEARCHVALUE, @CULTUREID

    INSERT @UNIQUEPRODUCTS
    SELECT DISTINCT PRODUCTS.PRODUCT
    FROM
        @PRODUCTS AS PRODUCTS

    IF (@ASCENDING = 1)
    BEGIN
        SELECT
            ITEMID, ITEMNAME, '' AS ITEMPRICE, I.UNITOFMEASURE, I.INVENTPRODUCTTYPE_BR, ROWNUMBER
        FROM
            (
                SELECT ROW_NUMBER() OVER(ORDER BY
                                            CASE
                                                WHEN @ORDERBY='ITEMID' THEN IT.ITEMID
                                                ELSE IT.ITEMNAME
                                            END
                                            ASC) AS ROWNUMBER
                    ,IT.INVENTPRODUCTTYPE_BR, IT.ITEMID, COALESCE(TR.NAME, IT.ITEMID) AS ITEMNAME, ISNULL(IM.UNITID, '') AS UNITOFMEASURE
                FROM
                    (SELECT DISTINCT PRODUCTID, CHANNELID from crt.ASSORTEDPRODUCTSVIEW) as apv
                JOIN INVENTTABLE IT
                    ON apv.PRODUCTID = IT.PRODUCT
                JOIN INVENTTABLEMODULE IM
                    ON IT.ITEMID = IM.ITEMID AND IM.MODULETYPE = 2
                JOIN @UNIQUEPRODUCTS UP
                    ON UP.PRODUCT = IT.PRODUCT
                LEFT JOIN ECORESPRODUCTTRANSLATION AS TR
                    ON IT.PRODUCT = TR.PRODUCT AND TR.LANGUAGEID = @CULTUREID
                WHERE APV.CHANNELID = @STORERECID
            ) AS I
        WHERE ROWNUMBER BETWEEN @FROMROW AND (@FROMROW + @PAGESIZE - 1)
    END
    ELSE
    BEGIN
        SELECT
            ITEMID, ITEMNAME, '' AS ITEMPRICE, I.UNITOFMEASURE, I.INVENTPRODUCTTYPE_BR, ROWNUMBER
        FROM
            (
                SELECT ROW_NUMBER() OVER(ORDER BY
                                            CASE
                                                WHEN @ORDERBY='ITEMID' THEN IT.ITEMID
                                                ELSE IT.ITEMNAME
                                            END
                                            DESC) AS ROWNUMBER
                    ,IT.INVENTPRODUCTTYPE_BR, IT.ITEMID, COALESCE(TR.NAME, IT.ITEMID) AS ITEMNAME, ISNULL(IM.UNITID, '') AS UNITOFMEASURE
                FROM
                    (SELECT DISTINCT PRODUCTID, CHANNELID from crt.ASSORTEDPRODUCTSVIEW) as apv
                JOIN INVENTTABLE IT
                    ON apv.PRODUCTID = IT.PRODUCT
                JOIN INVENTTABLEMODULE IM
                    ON IT.ITEMID = IM.ITEMID AND IM.MODULETYPE = 2
                JOIN @UNIQUEPRODUCTS UP
                    ON UP.PRODUCT = IT.PRODUCT
                LEFT JOIN ECORESPRODUCTTRANSLATION AS TR
                    ON IT.PRODUCT = TR.PRODUCT AND TR.LANGUAGEID = @CULTUREID
                WHERE APV.CHANNELID = @STORERECID
            ) AS I
        WHERE ROWNUMBER BETWEEN @FROMROW AND (@FROMROW + @PAGESIZE - 1)
    END

    RETURN
END
GO

-- Creating stored procedure SMARTSEARCH
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SMARTSEARCH]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SMARTSEARCH]
GO
CREATE PROCEDURE [dbo].[SMARTSEARCH]
(
    @SEARCHVALUE            NVARCHAR(50),
    @ORDERBY                NVARCHAR(50),
    @CULTUREID              NVARCHAR(7),
    @STORERECID             BIGINT,
    @STOREDATE              DATETIME,
    @DATAAREAID             NVARCHAR(4),
    @CATEGORYHIERARCHY      BIGINT,
    @SEARCHTYPE             INT,
    @ITEMTYPE               INT,
    @CUSTOMERTYPE           INT,
    @CATEGORYTYPE           INT,
    @ASCENDING              BIT         = 1,
    @FROMROW                INT         = 0,
    @PAGESIZE               INT         = 200
)
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @IncludeItems INT
    DECLARE @includeCustomers INT
    DECLARE @IncludeCategories INT

    IF (@SEARCHTYPE <> @CUSTOMERTYPE AND @SEARCHTYPE <> @CATEGORYTYPE)
        SET @IncludeItems = 1

    IF (@SEARCHTYPE <> @ITEMTYPE AND @SEARCHTYPE <> @CATEGORYTYPE)
        SET @includeCustomers = 1

    IF (@SEARCHTYPE <> @ITEMTYPE AND @SEARCHTYPE <> @CUSTOMERTYPE)
        SET @IncludeCategories = 1

    IF (@IncludeItems = 1)
    BEGIN
        DECLARE @PRODUCTS TABLE (PRODUCT BIGINT)
        DECLARE @UNIQUEPRODUCTS TABLE (PRODUCT BIGINT)

        INSERT @PRODUCTS
        Exec GETPRODUCTSBYITEMID @SEARCHVALUE

        INSERT @PRODUCTS
        Exec GETPRODUCTSBYSEARCHNAME @SEARCHVALUE

        INSERT @PRODUCTS
        Exec GETPRODUCTSBYNAME @SEARCHVALUE, @CULTUREID

        INSERT @UNIQUEPRODUCTS
        SELECT DISTINCT PRODUCTS.PRODUCT
        FROM
            @PRODUCTS AS PRODUCTS
    END

    IF (@includeCustomers = 1)
    BEGIN
        DECLARE @PARTYIDS TABLE (PARTY BIGINT)
        DECLARE @UNIQUEPARTYIDS TABLE (PARTY BIGINT)

        INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYCUSTOMER @SEARCHVALUE

        INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYCONTACT @SEARCHVALUE

        INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYADDRESS @SEARCHVALUE

        INSERT @PARTYIDS
        EXEC [crt].GETPARTYBYLOYALTYCARD @SEARCHVALUE

        INSERT INTO @UNIQUEPARTYIDS
        SELECT DISTINCT PARTY FROM @PARTYIDS;
    END

    SELECT
        NUMBER, NAME, TYPE, TAG
    FROM
        (
            SELECT *, ROW_NUMBER() OVER(ORDER BY
                                            CASE
                                                WHEN @ORDERBY='NUMBER' THEN NUMBER
                                                ELSE NAME
                                            END
                                            ASC) AS ROWNUMBER
            FROM
                (
                    SELECT
                        DISTINCT IT.ITEMID AS NUMBER, COALESCE(TR.NAME, IT.ITEMNAME, IT.ITEMID) AS NAME, @ITEMTYPE AS TYPE, ISNULL(IM.UNITID, '') AS TAG
                    FROM
                        [dbo].GETASSORTEDPRODUCTS(@STORERECID, @STOREDATE) AP
                    JOIN INVENTTABLE IT ON IT.ITEMID = AP.ITEMID AND IT.DATAAREAID = @DATAAREAID
                    JOIN INVENTTABLEMODULE IM
                        ON IT.ITEMID = IM.ITEMID AND IM.MODULETYPE = 2 AND IM.DATAAREAID = @DATAAREAID
                    JOIN @UNIQUEPRODUCTS UP
                        ON UP.PRODUCT = IT.PRODUCT
                    LEFT JOIN ECORESPRODUCTTRANSLATION AS TR
                        ON UP.PRODUCT = TR.PRODUCT AND TR.LANGUAGEID = @CULTUREID
                    WHERE
                        @IncludeItems = 1

                    UNION ALL

                    SELECT ACCOUNTNUMBER As NUMBER
                          ,[NAME]
                          ,@CUSTOMERTYPE AS TYPE
                          ,PARTYNUMBER AS TAG
                    FROM [crt].GLOBALCUSTOMERSVIEW gcv
                    INNER JOIN @UNIQUEPARTYIDS pid ON gcv.RECORDID = pid.PARTY
                    WHERE
                        @includeCustomers = 1

                    UNION ALL

                    SELECT
                        CAST(C.RECID AS nvarchar) AS NUMBER, ISNULL(NAME, FRIENDLYNAME) AS NAME, @CATEGORYTYPE AS TYPE, '' AS TAG
                    FROM
                        ECORESCATEGORY C
                    LEFT JOIN ECORESCATEGORYTRANSLATION T
                        ON T.CATEGORY = C.RECID AND T.LANGUAGEID = @CULTUREID
                    WHERE
                        @IncludeCategories = 1 AND
                        ISACTIVE = 1 AND CATEGORYHIERARCHY = @CATEGORYHIERARCHY AND NAME LIKE '%' + @SEARCHVALUE + '%'
                ) UN
        ) RN
    WHERE ROWNUMBER BETWEEN @FROMROW AND (@FROMROW + @PAGESIZE - 1)

    SET NOCOUNT OFF
    RETURN
END
GO
-- Creating procedure GETCUSTOMERLOYALTYCARDS
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETCUSTOMERLOYALTYCARDS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].GETCUSTOMERLOYALTYCARDS
GO
CREATE PROCEDURE [dbo].GETCUSTOMERLOYALTYCARDS
    @PartyNumber NVARCHAR(255)
AS
BEGIN
    SELECT
    FROM [ax].[RETAILLOYALTYCARD] rlc
    JOIN [ax].[DIRPARTYTABLE] dpt ON dpt.RECID = rlc.PARTY
    WHERE dpt.PARTYNUMBER = @PartyNumber

END
GO
-- Creating procedure GetLoyaltyEarnSchemeLines
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetLoyaltyEarnSchemeLines]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetLoyaltyEarnSchemeLines]
GO
CREATE PROCEDURE [dbo].[GetLoyaltyEarnSchemeLines]
    @LoyaltyCardNumber  NVARCHAR(30),
    @StoreNumber        NVARCHAR(10),
    @ChannelLocalDate   DATE
AS
BEGIN
    DECLARE @ChannelId BIGINT

    SELECT @ChannelId = rst.RECID
    FROM [ax].[RETAILSTORETABLE] rst
    WHERE rst.STORENUMBER = @StoreNumber

    exec [crt].[GETLOYALTYEARNSCHEMELINES] @bi_ChannelId = @ChannelId, @dt_ChannelLocalDate = @ChannelLocalDate, @nvc_LoyaltyCardNumber = @LoyaltyCardNumber
END
GO
-- Creating procedure GetLoyaltyRedeemSchemeLines
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetLoyaltyRedeemSchemeLines]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetLoyaltyRedeemSchemeLines]
GO
CREATE PROCEDURE [dbo].[GetLoyaltyRedeemSchemeLines]
    @LoyaltyCardNumber      NVARCHAR(30),
    @StoreNumber            NVARCHAR(10),
    @ChannelLocalDate       DATE,
    @RewardPointRewardId    NVARCHAR(64)
AS
BEGIN
    DECLARE @ChannelId BIGINT

    SELECT @ChannelId = rst.RECID
    FROM [ax].[RETAILSTORETABLE] rst
    WHERE rst.STORENUMBER = @StoreNumber

    exec [crt].[GETLOYALTYREDEEMSCHEMELINES] @bi_ChannelId = @ChannelId, @dt_ChannelLocalDate = @ChannelLocalDate, @nvc_LoyaltyCardNumber = @LoyaltyCardNumber, @nvc_RewardPointRewardId = @RewardPointRewardId;
END
GO

-- Creating table function [dbo].[GETNEARBYSTORESFUNCTION]
PRINT N'Creating table function [dbo].[GETNEARBYSTORESFUNCTION]';

GO
IF OBJECT_ID(N'[dbo].[GETNEARBYSTORESFUNCTION]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [dbo].[GETNEARBYSTORESFUNCTION] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [dbo].[GETNEARBYSTORESFUNCTION].'
GO

ALTER FUNCTION GETNEARBYSTORESFUNCTION
(
    @CHANNELID              BIGINT,
    @LATITUDE               FLOAT,
    @LONGITUDE              FLOAT,
    @SEARCHDISTANCE         FLOAT,
    @UNITCONVERSION         FLOAT
)
RETURNS @GETNEARBYSTORESRESULT TABLE
(
    [DISTANCE] [FLOAT] NOT NULL,
    [STORENUMBER] [nvarchar](10) NOT NULL,
    [NAME] [nvarchar](100) NOT NULL,
    [CHANNELID] [bigint] NOT NULL,
    [INVENTLOCATION] [nvarchar](10) NOT NULL,
    [GEOLOCATION] [GEOGRAPHY] NOT NULL,
    [ADDRESS] [nvarchar](250) NOT NULL,
    [COUNTRYREGIONID] [nvarchar](10) NOT NULL,
    [ZIPCODE] [nvarchar](10) NOT NULL,
    [STATE] [nvarchar](10) NOT NULL,
    [COUNTY] [nvarchar](10) NOT NULL,
    [CITY] [nvarchar](60) NOT NULL,
    [STREET] [nvarchar](250) NOT NULL,
    [LATITUDE] [numeric](32, 16) NOT NULL,
    [LONGITUDE] [numeric](32, 16) NOT NULL,
    [STREETNUMBER] [nvarchar](20) NOT NULL,
    [BUILDINGCOMPLIMENT] [nvarchar](60) NOT NULL,
    [POSTBOX] [nvarchar](20) NOT NULL,
    [CITYRECID] [bigint] NOT NULL,
    [DISTRICT] [bigint] NOT NULL,
    [LOCATION] [bigint] NOT NULL,
    [ZIPCODERECID] [bigint] NOT NULL,
    [DISTRICTNAME] [nvarchar](60) NOT NULL,
    [MODIFIEDDATETIME] [datetime] NOT NULL,
    [RECID] [bigint] NOT NULL
)
AS
BEGIN
    INSERT @GETNEARBYSTORESRESULT
    SELECT
        [DISTANCE],
        [STORENUMBER],
        [NAME],
        [CHANNELID],
        [INVENTLOCATION],
        [GEOLOCATION],
        [ADDRESS],
        [COUNTRYREGIONID],
        [ZIPCODE],
        [STATE],
        [COUNTY],
        [CITY],
        [STREET],
        [LATITUDE],
        [LONGITUDE],
        [STREETNUMBER],
        [BUILDINGCOMPLIMENT],
        [POSTBOX],
        [CITYRECID],
        [DISTRICT],
        [LOCATION],
        [ZIPCODERECID],
        [DISTRICTNAME],
        [MODIFIEDDATETIME],
        [RECID]
    FROM crt.GETNEARBYSTORESFUNCTION(@CHANNELID, @LATITUDE, @LONGITUDE, @SEARCHDISTANCE, @UNITCONVERSION)
    RETURN
END

GO
PRINT N'Finished creating table function [dbo].[GETNEARBYSTORESFUNCTION]'
-- End creating table function [dbo].[GETNEARBYSTORESFUNCTION]


-- Creating stored procedure GETPARTYBYADDRESS
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPARTYBYADDRESS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETPARTYBYADDRESS]
GO
CREATE PROCEDURE [dbo].[GETPARTYBYADDRESS]
    @SEARCHVALUE    NVARCHAR(50)
AS
BEGIN
    DECLARE @FULLTEXTENABLED INT = COLUMNPROPERTY(OBJECT_ID('ax.LOGISTICSPOSTALADDRESS'), 'ADDRESS', 'IsFulltextIndexed')

    IF (@FULLTEXTENABLED = 1)
    BEGIN
        SET @SEARCHVALUE = '"' + @SEARCHVALUE + '*"';
        SELECT dpt.RECID AS PARTY
            FROM [ax].LOGISTICSPOSTALADDRESS lpa
            INNER JOIN [ax].DIRPARTYLOCATION dpl ON lpa.LOCATION = dpl.LOCATION
            INNER JOIN  [ax].DIRPARTYTABLE dpt ON dpl.PARTY = dpt.RECID
            WHERE GETUTCDATE() BETWEEN lpa.VALIDFROM AND lpa.VALIDTO
              AND CONTAINS(lpa.[ADDRESS], @SEARCHVALUE)
    END
    ELSE
    BEGIN
        SET @SEARCHVALUE =  '%' + @SEARCHVALUE + '%';
        SELECT dpt.RECID AS PARTY
            FROM [ax].LOGISTICSPOSTALADDRESS lpa
            INNER JOIN [ax].DIRPARTYLOCATION dpl ON lpa.LOCATION = dpl.LOCATION
            INNER JOIN  [ax].DIRPARTYTABLE dpt ON dpl.PARTY = dpt.RECID
            WHERE GETUTCDATE() BETWEEN lpa.VALIDFROM AND lpa.VALIDTO
              AND lpa.[ADDRESS] like @SEARCHVALUE
    END

    RETURN
END
GO

-- Creating stored procedure GETPARTYBYCONTACT
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPARTYBYCONTACT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETPARTYBYCONTACT]
GO
CREATE PROCEDURE [dbo].[GETPARTYBYCONTACT]
(
    @SEARCHVALUE    NVarChar(50)
)
AS
    SELECT T1.RECID AS PARTY
    FROM
        LOGISTICSELECTRONICADDRESS T3
        INNER JOIN  DIRPARTYLOCATION T2
            ON T3.LOCATION = T2.LOCATION
        INNER JOIN DIRPARTYTABLE T1
            ON T2.PARTY = T1.RECID
    WHERE
         T3.VALIDFROM <= GETUTCDATE() AND T3.VALIDTO >= GETUTCDATE()
         AND (T3.TYPE = 1 OR T3.TYPE = 2)
         AND T3.LOCATOR LIKE @SearchValue +'%'
GO

-- Creating procedure GETPARTYBYCUSTOMER
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPARTYBYCUSTOMER]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETPARTYBYCUSTOMER]
GO
CREATE PROCEDURE [dbo].[GETPARTYBYCUSTOMER]
     @SEARCHVALUE      NVARCHAR(50)
AS
BEGIN
    DECLARE @FULLTEXTENABLED INT = COLUMNPROPERTY(OBJECT_ID('ax.DIRPARTYTABLE'), 'NAME', 'IsFulltextIndexed');
    DECLARE @FULLTEXTSEARCHVALUE NVARCHAR(50) = '"' + @SEARCHVALUE + '*"';
    SET @SEARCHVALUE = @SEARCHVALUE + '%';
    DECLARE @SEARCHVALUEWITHPREFIXWILDCARD NVARCHAR(50) = '%' + @SEARCHVALUE;

    IF (@FULLTEXTENABLED = 1)
        BEGIN
            SELECT ct.PARTY
            FROM [ax].CUSTTABLE ct
            WHERE ct.ACCOUNTNUM LIKE @SEARCHVALUE
               OR ct.ORGID LIKE @SEARCHVALUE

            UNION ALL

            SELECT dpt.RECID
            FROM [ax].DIRPARTYTABLE dpt
            WHERE CONTAINS(dpt.NAME, @FULLTEXTSEARCHVALUE);
        END
    ELSE
        BEGIN
            SELECT ct.PARTY
            FROM [ax].CUSTTABLE ct
            WHERE ct.ACCOUNTNUM LIKE @SEARCHVALUE
               OR ct.ORGID LIKE @SEARCHVALUE

            UNION ALL

            SELECT dpt.RECID
            FROM [ax].DIRPARTYTABLE dpt
            WHERE dpt.NAME LIKE @SEARCHVALUEWITHPREFIXWILDCARD;
        END

    RETURN
END
GO

-- Creating stored procedure GETUNASSORTEDITEMSFORPURCHASEORDER
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETUNASSORTEDITEMSFORPURCHASEORDER]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETUNASSORTEDITEMSFORPURCHASEORDER]
GO
CREATE PROCEDURE [dbo].[GETUNASSORTEDITEMSFORPURCHASEORDER]
    @bi_ChannelId               BIGINT,
    @dt_ChannelDate             DATETIME,
    @nvc_DataAreaId             NVARCHAR(4),
    @nvc_purchaseOrderNumber    NVARCHAR(100),
    @nvc_ReceiptNumber          NVARCHAR(100),
    @int_ModuleType             INT
AS
BEGIN
    SET NOCOUNT ON
    SELECT DISTINCT(P1.ITEMNUMBER) FROM POSPURCHASEORDERRECEIPTLINE P1 WHERE NOT EXISTS
    (   SELECT DISTINCT AII.ITEMID FROM POSPURCHASEORDERRECEIPTLINE P2
        INNER JOIN [dbo].GETASSORTEDPRODUCTS(@bi_ChannelId, @dt_ChannelDate) AII ON P2.ITEMNUMBER = AII.ITEMID
        INNER JOIN INVENTTABLEMODULE ITM ON P2.ITEMNUMBER = ITM.ITEMID AND ITM.DATAAREAID = @nvc_DataAreaId
        WHERE AII.ITEMID = P1.ITEMNUMBER AND ITM.MODULETYPE = @int_ModuleType
        AND P2.PONUMBER = @nvc_purchaseOrderNumber AND P2.RECEIPTNUMBER = @nvc_ReceiptNumber
    )
    AND P1.PONUMBER = @nvc_purchaseOrderNumber AND P1.RECEIPTNUMBER = @nvc_ReceiptNumber
END

GO
PRINT N'Finished creating stored procedure [dbo].[GETUNASSORTEDITEMSFORPURCHASEORDER]'
GO
-- End creating stored procedure [dbo].[GETUNASSORTEDITEMSFORPURCHASEORDER]

GRANT EXECUTE ON [dbo].GETUNASSORTEDITEMSFORPURCHASEORDER TO [UsersRole];
GO

-- Creating stored procedure GETUNASSORTEDITEMSFORSTOCKCOUNT
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETUNASSORTEDITEMSFORSTOCKCOUNT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GETUNASSORTEDITEMSFORSTOCKCOUNT]
GO
CREATE PROCEDURE [dbo].[GETUNASSORTEDITEMSFORSTOCKCOUNT]
    @bi_ChannelId          BIGINT,
    @dt_ChannelDate        DATETIME,
    @nvc_JournalId         NVARCHAR(100)
AS
BEGIN
    SET NOCOUNT ON
    SELECT DISTINCT(P1.ITEMNUMBER) FROM POSSTOCKCOUNT P1 WHERE NOT EXISTS
    (   SELECT DISTINCT AII.ITEMID FROM POSSTOCKCOUNT P2
        INNER JOIN [dbo].GETASSORTEDPRODUCTS(@bi_ChannelId, @dt_ChannelDate) AII ON P2.ITEMNUMBER = AII.ITEMID
        WHERE AII.ITEMID = P1.ITEMNUMBER
        AND P2.JOURNALID = @nvc_JournalId
    )
    AND P1.JOURNALID = @nvc_JournalId
END

GO
PRINT N'Finished creating stored procedure [dbo].[GETUNASSORTEDITEMSFORSTOCKCOUNT]'
GO
-- End creating stored procedure [dbo].[GETUNASSORTEDITEMSFORSTOCKCOUNT]

GRANT EXECUTE ON [dbo].GETUNASSORTEDITEMSFORSTOCKCOUNT TO [UsersRole];
GO

-- Creating stored procedure [dbo].[REVERSELOOKUPKITVARIANTINFO]

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[REVERSELOOKUPKITVARIANTINFO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[REVERSELOOKUPKITVARIANTINFO]
GO
PRINT N'Creating stored procedure [dbo].[REVERSELOOKUPKITVARIANTINFO]';
GO
CREATE PROCEDURE [dbo].[REVERSELOOKUPKITVARIANTINFO]
    @itemId         NVARCHAR(20),
    @storeRecId     BIGINT,
    @dataAreaId     NVARCHAR(4),
    @cultureId      NVARCHAR(7),
    @storeDate      date,
    @tvp_components [dbo].[KITCOMPONENT_TABLETYPE]   READONLY
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @kitProductMasterNumber BIGINT
    DECLARE @kitRecId               BIGINT
    DECLARE @componentCount         INT

    -- Get kit recordid component count and productmaster associated with current kit item
    SELECT
        @kitProductMasterNumber = T1.PRODUCTMASTER,
        @kitRecId = T1.RECID,
        @componentCount = COUNT(T1.RECID)
    FROM
        RETAILKIT T1
    INNER JOIN dbo.GETASSORTEDPRODUCTS(@storeRecId, @storeDate) AS T2
        ON T1.PRODUCTMASTER = T2.PRODUCTID
    INNER JOIN RETAILKITCOMPONENT AS T3
        ON T3.KIT = T1.RECID
    WHERE
        T2.ITEMID = @ITEMID
    GROUP BY
        T1.RECID , T1.PRODUCTMASTER

    -- Get detailed info of the kit variant that contains the components in the parameter '@tvp_components'. 
    -- If there are mutliple bar code, make sure to select top 1 as caller is expecting single record.
    SELECT TOP 1
        IDC.ITEMID                   AS KITITEMID,
        IDC.DISTINCTPRODUCTVARIANT   AS RETAILKITDISTINCTPRODUCTVARIANT,
        IDC.INVENTDIMID              AS RETAILKITINVENTDIMID,
        IDC.RETAILVARIANTID          AS RETAILKITRETAILVARIANTID,
        ID.CONFIGID                  AS CONFIGID,
        MDV.NAME                     AS CONFIGNAME,
        ISNULL(IIBC.ITEMBARCODE, '') AS KITCONFIGBARCODE
    FROM [dbo].GETASSORTEDPRODUCTS(@STORERECID, @STOREDATE) AP
    INNER JOIN INVENTDIMCOMBINATION IDC
        ON IDC.ITEMID = AP.ITEMID AND
           IDC.DATAAREAID = @DATAAREAID AND
           (IDC.DISTINCTPRODUCTVARIANT = AP.DISTINCTPRODUCTVARIANT OR AP.DISTINCTPRODUCTVARIANT = 0)
    INNER JOIN
            (   -- select the kit variantIds that contain the exact set of components specified in the '@tvp_components' argument
                SELECT
                    KITVARIANT
                FROM
                    RETAILKITVARIANTCOMPONENT AS RKVC
                INNER JOIN @tvp_components    AS CMP
                    ON RKVC.COMPONENT = CMP.PRODUCTID AND
                       RKVC.COMPONENTRECID = CMP.KITLINEIDENTIFIER
                GROUP BY
                    KITVARIANT
                HAVING COUNT(COMPONENT) = @componentCount
            ) AS KV ON KV.KITVARIANT = IDC.DISTINCTPRODUCTVARIANT
    INNER JOIN
        INVENTDIM ID
            ON ID.INVENTDIMID = IDC.INVENTDIMID AND
               ID.DATAAREAID = IDC.DATAAREAID
    LEFT OUTER JOIN
        ECORESCONFIGURATION C
            ON C.NAME = ID.CONFIGID
    LEFT OUTER JOIN
        ECORESPRODUCTMASTERCONFIGURATION MC
            ON MC.CONFIGURATION = C.RECID AND
               MC.CONFIGPRODUCTMASTER = @kitProductMasterNumber
    LEFT OUTER JOIN
        ECORESPRODUCTMASTERDIMVALUETRANSLATION MDV
            ON MDV.PRODUCTMASTERDIMENSIONVALUE = MC.RECID AND
               MDV.LANGUAGEID = @cultureId
    LEFT OUTER JOIN INVENTITEMBARCODE IIBC
            ON IIBC.ITEMID = IDC.ITEMID AND
               IIBC.INVENTDIMID = IDC.INVENTDIMID AND
               IIBC.DATAAREAID = IDC.DATAAREAID AND
               IIBC.BLOCKED = 0
    WHERE IDC.DATAAREAID = @dataAreaId AND
          IDC.ITEMID = @ITEMID
END
GO
PRINT N'Finished creating stored procedure [dbo].[REVERSELOOKUPKITVARIANTINFO]'
GO

GRANT EXECUTE ON [dbo].[REVERSELOOKUPKITVARIANTINFO] TO [UsersRole];
GO
-- End creating stored procedure [dbo].[REVERSELOOKUPKITVARIANTINFO]

-- Creating stored procedure [dbo].[SAVEPRODUCTDATA]

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SAVEPRODUCTDATA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SAVEPRODUCTDATA]
GO
PRINT N'Creating stored procedure [dbo].[SAVEPRODUCTDATA]';
SET QUOTED_IDENTIFIER ON;
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SAVEPRODUCTDATA]
    @bi_ChannelId       BIGINT,
    @xml_ProductData    XML
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @i_ReturnCode               INT;
    execute @i_ReturnCode = crt.SaveProductData @bi_ChannelId, @xml_ProductData
    RETURN @i_ReturnCode;
END;

GO
PRINT N'Finished creating stored procedure [dbo].[SAVEPRODUCTDATA]'
GO

GRANT EXECUTE ON [dbo].[SAVEPRODUCTDATA] TO [UsersRole];
GO
-- End creating stored procedure [dbo].[SAVEPRODUCTDATA]



-- Creating view [DBO].[RETAILINFOCODETRANSLATION]
PRINT N'Creating view [DBO].[RETAILINFOCODETRANSLATION]';

GO
IF OBJECT_ID(N'[DBO].[RETAILINFOCODETRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RETAILINFOCODETRANSLATION]
GO
CREATE VIEW [DBO].[RETAILINFOCODETRANSLATION] AS
(
    SELECT * FROM [AX].RETAILINFOCODETRANSLATION
)

GO
PRINT N'Finished creating view [DBO].[RETAILINFOCODETRANSLATION]'
GO
-- End creating view [DBO].[RETAILINFOCODETRANSLATION]



-- Creating view [DBO].[RETAILINFORMATIONSUBCODETRANSLATION]
PRINT N'Creating view [DBO].[RETAILINFORMATIONSUBCODETRANSLATION]';

GO
IF OBJECT_ID(N'[DBO].[RETAILINFORMATIONSUBCODETRANSLATION]', N'V') IS NOT NULL
    DROP VIEW [DBO].[RETAILINFORMATIONSUBCODETRANSLATION]
GO
CREATE VIEW [DBO].[RETAILINFORMATIONSUBCODETRANSLATION] AS
(
    SELECT * FROM [AX].RETAILINFORMATIONSUBCODETRANSLATION
)

GO
PRINT N'Finished creating view [DBO].[RETAILINFORMATIONSUBCODETRANSLATION]'
GO
-- End creating view [DBO].[RETAILINFORMATIONSUBCODETRANSLATION]


-- Creating function GETPARTYPRIMARYADDRESS
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPARTYPRIMARYADDRESS]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE FUNCTION [dbo].[GETPARTYPRIMARYADDRESS]
(
@PARTYID        BIGINT
)
RETURNS NVARCHAR(255)
AS
BEGIN
DECLARE @ADDRESS    NVARCHAR(255)

SET @ADDRESS = (SELECT TOP 1 REPLACE(LPA.[ADDRESS], CHAR(10), '' '')
FROM DIRPARTYTABLE PT
INNER JOIN DIRPARTYLOCATION PL
ON PT.RECID = PL.PARTY
AND
PL.ISPOSTALADDRESS = 1
AND
PL.ISPRIMARY = 1
AND
PL.ISPRIVATE = 0
AND
PL.VALIDFROM <= GETUTCDATE() AND PL.VALIDTO >= GETUTCDATE()
INNER JOIN  LOGISTICSPOSTALADDRESS LPA
ON PL.LOCATION = LPA.LOCATION
WHERE
PT.RECID = @PARTYID)

RETURN @ADDRESS

END
'
END

GO

-- Creating function GETPARTYPRIMARYCONTACT
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPARTYPRIMARYCONTACT]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE FUNCTION [dbo].[GETPARTYPRIMARYCONTACT]
(
    @PARTYID        BIGINT,
    @CONTACTTYPE    INT
)
RETURNS NVARCHAR(255)
AS
BEGIN

DECLARE @LOCATOR        NVARCHAR(255)

SET @LOCATOR = (
    SELECT TOP 1 LEA.LOCATOR FROM DIRPARTYTABLE PT
        INNER JOIN DIRPARTYLOCATION PL
            ON PT.RECID = PL.PARTY
                AND PL.ISPOSTALADDRESS = 0
        INNER JOIN LOGISTICSELECTRONICADDRESS LEA
            ON PL.LOCATION = LEA.LOCATION
    WHERE PT.RECID = @PARTYID
            AND LEA.ISPRIMARY = 1
            AND LEA.ISPRIVATE = 0
            AND LEA.VALIDFROM <= GETUTCDATE()
            AND LEA.VALIDTO >= GETUTCDATE()
            AND LEA.TYPE = @CONTACTTYPE)

RETURN @LOCATOR

END

'
END

GO


-- Creating table function [dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY]
PRINT N'Creating table function [dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY]';

GO
IF OBJECT_ID(N'[dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY]', N'TF') IS NULL
    EXEC ('CREATE FUNCTION [dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY] () RETURNS @ret TABLE ( id INT ) AS BEGIN RETURN END')
GO
IF (@@ERROR != 0)
    PRINT N'FAILED to create table function [dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY].'
GO

ALTER FUNCTION [dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY]
(
    @ITEMID NVARCHAR(20)
)
RETURNS @CATEGORYHIERARCHIES TABLE
(
    [RECID]                 [BIGINT]            NOT NULL,
    [CATEGORYNAME]          [NVARCHAR](254)     NOT NULL,
    [PARENTCATEGORYID]      [BIGINT]            NULL,
    [CATEGORYLEVEL]         [INT]
)
AS
BEGIN

    DECLARE @PRODUCTCATEGORYID          BIGINT
    DECLARE @CATEGORYHIERARCHYID        BIGINT
    DECLARE @CATEGORYID                 BIGINT
    DECLARE @CATEGORYNAME               NVARCHAR(254)
    DECLARE @PARENTCATEGORYID           BIGINT
    DECLARE @CATEGORYLEVEL              INT

    SET @CATEGORYLEVEL = 0

    SELECT
        @CATEGORYHIERARCHYID = ECORESCATEGORYHIERARCHYROLE.CATEGORYHIERARCHY
    FROM ECORESCATEGORYHIERARCHYROLE
    WHERE NAMEDCATEGORYHIERARCHYROLE = 4

    SELECT
        @PRODUCTCATEGORYID = ECORESPRODUCTCATEGORY.CATEGORY
    FROM ECORESPRODUCTCATEGORY
    INNER JOIN ECORESPRODUCT ON ECORESPRODUCTCATEGORY.PRODUCT = ECORESPRODUCT.RECID
    INNER JOIN INVENTTABLE ON ECORESPRODUCT.RECID = INVENTTABLE.PRODUCT
    WHERE ECORESPRODUCTCATEGORY.CATEGORYHIERARCHY = @CATEGORYHIERARCHYID AND INVENTTABLE.ITEMID = @ITEMID

    SELECT
        @CATEGORYID = RECID,
        @PARENTCATEGORYID = PARENTCATEGORY,
        @CATEGORYNAME = NAME
    FROM ECORESCATEGORY
    WHERE RECID = @PRODUCTCATEGORYID AND CATEGORYHIERARCHY = @CATEGORYHIERARCHYID

    WHILE @PARENTCATEGORYID >= 0
    BEGIN
        INSERT INTO @CATEGORYHIERARCHIES (RECID, CATEGORYNAME, PARENTCATEGORYID, CATEGORYLEVEL)
        VALUES (@CATEGORYID, @CATEGORYNAME, @PARENTCATEGORYID, @CATEGORYLEVEL)

        IF @PARENTCATEGORYID = 0
        SET @PARENTCATEGORYID = -1

        SELECT
            @CATEGORYID = RECID,
            @PARENTCATEGORYID = PARENTCATEGORY,
            @CATEGORYNAME = NAME
        FROM ECORESCATEGORY
        WHERE RECID = @PARENTCATEGORYID AND CATEGORYHIERARCHY = @CATEGORYHIERARCHYID

        SET @CATEGORYLEVEL -= 1
    END

    UPDATE @CATEGORYHIERARCHIES
    SET CATEGORYLEVEL -= @CATEGORYLEVEL + 1

    RETURN
END

GO
PRINT N'Finished creating table function [dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY]'
-- End creating table function [dbo].[GETRETAILPRODUCTCATEGORYHIERARCHY]



-- Creating view [dbo].[RETAILMANUALCHANGESLOG_BR]
PRINT N'Creating view [dbo].[RETAILMANUALCHANGESLOG_BR]';

GO
IF OBJECT_ID(N'[dbo].[RETAILMANUALCHANGESLOG_BR]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RETAILMANUALCHANGESLOG_BR]
GO
CREATE VIEW [dbo].[RETAILMANUALCHANGESLOG_BR] AS
(
  SELECT
    [TABLENAME],
    [PRIMARYKEY],
    [APPLICATION]
  FROM [ax].[RETAILMANUALCHANGESLOG_BR]
)

GO
PRINT N'Finished creating view [DBO].[RETAILMANUALCHANGESLOG_BR]'
GO
-- End creating view [DBO].[RETAILMANUALCHANGESLOG_BR]


SET QUOTED_IDENTIFIER ON
CREATE TYPE [dbo].[RETAILERRORSTABLETYPE] AS TABLE(
    [ERRORID] [int] NOT NULL,
    [ERRORMESSAGEID] [int] NOT NULL,
    [DESCRIPTION] [nvarchar](255) NULL,
    [CODEUNIT] [nvarchar](100) NULL,
    [ACTIVE] [int] NULL,
    [FIRSTINVERSION] [nvarchar](20) NULL,
    [DATECREATED] [datetime] NULL,
    [DATEUPDATED] [datetime] NULL,
    [RECID] [bigint] NULL,
    PRIMARY KEY NONCLUSTERED
    (
              [ERRORID] ASC,
              [ERRORMESSAGEID] ASC
    )
)

GRANT EXECUTE ON TYPE::[dbo].[RETAILERRORSTABLETYPE] TO [UsersRole];
GO

DECLARE @tvp_RetailErrors [dbo].[RETAILERRORSTABLETYPE]

-- Populates temporary table dbo.RetailErrors_tmp with records.
INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1, 1, N'Could not initialize the application, e.g. loading all settings', N'POS.Program.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (2, 2, N'A critical error has occurred.  The application will terminate.', N'POS.Program.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3, 5, N'Another instance of the application is running.', N'POS.Program.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1000, 1000, N'Could not initialize the operation and run the operation thread.', N'POSProcesses.POSApp.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1001, 1001, N'The operation thread timed out.', N'POSProcesses.POSProcessThread.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1002, 1002, N'Error executing the operation thread.', N'POSProcesses.POSProcessThread.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1003, 1003, N'The supplied error number could not be found in the database', N'POSProcesses.frmError', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1004, 1004, N'The user has insufficient rights to run the operation.', N'POSProcesses.Operation', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1005, 1005, N'Error occured during cash changer operation.', N'POSProcesses.Operation', 1, N'6.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1007, 1020, N'Trying to run an unknown operation.', N'POSProcesses.POSProcessThread', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1008, 1010, N'Could not display a transaction selected in the journal.', N'POSProcesses.frmTransactionViewer', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1009, 1820, N'Error concluding the transaction', N'POSProcesses.POSApp.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1010, 1824, N'Error saving the transaction', N'POSProcesses.POSApp.cs', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (1650, 1650, N'Error processing the Tax Free operation', N'POSProcesses.frmJournal', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3180, 3186, N'Illeagal price entry', N'POSProcesses.PayCash', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3540, 3540, N'The user has insufficient rights to run the operation.', N'POSProcesses.VerifyUserRights', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3600, 3601, N'Error processing the EOD operation', N'POSProcesses.EOD', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3620, 3621, N'Error processing the end of shift operation', N'POSProcesses.EOS', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3840, 3841, N'Error processing the DeclareStartAmount operation', N'POSProcesses.DeclareStartAmount', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3860, 3862, N'Error processing the FloatEntry operation', N'POSProcesses.FloatEntry', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3880, 3881, N'Error processing the TenderRemoval operation', N'POSProcesses.TenderRemoval ', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3900, 3901, N'Error processing the SafeDrop operation', N'POSProcesses.SafeDrop', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (3920, 3921, N'Error processing the BankDrop operation', N'POSProcesses.BankDrop', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4023, 4023, N'Error processing a customercard.', N'POSProcesses.CustomerCard', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4043, 4043, N'Error processing a customer barcode.', N'POSProcess.CustomerBarcode', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4062, 4062, N'Error processing employee card.', N'POSProcess.EmployeeCard', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4082, 4082, N'Error processing  a employee barcode.', N'POSProcess.EmployeeBarcode', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4103, 4103, N'Error processing a salesperson''s card.', N'POSProcess.SalespersonCard', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4122, 4122, N'Error processing a salesperson''s barcode.', N'POSProcess.SalespersonBarcode', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4142, 4142, N'Error when clearing a salesperson''s info from an item', N'POSProcess.SalespersonClear', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4160, 4172, N'Illeagal quantity entry', N'POSProcesses.SetQuantity', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (4181, 4181, N'Error processing the Pay Credit Memo operation', N'POSProcesses.PayCreditMemo', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (13000, 13000, N'Could not load all external service and module dlls', N'SystemFramework.ApplicationServices', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (13010, 13010, N'Could not establish a link to the transaction services', N'SystemFramework.TransactionServices', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

INSERT @tvp_RetailErrors ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
VALUES (50000, 50000, N'Could not increment the EFT batch number', N'Services.EFT', 1, N'5.0.0.0', GETUTCDATE(), NULL, NULL)

-- Merges temporary table into dbo.RetailErrors.
MERGE dbo.RetailErrors AS T
USING @tvp_RetailErrors AS S
ON (T.errorid = S.errorid AND T.errormessageid = S.errormessageid)
WHEN MATCHED
    THEN UPDATE SET [DESCRIPTION] = S.[DESCRIPTION],
                    [CODEUNIT] = S.CODEUNIT,
                    [ACTIVE] = S.ACTIVE,
                    [FIRSTINVERSION] = S.FIRSTINVERSION,
                    [DATECREATED] = S.DATECREATED,
                    [DATEUPDATED] = S.DATEUPDATED,
                    [RECID] = S.RECID
WHEN NOT MATCHED
    THEN INSERT ([ERRORID], [ERRORMESSAGEID], [DESCRIPTION], [CODEUNIT], [ACTIVE], [FIRSTINVERSION], [DATECREATED], [DATEUPDATED], [RECID])
         VALUES(S.ERRORID, S.ERRORMESSAGEID, S.[DESCRIPTION], S.CODEUNIT, S.ACTIVE, S.FIRSTINVERSION, S.DATECREATED, S.DATEUPDATED, S.RECID)
;

DROP TYPE [dbo].[RETAILERRORSTABLETYPE]
GO

-- Populate POSISINFO table
PRINT 'Populating table POSISINFO ..'
IF NOT EXISTS (SELECT * FROM [dbo].[POSISINFO] WHERE [ID] = 'DBVERSION')
BEGIN
    INSERT [dbo].[POSISINFO] ([ID], [TEXT]) VALUES ('DBVERSION', '6.3.0.0')
END
GO