Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Wednesday, April 24, 2024

SQL Delete statement with Not exists join

Sample SQL: 

Requirement: Delete with Not exsits join in where condition

DELETE  ITM FROM  InventItemInventSetup ITM 

WHERE  NOT EXISTS (SELECT 1 FROM   INVENTTABLE IT WHERE IT.DataAreaId =  ITM.DataAreaId 

AND IT.ITEMID = ITM.ITEMID)

       AND ITM.DATAAREAID in ('USMF')

Monday, May 15, 2023

SQL Keywords

STRING_AGG

SQL Query:

select STRING_AGG(erc.Code, ';') as ProductLine From EcoResCategory erc

join EcoResProductCategory erpc

on erc.RecId = erpc.Category 

join INVENTTABLE it

on erpc.Product  = it.PRODUCT

where  it.ITEMID  = 'TST702'  and erc.Code  != '' and it.DATAAREAID = 'USMF' 

Output: 

2;7;13;G;9;3;Z;11;17;D;B;F;8;6;1;05


Execute:


Execute ('

Declare @val Varchar(MAX)

Select @val = COALESCE(@val + '','' + erc.Code, erc.Code) 

        From EcoResCategory erc

join EcoResProductCategory erpc

on erc.RecId = erpc.Category 

join INVENTTABLE it

on erpc.Product  = it.PRODUCT

where  it.ITEMID  = 'TST702'  and erc.Code  != '' and it.DATAAREAID = 'USMF' 

Group by erc.Code order by erc.Code asc

Select @val')


COALESCE

Declare @val Varchar(MAX)

Select @val = COALESCE(@val + ';' + erc.Code, erc.Code) 

        From EcoResCategory erc

join EcoResProductCategory erpc

on erc.RecId = erpc.Category 

join INVENTTABLE it

on erpc.Product  = it.PRODUCT

where  it.ITEMID  = 'TST702'  and erc.Code  != '' and it.DATAAREAID = 'USMF' 

Group by erc.Code order by erc.Code asc

Select @val


Wednesday, March 15, 2023

To select the nth row in a SQL database table?

Query:


SELECT * FROM

    (

        SELECT ROW_NUMBER () OVER (ORDER BY RecId) AS RowNum, *   FROM SALESTABLE

    ) sub

WHERE RowNum = 9

Monday, January 23, 2023

Sync D365FO/AX table to Commerce DB in D365FO


Subscribe to Event handler.

    [SubscribesTo(classStr(RetailCDXSeedDataBase), delegateStr(RetailCDXSeedDataBase, registerCDXSeedDataExtension))]

    public static void RetailCDXSeedDataBase_registerCDXSeedDataExtension(str originalCDXSeedDataResource, List resources)

    {

        if (originalCDXSeedDataResource == resourceStr(RetailCDXSeedDataAX7))

        {

            resources.addEnd(resourceStr(SAN_SalesOrderClassResource));

            resources.addEnd(resourceStr(smmBusRelSectorTableResource));

        }

    }


Create D365FO resource (SAN_SalesOrderClassResource) for new table.

Resource content: XML

<RetailCdxSeedData ChannelDBMajorVersion="7" ChannelDBSchema="ext" Name="AX7">

   <Subjobs>

       <Subjob Id="SAN_SalesOrderClass" TargetTableSchema="ext" AxTableName="SAN_SalesOrderClass">

           <ScheduledByJobs>

               <ScheduledByJob>1140</ScheduledByJob>

           </ScheduledByJobs>

           <AxFields>

              <Field Name="SALESORDERCLASS"/>

<Field Name="MAXQTY"/>

<Field Name="AVAILABLEFROM"/>

<Field Name="AVAILABLETO"/>

<Field Name="SOALLOCPRIORITY"/>

<Field Name="PAYMTERMID"/>

<Field Name="HOLDCODE"/>      

<Field Name="RECID"/>

    <Field Name="RECVERSION"/>

    <Field Name="PARTITION"/>

            </AxFields>

       </Subjob>

   </Subjobs>

</RetailCdxSeedData>


Friday, January 6, 2023

SQL Query to fetch Related information based on transaction type from TaxTrans in D365FO

//Query to Fetch Related information based on transaction type and tagged Masters (Customer/Vendor) from 

Posted Sales Tax

1. Type (Customer or vendor or ledger)

2. Identification (Customer or vendor account name or Voucher entries text)

//These columns also be converted to Computed column (T-SQL) in view.


Query:

 CAST

                 ((SELECT TOP (1) CAST((CASE WHEN tt.Voucher =

                                   (SELECT TOP (1) ct.Voucher

                                   FROM    CUSTTRANS AS ct

                                   WHERE ct.VOUCHER = tt.VOUCHER AND ct.TRANSDATE = tt.TRANSDATE AND ct.DATAAREAID = tt.DATAAREAID) THEN 'Customer' ELSE CASE WHEN tt.Voucher =

                                   (SELECT TOP (1) vt.Voucher

                                   FROM    VendTrans AS vt

                                   WHERE vt.VOUCHER = tt.VOUCHER AND vt.TRANSDATE = tt.TRANSDATE AND vt.DATAAREAID = tt.DATAAREAID) THEN 'Vendor' ELSE 'Ledger' END END) AS NVARCHAR(10)) AS Expr1

                  FROM    dbo.TAXTRANS AS tt

                  WHERE (RECID = T1.RECID)) AS NVARCHAR(60)) AS TYPE,


 

CAST

                 ((SELECT TOP (1) dpt.NAME

                  FROM    dbo.CUSTTRANS AS ct INNER JOIN

                               dbo.CUSTTABLE AS ctab ON ctab.ACCOUNTNUM = ct.ACCOUNTNUM AND ct.DATAAREAID = ctab.DATAAREAID INNER JOIN

                               dbo.DIRPARTYTABLE AS dpt ON dpt.RECID = ctab.PARTY

                  WHERE (ct.VOUCHER = T1.VOUCHER) AND (ct.TRANSDATE = T1.TRANSDATE) AND (ct.DATAAREAID = T1.DATAAREAID)

                  UNION ALL

                  SELECT TOP (1) dpt.NAME

                  FROM   dbo.VENDTRANS AS vt INNER JOIN

                               dbo.VENDTABLE AS vtab ON vtab.ACCOUNTNUM = vt.ACCOUNTNUM AND vt.DATAAREAID = vtab.DATAAREAID INNER JOIN

                               dbo.DIRPARTYTABLE AS dpt ON dpt.RECID = vtab.PARTY

                  WHERE (vt.VOUCHER = T1.VOUCHER) AND (vt.TRANSDATE = T1.TRANSDATE) AND (vt.DATAAREAID = T1.DATAAREAID)

                  UNION ALL

                  SELECT TOP (1) gjae.TEXT

                  FROM   dbo.GENERALJOURNALENTRY AS gje INNER JOIN

                               dbo.GENERALJOURNALACCOUNTENTRY AS gjae ON gjae.GENERALJOURNALENTRY = gje.RECID

                  WHERE (NOT EXISTS

                                   (SELECT TOP (1) VOUCHER

                                   FROM    dbo.CUSTTRANS AS ct2

                                   WHERE (VOUCHER = T1.VOUCHER) AND (TRANSDATE = T1.TRANSDATE) AND (DATAAREAID = T1.DATAAREAID))) AND (NOT EXISTS

                                   (SELECT TOP (1) VOUCHER

                                   FROM    dbo.VENDTRANS AS vt2

                                   WHERE (VOUCHER = T1.VOUCHER) AND (TRANSDATE = T1.TRANSDATE) AND (DATAAREAID = T1.DATAAREAID))) AND (gje.SUBLEDGERVOUCHER = T1.VOUCHER) AND (gje.ACCOUNTINGDATE = T1.TRANSDATE) AND 

                               (gje.SUBLEDGERVOUCHERDATAAREAID = T1.DATAAREAID)) AS NVARCHAR(100)) AS IDENTIFICATION 

FROM   dbo.TAXTRANS AS T1

Tuesday, July 5, 2022

Batch job clean up X++ D365FO

  Connection                      connection;

        Statement                       statement;

        SqlStatementExecutePermission   permission;

        str                             deleteStm;


        if (!Global::isSystemAdministrator())

        {

            error("@SYS130561");

            return;

        }


        connection  = new Connection();

        connection.ttsbegin();


        statement   = connection.createStatement();

        deleteStm = '(SELECT RECID FROM ' + ReleaseUpdateDB::backendTableName(tableNum(Batch)) + ' WHERE GROUPID = \'' + 'TT_BT' + '\')';

        deleteStm = 'DELETE FROM ' + ReleaseUpdateDB::backendTableName(tableNum(BatchConstraints)) + ' WHERE BATCHID IN ' + deleteStm +

            ' OR DEPENDSONBATCHID IN ' + deleteStm + ';';

        permission  = new SqlStatementExecutePermission(deleteStm);

        permission.assert();

        statement.executeUpdate(deleteStm);

        statement.close();

        CodeAccessPermission::revertAssert();


        statement   = connection.createStatement();

        deleteStm = 'DELETE FROM ' + ReleaseUpdateDB::backendTableName(tableNum(Batch)) + ' WHERE GROUPID = \'' + 'TT_BT' + '\';';

        permission  = new SqlStatementExecutePermission(deleteStm);

        permission.assert();

        statement.executeUpdate(deleteStm);

        statement.close();

        CodeAccessPermission::revertAssert();


statement   = connection.createStatement();

        deleteStm = 'DELETE FROM ' + ReleaseUpdateDB::backendTableName(tableNum(BatchJobHistory)) + ' WHERE STATUS != \'' + 3 + '\';';

        permission  = new SqlStatementExecutePermission(deleteStm);

        permission.assert();

        statement.executeUpdate(deleteStm);

        statement.close();

        CodeAccessPermission::revertAssert();


        connection.ttscommit();

        connection = null;

Monday, February 28, 2022

Get SQL Table row counts

CREATE TABLE TSTRowCounts(RowCount1 BIGINT,TableName VARCHAR(128))


EXEC sp_MSForEachTable 'INSERT INTO TSTRowCounts

                        SELECT COUNT_BIG(*) AS RowCount1,

                        ''?'' as TableName FROM ?'


SELECT  top 100 TableName, RowCount1  FROM  TSTRowCounts ORDER BY RowCount1 DESC


select * from TSTRowCounts

where RowCount1 >100000

Monday, July 12, 2021

Get Category Hierarchy levels X++ D365FO

 class GetCategoryLevels

{

    public static void main(Args _args)

    {

// TOP to BOTTOM hierarchy level data

        void loopchild(RefRecId     _recId)

        {

            EcoResCategory   ecoResCategoryChk, ecoResCategoryChild;

            while select ecoResCategoryChk

                where ecoResCategoryChk.ParentCategory ==  _recId

            {

                //Child query insert to table Write ur logic

                Info(ecoResCategoryChk.Name);

                ecoResCategoryChild.clear();

                select firstonly  ecoResCategoryChild

                    where ecoResCategoryChild.ParentCategory ==  ecoResCategoryChk.RecId;

                if(ecoResCategoryChild)

                {

                    loopchild(ecoResCategoryChild.ParentCategory);

                }

            }

        }

        EcoResCategory  ecoResCategory;

        EcoResProductCategory   ecoResProductCategory, ecoResProductCategoryCHk;

        RefRecId parentCategory;

        select firstonly  ecoResCategory

            where ecoResCategory.Name == "Refrigeration";

        parentCategory = EcoResCategory.RecId;

        if(parentCategory)

        {

            //Parent query insert  - Write ur logic

            Info(ecoResCategory.Name);

            loopchild(parentCategory);

        }

    }

}

Thursday, January 21, 2021

Insert table data from one DB to another DB SQL script

 Insert table data from one DB to another DB SQL script


SQL 1:

INSERT INTO <Target DB>.dbo.<Table Name>

SELECT *

FROM <Source DB>.dbo.<Table Name>

where <Source DB>.dbo.<Table Name>.<Table field name>= '<values>'

 

SQL 2:

INSERT INTO [target db].[dbo].[table] (<columnA>,<columnB>,…)

SELECT <columnA>,<columnB>,…

FROM [source db].[dbo].[table] 

 


Monday, August 12, 2019

SysDa API in D365 FO

SysDa API

"Da" is short for Data access. It is a set of new APIs exposing the object graph that the compiler otherwise produces from select statements. 

Problem:
On the extensibility journey in D365 FO, X++ select statements are not extensible. If developer needs to add a new range, a join, a field in the field list – it is not possible.

Pros:
1. It has the same performance characteristics as select statements
2. It is extensible for futher enhancement

3. It is available in from PU22


List:
  • Select: SysDaQueryObject, SysDaSearchObject, and SysDaSearchStatement
  • Update: SysDaUpdateObject and SysDaUpdateStatement
  • Insert: SysDaInsertObject and SysDaInsertStatement
  • Delete: SysDaQueryObject, SysDaDeleteObject, and SysDaDeleteStatement
CRUD Operation:

Select: 

        //Selection - On SYSDA API  

        VendTable   vendTab; 
        var qe = new SysDaQueryObject(vendTab);
        qe.projection()
                .add(fieldStr(VendTable, AccountNum))
                .add(fieldStr(VendTable, VendGroup));
        qe.WhereClause(new SysDaEqualsExpression(
                new SysDaFieldExpression(vendTab, fieldStr(VendTable, VendGroup)),
                new SysDaValueExpression(10)));
        //below statement to get less than or equal to field values
        //qe.WhereClause(new SysDaLessThanOrEqualsExpression(
        //        new SysDaFieldExpression(vendTab, fieldStr(VendTable, VendGroup)),
        //        new SysDaValueExpression(10)));
        //Default order by field is ASC
        qe.OrderByClause().addDescending(fieldStr(VendTable, AccountNum)); //for desc

        //Type 1
        var so = new SysDaSearchObject(qe);
        var ss = new SysDaSearchStatement();
        while (ss.nextRecord(so))
        {
            info(vendTab.AccountNum);
        }

        //Type 2 
        var fo = new SysDaFindObject(qe);
        new SysDaFindStatement().execute(fo);

        //Type 3 Using join
        PurchLine   purchLine;
        InventDim   Invdim;
        var qepl = new SysDaQueryObject(purchLine);
        var qedim = new SysDaQueryObject(Invdim);
        qepl.joinClause(SysDaJoinKind::InnerJoin,qedim);
        //Relation manual
        qedim.WhereClause(new SysDaEqualsExpression(
                new SysDaFieldExpression(purchLine, fieldStr(PurchLine, InventDimId)),
                new SysDaFieldExpression(Invdim, fieldStr(InventDim, InventDimId))));
        qepl.WhereClause(new SysDaEqualsExpression(
                new SysDaFieldExpression(purchLine, fieldStr(PurchLine, VendAccount)),
                new SysDaValueExpression("000013")));
        var so1 = new SysDaSearchObject(qepl);
        var ss1 = new SysDaSearchStatement();
        while (ss1.nextRecord(so1))
        {
            info(purchLine.ItemId + purchLine.InventDimId);
        }

Update:
      // Update - ON SysDa API
        PurchTable  purchTable;
        var updateObj = new SysDaUpdateObject(purchTable);
        updateObj.settingClause()
         .add(fieldStr(PurchTable, PurchName), new SysDaValueExpression( "SAN")); 
        updateObj.whereClause(new SysDaEqualsExpression(
        new SysDaFieldExpression(purchTable, fieldStr(PurchTable, OrderAccount)),
            new SysDaValueExpression("000013")));
        //Updating the rows.
        ttsbegin;
        new SysDaUpdateStatement().execute(updateObj);
        ttscommit;
Insert:
     // Insert - ON SysDa API
        sanLanguageTable santab;
        var Io = new SysDaInsertObject(santab);
        Io.fields()
            .add(fieldStr(sanLanguageTable, Name))
            .add(fieldStr(sanLanguageTable, Description));
        VendGroup source;
        var qe = new SysDaQueryObject(source); 
        var s1 = qe.projection()
            .Add(fieldStr(VendGroup, Name))
            .Add(fieldStr(VendGroup, VendGroup));
        Io.query(qe);
        var istate = new SysDaInsertStatement();
        ttsbegin;
        istate.executeQuery(Io);
        ttscommit;
Delete:
     // Delete - ON SysDa API
        sanLanguageTable santab;
        var qe = new SysDaQueryObject(santab); 
        var s = qe.projection()
                .add(fieldStr(sanLanguageTable, Name));
        var ds = new SysDaDeleteStatement();
        var delobj = new SysDaDeleteObject(qe);
        ttsbegin;
        ds.executeQuery(delobj);
        ttscommit;
        //To get no of rrows after deletion
        info("Number of rows after deletion: " + any2Str(t.RowCount()));


Important:
You can use the toString() method on SysDaQueryObject, SysDaUpdateObject, SysDaInsertObject, and SysDaQueryObject objects to view the statement that you're building.

Related Objects: (SysDa API)
Base Enum:
SysDaAggregateFieldType
SysDaFirstOnlyHint
SysDaJoinKind

Class:
SysDaAggregateProjectionField
SysDaAndExpression
SysDaAvgOfField
SysDaBinaryExpression
SysDaCountOfField
SysDaCrossCompany
SysDaCrossCompanyAll
SysDaCrossCompanyContainer
SysDaDataAccessStatement
SysDaDeleteObject
SysDaDeleteStatement
SysDaDivideExpression
SysDaEqualsExpression
SysDaFieldExpression
SysDaFindStatement
SysDaGreaterThanExpression
SysDaGreaterThanOrEqualsExpression
SysDaGroupBys
SysDaInsertObject
SysDaInsertStatement
SysDaIntDivExpression
SysDaLessThanExpression
SysDaLessThanOrEqualsExpression
SysDaLikeExpression
SysDaMaxOfField
SysDaMinOfField
SysDaMinusExpression
SysDaModExpression
SysDaMultiplyExpression
SysDaNotEqualsExpression
SysDaOrderBys
SysDaOrExpression
SysDaPlusExpression
SysDaProjectionField
SysDaQueryExpression
SysDaQueryObject
SysDaSearchObject
SysDaSearchStatement
SysDaSelection
SysDaSettingsList
SysDaSumOfField
SysDaUpdateObject
SysDaUpdateStatement
SysDaValueExpression
SysDaValueField


Tuesday, July 16, 2019

Get all records from AOT Query by enabling validTimeStateDateTimeRange in D365 FO/AX 2012

utcdatetime minDateTime = DateTimeUtil::minValue() , maxDateTime = DateTimeUtil::maxValue();


qry = new Query(QueryStr(TestQuery));
qry.validTimeStateDateTimeRange(minDateTime, maxDateTime); //In order display all records from ValidTimeState stamp table

Example: (Table Names)
HcmEmployment
HcmWorkerPositionAssignment
HcmWorkerEnrollBenefit

Thursday, June 27, 2019

Document Routing Agent D365FO

Document Routing Agent is an application which enables network printing scenarios in Dynamics 365 for Finance and Operations. It basically manages the spooling of documents to network printer devices.
Install/Configure Document Routing Agent:
Navigate for network printers page 
-> Organization administration > Setup > Network printers
       -> Options tab, in the Application group, 
       -> click -> Download document routing agent installer.
-> Once downloaded an executable file double click to install it on system.
-> Close all browser
-> Run -> Document Routing Agent
      -> Click -> Setting 
                  -> Enter Application Id, AAD tenant, D365 URL
-> Sign In Document Routing Agent using Credentials
-> On Document Routing Agent
      -> Click -> Printers
      -> Navigate to Network Printer
      -> Edit and Make Active to YES for necessary printers

Note:
'Microsoft Dynamics 365 Document Routing Service' service should run under "Domain admin user"

Wednesday, June 12, 2019

Import New user using SQL in Azure cloud DEV VM in D365 FO



INSERT INTO USERINFO(Id, Name, ENABLE, COMPANY,SID,NETWORKDOMAIN, NETWORKALIAS, ENABLEDONCE,LANGUAGE,
 HELPLANGUAGE, PREFERREDTIMEZONE, ACCOUNTTYPE,DEFAULTPARTITION)
VALUES ('<UserId>','<Name>',1,'<Default company login>','<SID>',
'https://sts.windows.net/',
'<Email Id>',1,'en-us','en-us',<Timezone>,2,1);

Insert into SECURITYUSERROLE (USER_, SECURITYROLE, ASSIGNMENTSTATUS, ASSIGNMENTMODE)
values ('<UserId>','199',1,1),
 ('<UserId>','217',1,1);

Step:

Method 1:
1. Right click on AOT -> Refresh
2. Full DB sync
3. iisreset

Method 2: (Method 1 is not working)
1. Right click on AOT -> Refresh
2. Build App Suite model with DB sync
3. iisreset

Method 3: (if Method 1 & 2 is not working)
1. Right click on AOT -> Refresh
2. Full Build All model with DB sync
3. iisreset




Friday, May 24, 2019

Timezone and TZId field in Dynamics

Timezone descriptionTimeZoneTZId
(GMT-12:00) International Date Line West2424001
(GMT-11:00) Midway Island, Samoa6565001
(GMT-10:00) Hawaii3939001
(GMT-09:00) Alaska22001
(GMT-08:00) Pacific Time (US &amp; Canada)5858001
(GMT-08:00) Tijuana, Baja California5959001
(GMT-07:00) Arizona7575001
(GMT-07:00) Mountain Time (US &amp; Canada)4747001
(GMT-07:00) Chihuahua, La Paz, Mazatlan4848001
(GMT-06:00) Central America1515001
(GMT-06:00) Central Time (US &amp; Canada)2121001
(GMT-06:00) Guadalajara, Mexico City, Monterrey2222001
(GMT-06:00) Saskatchewan1111001
(GMT-05:00) Bogota, Lima, Quito, Rio Branco6363001
(GMT-05:00) Eastern Time (US &amp; Canada)2929001
(GMT-05:00) Indiana (East)7474001
(GMT-04:00) Atlantic Time (Canada)66001
(GMT-04:00) La Paz6464001
(GMT-04:00) Manaus1717001
(GMT-04:00) Santiago5757001
(GMT-04:30) Caracas8585001
(GMT-03:30) Newfoundland5454001
(GMT-03:00) Brasilia2828001
(GMT-03:00) Buenos Aires, Georgetown6262001
(GMT-03:00) Greenland3636001
(GMT-03:00) Montevideo8383001
(GMT-02:00) Mid-Atlantic4545001
(GMT-01:00) Azores1010001
(GMT-01:00) Cape Verde Is.1212001
(GMT) Casablanca, Monrovia, Reykjavik3737001
(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, Londo3535001
(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna7979001
(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Pragu1818001
(GMT+01:00) Brussels, Copenhagen, Madrid, Paris6060001
(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb1919001
(GMT+01:00) West Central Africa7878001
(GMT+02:00) Amman4343001
(GMT+02:00) Athens, Bucharest, Istanbul3838001
(GMT+02:00) Beirut4646001
(GMT+02:00) Minsk2727001
(GMT+02:00) Cairo3030001
(GMT+02:00) Harare, Pretoria6868001
(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius3333001
(GMT+02:00) Jerusalem4242001
(GMT+02:00) Windhoek5151001
(GMT+03:00) Baghdad55001
(GMT+03:00) Kuwait, Riyadh33001
(GMT+03:00) Moscow, St. Petersburg, Volgograd6161001
(GMT+03:00) Nairobi2525001
(GMT+03:00) Tbilisi3434001
(GMT+03:30) Tehran4141001
(GMT+04:00) Abu Dhabi, Muscat44001
(GMT+04:00) Baku99001
(GMT+04:00) Caucasus Standard Time8484001
(GMT+04:00) Yerevan1313001
(GMT+04:30) Kabul11001
(GMT+05:00) Ekaterinburg3131001
(GMT+05:00) Islamabad, Karachi, Tashkent8080001
(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi4040001
(GMT+05:30) Sri Jayawardenepura6969001
(GMT+05:45) Kathmandu5252001
(GMT+06:00) Almaty, Novosibirsk5050001
(GMT+06:00) Astana, Dhaka1616001
(GMT+06:30) Yangon (Rangoon)4949001
(GMT+07:00) Bangkok, Hanoi, Jakarta6666001
(GMT+07:00) Krasnoyarsk5656001
(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi2323001
(GMT+08:00) Irkutsk, Ulaan Bataar5555001
(GMT+08:00) Kuala Lumpur, Singapore6767001
(GMT+08:00) Perth7777001
(GMT+08:00) Taipei7070001
(GMT+09:00) Osaka, Sapporo, Tokyo7272001
(GMT+09:00) Seoul4444001
(GMT+09:00) Yakutsk8282001
(GMT+09:30) Adelaide1414001
(GMT+09:30) Darwin77001
(GMT+10:00) Brisbane2626001
(GMT+10:00) Canberra, Melbourne, Sydney88001
(GMT+10:00) Guam, Port Moresby8181001
(GMT+10:00) Hobart7171001
(GMT+10:00) Vladivostok7676001
(GMT+11:00) Magadan, Solomon Is., New Caledonia2020001
(GMT+12:00) Auckland, Wellington5353001
(GMT+12:00) Fiji, Kamchatka, Marshall Is.3232001
(GMT+13:00) Nuku’alofa7373001

Wednesday, April 3, 2019

Explore metadata search feature in Visual Studio D365 FO


Access the Metadata search tool window from the Dynamics 365 > Metadata Search.


Search Keyword Description
Code # Search for a specific code. Use quotes around code snippets. The matching source code is the elements that contain the specified code snippet.
Type # Filter the elements by type  Each comma-separated value should be the name of an element or sub-element type (root type or subtype) (i.e. table, class, field). Logic of filtering is:
Model # Filter the elements by model Each comma-separated value should be the name of a model in your application
Name # Filter the elements by name This is the default filter, meaning if you just type a filter value, it is assumed to be an element name. Each comma-separated value is an acceptable element name.
Property # Search for element with the property with the specific value  Each comma-separated value should be in the form property_name=property_value



Note: Make sure there should not be any space in between Type values otherwise it will show "Invalid query" error.

Cleaning up cross-reference DB in Dynamics 365 for finance and operation ON DEV VM


// For unwanted cross reference data clean Up on DB (DYNAMICSXREFDB)

DELETE [REFERENCES] FROM [REFERENCES]
    JOIN Names 
ON (Names.Id = [REFERENCES].SourceId 
OR Names.Id = [REFERENCES].TargetId)
    JOIN Modules 
ON Names.ModuleId = Modules.Id


Thursday, February 14, 2019

Turn off all the D365F&O services in DEV VM

To turn off all the D365F&O services

Steps:
1. Open PowerShell as an admin
2. Type "stop-d365environment"
3. click -> Enter


To start
Start-d365environment

Tuesday, January 29, 2019

Backup and restore in another ENV Dynamics 365 Finance and operations


1.       Take the AxDB database backup
2.       Do the Full Build.
3.       Do the Database Synchronize 
4.       Connect the LCS and download the Database 
5.       Create the new Database with Name : UATBackUp81.
6.       Restore the downloaded Database from LCS to UATBackUp81.
7.       Need to change the UATBackUp81
a.        Security User details
Script:
CREATE USER axdeployuser FROM LOGIN axdeployuser
EXEC sp_addrolemember 'db_owner', 'axdeployuser'

CREATE USER axdeployextuser WITH PASSWORD = '<password from LCS>'
IF EXISTS (select * from sys.database_principals where type = 'R' and name = 'DeployExtensibilityRole')
BEGIN
    EXEC sp_addrolemember 'DeployExtensibilityRole', 'axdeployextuser'
END

CREATE USER axdbadmin WITH PASSWORD = '<password from LCS>'
EXEC sp_addrolemember 'db_owner', 'axdbadmin'

CREATE USER axruntimeuser WITH PASSWORD = '<password from LCS>'
EXEC sp_addrolemember 'db_datareader', 'axruntimeuser'
EXEC sp_addrolemember 'db_datawriter', 'axruntimeuser'

CREATE USER axmrruntimeuser WITH PASSWORD = '<password from LCS>'
EXEC sp_addrolemember 'ReportingIntegrationUser', 'axmrruntimeuser'
EXEC sp_addrolemember 'db_datareader', 'axmrruntimeuser'
EXEC sp_addrolemember 'db_datawriter', 'axmrruntimeuser'

CREATE USER axretailruntimeuser WITH PASSWORD = '<password from LCS>'
EXEC sp_addrolemember 'UsersRole', 'axretailruntimeuser'
EXEC sp_addrolemember 'ReportUsersRole', 'axretailruntimeuser'

CREATE USER axretaildatasyncuser WITH PASSWORD = '<password from LCS>'
EXEC sp_addrolemember 'DataSyncUsersRole', 'axretaildatasyncuser'

ALTER DATABASE SCOPED CONFIGURATION  SET MAXDOP=2
ALTER DATABASE SCOPED CONFIGURATION  SET LEGACY_CARDINALITY_ESTIMATION=ON
ALTER DATABASE SCOPED CONFIGURATION  SET PARAMETER_SNIFFING= ON
ALTER DATABASE SCOPED CONFIGURATION  SET QUERY_OPTIMIZER_HOTFIXES=OFF

ALTER DATABASE <imported database name> SET COMPATIBILITY_LEVEL = 130;
ALTER DATABASE <imported database name> SET QUERY_STORE = ON;

update [dbo].[SYSSERVICECONFIGURATIONSETTING]
set value ='<tenant ID from existing database>'
where name = 'TENANTID'

update dbo.POWERBICONFIG
set TENANTID = '<tenant ID from existing database>'

update dbo.PROVISIONINGMESSAGETABLE
set TENANTID = '<tenant ID from existing database>'
GO
-- Begin Refresh Retail FullText Catalogs
DECLARE @RFTXNAME NVARCHAR(MAX);
DECLARE @RFTXSQL NVARCHAR(MAX);
DECLARE retail_ftx CURSOR FOR
SELECT OBJECT_SCHEMA_NAME(object_id) + '.' + OBJECT_NAME(object_id) fullname FROM SYS.FULLTEXT_INDEXES
    WHERE FULLTEXT_CATALOG_ID = (SELECT TOP 1 FULLTEXT_CATALOG_ID FROM SYS.FULLTEXT_CATALOGS WHERE NAME = 'COMMERCEFULLTEXTCATALOG');
OPEN retail_ftx;
FETCH NEXT FROM retail_ftx INTO @RFTXNAME;

BEGIN TRY
    WHILE @@FETCH_STATUS = 0 
    BEGIN 
        PRINT 'Refreshing Full Text Index ' + @RFTXNAME;
        EXEC SP_FULLTEXT_TABLE @RFTXNAME, 'activate';
        SET @RFTXSQL = 'ALTER FULLTEXT INDEX ON ' + @RFTXNAME + ' START FULL POPULATION';
        EXEC SP_EXECUTESQL @RFTXSQL;
        FETCH NEXT FROM retail_ftx INTO @RFTXNAME;
    END
END TRY
BEGIN CATCH

PRINT error_message()
END CATCH

CLOSE retail_ftx; 
DEALLOCATE retail_ftx;
-- End Refresh Retail FullText Catalogs
8.       Changes the names like AxDB to AxDB_standard ,  UATBackUp81 to AXDB
USE master;
GO 
ALTER DATABASE AxDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE AxDB MODIFY NAME = AxDB_Standard ;
GO 
ALTER DATABASE AxDB_ Standard SET MULTI_USER
GO
---------------------------------------------------------------------------

USE master;
GO 
ALTER DATABASE UATBackUp81 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE UATBackUp81 MODIFY NAME = AxDB ;
GO 
ALTER DATABASE AxDB SET MULTI_USER
GO
9.       Do the Full DB Synchronize

Skip Inventory reservation on Sales order lines in D365FO

[ExtensionOf(classStr(InventUpd_Reservation))] final class InventUpd_ReservationCls_SAN_Extension {     void updateNow()     {         if(mo...