Monday, September 18, 2017

How to call Stored Procedure in MS Dynamics NAV?

How to Connect with SQl in NAV 2009?

This is for NAV 2009 using Automation Object For Above 2009 you can change these variables to Dotnet. The Link is provided below :- 

Direct Link For Reference in NAV 2013 and Above.

Name DataType Subtype Length
ADOConnection Automation 'Microsoft ActiveX Data Objects 2.8 Library'.Connection 
LADOCommand Automation 'Microsoft ActiveX Data Objects 2.8 Library'.Command 
LADOParameter Automation 'Microsoft ActiveX Data Objects 2.8 Library'.Parameter 
lvarActiveConnection Variant  
SQLString Text  1024
ADORecordSet Automation 'Microsoft ActiveX Data Objects 2.8 Library'.Recordset 

Name ConstValue
pcodServerName Server NAME
pcodDatabaseName DBNAME
pcodUserID USERID
pcodPassword PASSWORD


Step 1 :- Create the Connection


ltxtConnectionString := 'Driver={SQL Server};'
                        + 'Server='+pcodServerName+';' 
                        + 'Database='+pcodDatabaseName+';' 
                        + 'Uid='+pcodUserID+';' 
                        + 'Pwd='+pcodPassword+';'; 

NameCompany := 'DEV Company';

EXIT(ltxtConnectionString);

Step 2. :- Calling the SQL Connection.


IF ISCLEAR(ADOConnection) THEN
  CREATE(ADOConnection);

ADOConnection.ConnectionString := GetLiveConnectionString;

ADOConnection.Open;

Step 3. :- Write the SQL Querry


SQLString := 'select CAST(sum(SIL.Amount) as float) as InvoiceAmount, '
            + '((SUM(SIL.Amount)-SUM(SIL.[Unit Cost (LCY)]*SIL.Quantity))/SUM(SIL.Amount)*100) as GrossProfit '
            + 'from dbo.['+NameCompany+'$Sales Invoice Line] as SIL '
            + 'join dbo.['+NameCompany+'$Sales Invoice Header] as SIH '
            + 'on SIL.[Document No_] = SIH.[No_] '
            + 'where (SIH.[Posting Date] between '+ ConvertedStartDate + ' and ' + ConvertedEndDate + ');';

Step 4. :- Execute the SQL Querry

ADORecordSet := ADOConnection.Execute(SQLString);

Step 5 :- Manuplate if you want the record set if you want the SQL Record Set.

ADORecordSet.MoveFirst;

Step 6 :- Close All Connection and Clear the Variable.


ADORecordSet.Close;
ADOConnection.Close;
CLEAR(ADORecordSet);
CLEAR(ADOConnection);