consultas sap query 011000358700004861302004e

37
SAP Business One SQL Basics

Upload: cheo-garza

Post on 27-Dec-2015

41 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Consultas SAP Query 011000358700004861302004E

SAP Business One

SQL Basics

Page 2: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Agenda

Main Parts of a SELECT StatementColumns and Column HeadingsSortingCalculation FieldsGrouping and Aggregate FunctionsData Types and ConversionConditions with VariablesJoining and Relationships between Tables

Further Helpful Operations for QueriesDISTINCT FunctionString ConcatenationString Comparison with LIKENumeric Conditions with RangesDate FunctionsOther String Functions

Page 3: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SELECT

Main parts of a SELECT statement:

SELECT column_list

FROM table_list

WHERE search_condition (optional)

GROUP BY group_expression (optional)

ORDER BY order_expression [ASC | DESC] (Optional)

Page 4: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Business One Specifics - Table Names

Business One Table Naming Conventions:Each table name is always 4 letters longHeader (Master) tables start with O (OINV, ORDR, OPCH)O = OriginalLine (Detail) tables use the 3 letters without the O and have a 1 at the end (INV1, RDR1, PCH1)History tables have the same name as the regular tables, but start with A instead of OA = ArchiveUser-defined tables start with @

Page 5: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Query Results

Edit Query

Show Query

Save QueryDisplay Resultsgraphically

Double-click andALT double-clickto sort

CTRL double-clickto display Total

Open a queryOrCreate userReport forPrinting

Page 6: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Business One Specifics – FOR BROWSE

“FOR BROWSE” is generated automatically at the end of a query built by the Query Wizard or the Query InterfaceFOR BROWSE means that the result displays the orange arrow to navigate into the master record or document behind itThe orange arrow is only available for fields that represent keys of a tableThe orange arrow are not shown in queries that contain groupingsThe orange arrow are not shown in queries that are based on Archive tables

Page 7: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Steps to Create a User Report

1. Save the query result under a certain category2. Go to “Open Saved Query” window3. Select the saved query and press <Create Report>4. Enter a report name, select a template and press OK.5. Go to the menu Tools – User Reports6. Select the report and press Print Preview Icon.

Page 8: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Export the Query into Excel

1. Under Administration – System Initialization - General Settings –Path assign the correct path for the Excel docs (must be the directory from the correct Business One Client installation)

2. In the query results window, press the Excel Icon3. Confirm the “Save As” window (the report will be saved under a

subdirectory created for each database)4. Press “Enable Macros” when Excel is coming up

Page 9: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SELECT Statement

Display all invoices available with all fields

SQL SyntaxSELECT * from OINV

Display the customer number, the invoice number and the total invoice amount for all invoices

SQL SyntaxSELECT CardCode, DocNum, DocTotal from OINV

Display the customer number, the invoice number and the total invoice amount for all invoices with predefined column headings for printing

SQL SyntaxSELECT CardCode as ‘Cust.No.’, DocNum as ‘Inv.No.’, DocTotal as ‘Inv. Total’ from OINV

Page 10: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SELECT Statement - Sorting of the Results

Display all invoice totals sorted by customer number first and then by Invoice number, sorting should be from lowest to highest value

SQL SyntaxSELECT CardCode as ‘Cust.No.’, DocNum as ‘Inv.No.’, DocTotal as ‘Inv. Total’ from OINV ORDER BY CardCode, DocNum

Display all invoice totals sorted by total value, with the highest values first

SQL SyntaxSELECT CardCode as ‘Cust.No.’, DocNum as ‘Inv.No.’, DocTotal as ‘Inv. Total’ from OINV ORDER BY DocTotal DESC

Page 11: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SELECT Statement - Calculation Fields

Display the invoice total as net value only without VAT

SQL SyntaxSELECT T0.CardCode, T0.DocNum, T0.DocTotal, T0.VatSum, T0.DocTotal-T0.VatSum as 'Net Amount' FROM OINV T0 ORDER BY T0.DocNum

Select the total invoice amounts in EUR by converting using the rate 1.1

SQL SyntaxSELECT CardCode, DocNum, DocTotal*1.1 as ‘Amount in EUR’, DocTotalfrom OINV

Page 12: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SQL Syntax

Page 13: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Arithmetic Expressions

Page 14: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SELECT Statement - Grouping

Display one total value of all invoices for each customer. What happens in this case to the DocNum Column?

SQL SyntaxSELECT T0.CardCode , COUNT(T0.DocNum), SUM(T0.DocTotal) FROM OINV T0 GROUP BY T0.CardCode

SELECT T0.CardCode , SUM(T0.DocTotal) FROM OINV T0 GROUP BY T0.CardCode

Page 15: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Aggregate Functions

GROUP BY group_expressionSpecifies the groups for output rowsCalculates a summary value for each aggregate function from the SELECT

With aggregate functionSELECT country, city, SUM(revenue) FROM…GROUP BY country, city All columns from the select clause must be in the group by when using aggregate functions!!!Recommended to be used together with an ORDER BY for ordering the output of the columns

Example of Aggregate FunctionsAVG – Returns the average of the values in the expressionSUM – Returns the total of the valuesMAX – Returns the highest value in the expressionMIN – Returns the lowest value in the expressionCOUNT – Returns the number of rows

Page 16: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Important Data Types

CHAROnly alphanumeric characters are allowedNo calculations are possible even if the field contains a number!In order to do calculations, the datataype has to be convertedWhen assigning constants or variables to such a field in SQL, single quotes are required (Cardcode =‘C100’)

NUMBEROnly whole numbers, no decimalsOften used for ID columns (identifying each record uniquely)When assigning constants or variables to a number field, no quotes must be used (DocNum = 1000)String operations cannot be performed directly, the numeric field must first be converted into a character field

FLOATThese are also numeric values, but with decimal values (1.8734).Also no quotes are allowed when assigning constants or variablesSame restriction about the string operations apply as for the number format

Page 17: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Important Data Types

DATEOnly for datesStandard date fields are including time (not in Business One at the moment!!)Many different formats exist!!!American, German, with full year or only 2 digit year…It is always recommended to set the date format at the beginning of the query with the statementSET DATEFORMAT dmyThis way, the dates are always interpreted as dd/mm/yy.

Page 18: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Conversion of Data Types

Date -> StringCONVERT (CHAR, datefield, style)SELECT CONVERT (CHAR, DocDate, 101) from OINV101 is the style of the output

Overview of possible styles:

Style Output Style Output101 mm/dd/yyyy 1 mm/dd/yy 102 yyyy.mm.dd 2 yy.mm.dd 103 dd/mm/yyyy 3 dd/mm/yy 104 dd.mm.yyyy 4 dd.mm.yy105 dd-mm-yyyy 5 dd-mm-yy106 dd mon yyyy 6 dd mon yy107 mon dd, yyyy 7 mon dd, yy108 hh:mm:ss 8 hh:mm:ss110 mm-dd-yyyy 10 mm-dd-yy111 yyyy/mm/dd 11 yy/mm/dd112 yyyymmdd 12 yymmdd113 dd mon yyyy hh:mm:ss:mmm(24h)114 hh:mi:ss:mmm(24h)

Page 19: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Conversion of Data Types

String -> DateCONVERT (DATETIME, string, [style])SELECT CONVERT (DATETIME, ’13/10/2003’)SELECT CONVERT (DATETIME, ’13/10/2003’, 104)

Number / Float -> CharCONVERT (CHAR(length), numberfield)SELECT CONVERT (char(5), DocNum) from OINV

Number /Char -> FloatCONVERT (float, expression)SELECT CONVERT (float, DocNum) from OINV

Float / Char -> NumberCONVERT (INT, expression)SELECT CONVERT (INT, DocTotal) from OINVAttention: Decimals will be cut off, not rounded!

Page 20: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Conversion of Data Types

Convert a number into a StringSTR (Numeric_Exp, length, decimal)Numeric can be for example a float or integer expressionLength is total length of the result including decimal pointDecimal is the number of places on the right of the decimal pointReturns a CHARSELECT STR(OpenQty, 4, 0) + ‘ Pieces’

Page 21: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SELECT Statement - Conditions

Display only those invoices that are USD and have a total greater than 1000.

SQL SyntaxSELECT T0.CardCode, T0.DocNum, T0.DocTotal FROM OINV T0 WHERE T0.DocCur = 'USD' AND T0.DocTotal > 1000

Display only those invoices with a currency and a total greater than a value specified when running the query.

SQL SyntaxSELECT T0.CardCode, T0.DocNum, T0.DocTotal, T0.DocCurFROM OINV T0 WHERE T0.DocCur = ‘[%0]' AND T0.DocTotal > [%1]

Display only invoices in EUR and in USD, no other currencies.

SQL SyntaxSELECT T0.CardCode, T0.DocNum, T0.DocTotal FROM OINV T0 WHERE T0.DocCur = 'USD' OR T0.DocCur = ‘EUR’

Page 22: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Using Variables in Business One

VariablesVariables can be used in order to complete the condition of the WHERE clause at runtime.The variable is the placeholder for a value entered when executing the query.Variables are numbered sequentially starting with zero.Examples:

WHERE CardType = ‘[%0]’WHERE PostingDate >= ‘[%1]’ AND PostingDate <= ‘[%2]’

Page 23: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Summary Conditions

WHERE search_conditionRestricts the rows returned from the SELECT

Options:AND

Both conditions must be trueWHERE CardType = ‘C’ and Country = ‘Germany’

OREither one of the conditions must be trueWHERE Country = ‘Italy’ OR Country = ‘Germany’

Using different operatorsEqual: =Not Equal: <>, !=Greater, Smaller than: >, <, >=, <=Not Greater, Smaller than: !>, !<

Page 24: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

SELECT Statement - Relationships

Display Cardcode and invoice number also the invoice rows (row number and line amount) and show the item code and item description of each row.

SQL SyntaxSELECT T0.CardCode, T0.DocNum, T1.ItemCode, T1.Dscription, T1.LineTotal FROM INV1 T1 INNER JOIN OINV T0 ON T1.DocEntry = T0.DocEntryORDER by T0.DocNum

Page 25: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Selection from Several Tables and Relationships

FROM table_list

Options:Specific tables

FROM table1 T0, table2 T1 Business One always starts with T0 when numbering the tables

With Join Operation FROM table1 T0 INNER JOIN table2 T1 ON T0.Code = T1.CodeCode is the reference between the 2 tables, like CardCode, ItemCodeIf the data types of the reference are not compatible to each other, one of them needs to be converted.For example: DocNum is a numeric and Ref1 is a character fieldTo join both, you need to convert the numeric into a character or vice versa:CAST(T0.DocNum AS VARCHAR) = T1.Ref1

Page 26: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Problems with Relationships

Page 27: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

DISTINCT Function to Show Unique Values

Print a list of all customers for which we have invoices in the systemNeed an expression to select unique values only: DISTINCT (column)This expression is not supported by the Query Wizard.It has to be added manually in front of the column after creating the query with the Wizard.In the Query Analyzer, it can be added in front of the column in the Selection List WindowDistinct eliminates the duplicate rows thus making the result uniqueSQL Syntax

SELECT DISTINCT(CardCode) from OINV

Page 28: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

String Concatenation

Print “FOR REVIEW” after the Cardcode in the invoice listThis operation is not supported by the Query Wizard.It has to be done manually after creating the query with the Wizard.In the Query Analyzer, it can be added between the columns in the Selection List WindowInsert the string after the correct column and add it with the ‘+’ signOnly possible for alphanumeric columns!!!

SQL SyntaxSELECT T0.CardCode + ' FOR REVIEW', T0.DocNum, T0.DocTotal FROM OINV T0

Print “FOR REVIEW” after the invoice Total in the invoice listThe column as to be converted into a CHAR field first!!

SQL SyntaxSELECT T0.CardCode, T0.DocNum, CONVERT(CHAR,T0.DocTotal) + ' FOR REVIEW' FROM OINV T0

Page 29: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

String Comparison with LIKE

Display all invoices where the customer name starts with MSQL Syntax

SELECT Cardcode, Cardname, DocNum, DocTotal from OINVWHERE Cardname LIKE ‘M%’

LIKECompares if a string matches a certain patternCustomerName LIKE ‘Mai%’

In Query Wizard: Starts WithCustomerName LIKE ‘%er’

In Query Wizard: Ends WithCustomerName LIKE ‘%aier%’

In Query Wizard: ContainsCustomerName NOT LIKE ‘A%’

In Query Wizard: Does Not ContainCustomerName LIKE ‘M[ae]ier’CustomerName LIKE ‘M_ier’

Page 30: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Numeric Conditions With Ranges

Display all invoices with a total between 100 and 10.000

BETWEENSpecifies a range for numeric valuesWHERE Age BETWEEN 10 and 20WHERE Age NOT BETWEEN 10 and 20

SQL SyntaxSELECT T0.CardCode, T0.DocNum, T0.DocTotalFROM OINV T0WHERE (T0.DocTotal >= 100 AND T0.DocTotal <= 10000 )

Page 31: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

DATE Function to Get Today’s Date

SQL Function to get today’s date:GETDATE()Needed in conditions based on the system date

Can be used in the selection list or in conditions(just like any other date expression)Returns the current system date at execution of the query with date and time

Page 32: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

DATE Functions

SQL Function to calculate the difference between two dates:DATEDIFF(datepart, startdate, enddate)Datepart specifies on which part of the date to calculate the difference(for example year, month or day)Start date is subtracted from end date. If start date is later than end date, a negative value is returned

Display all invoices from the last 10 days

SQL SyntaxSELECT T0.CardCode, T0.CardName, T0.DocNum, T0.DocTotal, T0.DocDate FROM OINV T0 WHERE DATEDIFF(d, T0.DocDate, getdate())<=10

Page 33: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

DATE Functions

SQL Function to determine a date in the future based:DATEADD(datepart, number, date)Datepart specifies on which part of the date a new value should be added(for example year, month or day)Number specifies the value used to increment datepart.

Display the invoices and create a due date by adding 30 days to the DocDate for all invoices

SQL SyntaxSELECT T0.CardCode, T0.CardName, T0.DocNum, T0.DocTotal, T0.DocDate, DATEADD(d, 30, T0.DocDate) FROM OINV

Page 34: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Other STRING Functions

Replace Characters in a StringREPLACE (exp1, exp2, exp3)Exp1 is the string to be searchedExp2 is the pattern to search forExp3 is the pattern to replace with

Cut a Part out of a StringSUBSTRING (exp, start, length)Exp is the string to be searchedStart is the character where the substring beginsLength is the length of the substringSUBSTRING(‘C00001’, 1, 1) -> ‘C’

Page 35: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Steps to Create a Query

1. Get an overview of the data first by using SELECT * on the main table2. Choose the needed columns; display the foreign keys of other tables that

you need to join3. Add the conditions; at the beginning, always add a condition to limit the

query first to one customer, invoice etc. in order to check the results4. Add the other tables and write/check the join conditions5. Now replace the foreign key column by the columns needed from the other

tables6. If you need variables, always use constant values first to check the result

and as the last step, replace the constants with the variables

Things to Check:Could the condition include NULL values?Make sure that there is no Cartesian product, for example by counting the rows of the result.Always use examples where you know the data (add this as constants to the condition) so that you can check if the result is correct.

Page 36: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Common Errors

Date format problemsApplying a string operation to a numeric fieldApplying an arithmetic operation to an alphanumeric fieldWrong assignment of constants (usage of quotes)Forget the blank when using variablesWrong numbering when using variablesVariable does not match the data type (quotes)Mixing up the columns from the different tables by assigning thewrong aliases

Page 37: Consultas SAP Query 011000358700004861302004E

© SAP AG 2004

Copyright 2004 SAP AG. All Rights ReservedNo part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice.Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors.Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, and Informix are trademarks or registered trademarks of IBM Corporation in the United States and/or other countries.Oracle is a registered trademark of Oracle Corporation.UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc.HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Java is a registered trademark of Sun Microsystems, Inc.JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. MaxDB is a trademark of MySQL AB, Sweden.SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary.These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.