Sie sind auf Seite 1von 37

SAP Busi ness One

SQL Basi c s
SAP AG 2004
Agenda
Main Parts of a SELECT Statement
Columns and Column Headings
Sorting
Calculation Fields
Grouping and Aggregate Functions
Data Types and Conversion
Conditions with Variables
Joining and Relationships between Tables
Further Helpful Operations for Queries
DISTINCT Function
String Concatenation
String Comparison with LIKE
Numeric Conditions with Ranges
Date Functions
Other String Functions
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)
SAP AG 2004
Busi ness One Spec i f i c s - Tabl e Names
Business One Table Naming Conventions:
Each table name is always 4 letters long
Header (Master) tables start with O (OINV, ORDR, OPCH)
O = Original
Line (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 O
A = Archive
User-defined tables start with @
SAP AG 2004
Quer y Resul t s
Edit Query
Show Query
Save Query
Display Results
graphically
Double-click and
ALT double-click
to sort
CTRL double-click
to display Total
Open a query
Or
Create user
Report for
Printing
SAP AG 2004
Busi ness One Spec i f i c s FOR BROWSE
FOR BROWSE is generated automatically at the end of a query
built by the Query Wizard or the Query Interface
FOR BROWSE means that the result displays the orange arrow to
navigate into the master record or document behind it
The orange arrow is only available for fields that represent keys of a
table
The orange arrow are not shown in queries that contain groupings
The orange arrow are not shown in queries that are based on Archive
tables
SAP AG 2004
St eps t o Cr eat e a User Repor t
1. Save the query result under a certain category
2. Go to Open Saved Query window
3. 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 Reports
6. Select the report and press Print Preview Icon.
SAP AG 2004
Ex por t t he Quer y i nt o Ex c el
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 Icon
3. 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
SAP AG 2004
SELECT St at ement
Display all invoices available with all fields
SQL Syntax
SELECT * from OINV
Display the customer number, the invoice number and the total
invoice amount for all invoices
SQL Syntax
SELECT 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 Syntax
SELECT CardCode as Cust.No., DocNum as Inv.No., DocTotal as Inv.
Total from OINV
SAP AG 2004
SELECT St at ement - Sor t i ng of t he Resul t s
Display all invoice totals sorted by customer number first and then
by Invoice number, sorting should be from lowest to highest value
SQL Syntax
SELECT 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 Syntax
SELECT CardCode as Cust.No., DocNum as Inv.No., DocTotal as Inv.
Total from OINV ORDER BY DocTotal DESC
SAP AG 2004
SELECT St at ement - Cal c ul at i on Fi el ds
Display the invoice total as net value only without VAT
SQL Syntax
SELECT 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 Syntax
SELECT CardCode, DocNum, DocTotal*1.1 as Amount in EUR, DocTotal
from OINV
SAP AG 2004
SQL Synt ax
SAP AG 2004
Ar i t hmet i c Ex pr essi ons
SAP AG 2004
SELECT St at ement - Gr oupi ng
Display one total value of all invoices for each customer. What
happens in this case to the DocNum Column?
SQL Syntax
SELECT 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
SAP AG 2004
Aggr egat e Func t i ons
GROUP BY group_expression
Specifies the groups for output rows
Calculates a summary value for each aggregate function from the
SELECT
With aggregate function
SELECT 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 Functions
AVG Returns the average of the values in the expression
SUM Returns the total of the values
MAX Returns the highest value in the expression
MIN Returns the lowest value in the expression
COUNT Returns the number of rows
SAP AG 2004
I mpor t ant Dat a Types
CHAR
Only alphanumeric characters are allowed
No calculations are possible even if the field contains a number!
In order to do calculations, the datataype has to be converted
When assigning constants or variables to such a field in SQL, single
quotes are required (Cardcode =C100)
NUMBER
Only whole numbers, no decimals
Often 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
FLOAT
These are also numeric values, but with decimal values (1.8734).
Also no quotes are allowed when assigning constants or variables
Same restriction about the string operations apply as for the number
format
SAP AG 2004
I mpor t ant Dat a Types
DATE
Only for dates
Standard 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 statement
SET DATEFORMAT dmy
This way, the dates are always interpreted as dd/mm/yy.
SAP AG 2004
Conver si on of Dat a Types
Date -> String
CONVERT (CHAR, datefield, style)
SELECT CONVERT (CHAR, DocDate, 101) from OINV
101 is the style of the output
Overview of possible styles:
Style Output Style Output
101
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.yy
105
dd-mm-yyyy
5
dd-mm-yy
106
dd mon yyyy
6
dd mon yy
107
mon dd, yyyy
7
mon dd, yy
108
hh:mm:ss
8
hh:mm:ss
110
mm-dd-yyyy
10
mm-dd-yy
111
yyyy/mm/dd
11
yy/mm/dd
112
yyyymmdd
12
yymmdd
113
dd mon yyyy hh:mm:ss:mmm(24h)
114
hh:mi:ss:mmm(24h)
SAP AG 2004
Conver si on of Dat a Types
String -> Date
CONVERT (DATETIME, string, [style])
SELECT CONVERT (DATETIME, 13/10/2003)
SELECT CONVERT (DATETIME, 13/10/2003, 104)
Number / Float -> Char
CONVERT (CHAR(length), numberfield)
SELECT CONVERT (char(5), DocNum) from OINV
Number /Char -> Float
CONVERT (float, expression)
SELECT CONVERT (float, DocNum) from OINV
Float / Char -> Number
CONVERT (INT, expression)
SELECT CONVERT (INT, DocTotal) from OINV
Attention: Decimals will be cut off, not rounded!
SAP AG 2004
Conver si on of Dat a Types
Convert a number into a String
STR (Numeric_Exp, length, decimal)
Numeric can be for example a float or integer expression
Length is total length of the result including decimal point
Decimal is the number of places on the right of the decimal point
Returns a CHAR
SELECT STR(OpenQty, 4, 0) + Pieces
SAP AG 2004
SELECT St at ement - Condi t i ons
Display only those invoices that are USD and have a total greater
than 1000.
SQL Syntax
SELECT 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 Syntax
SELECT T0.CardCode, T0.DocNum, T0.DocTotal, T0.DocCur
FROM OINV T0
WHERE T0.DocCur = [%0]' AND T0.DocTotal > [%1]
Display only invoices in EUR and in USD, no other currencies.
SQL Syntax
SELECT T0.CardCode, T0.DocNum, T0.DocTotal FROM OINV T0
WHERE T0.DocCur = 'USD' OR T0.DocCur = EUR
SAP AG 2004
Usi ng Var i abl es i n Busi ness One
Variables
Variables 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]
SAP AG 2004
Summar y Condi t i ons
WHERE search_condition
Restricts the rows returned from the SELECT
Options:
AND
Both conditions must be true
WHERE CardType = C and Country = Germany
OR
Either one of the conditions must be true
WHERE Country = Italy OR Country = Germany
Using different operators
Equal: =
Not Equal: <>, !=
Greater, Smaller than: >, <, >=, <=
Not Greater, Smaller than: !>, !<
SAP AG 2004
SELECT St at ement - Rel at i onshi ps
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 Syntax
SELECT T0.CardCode, T0.DocNum, T1.ItemCode, T1.Dscription,
T1.LineTotal
FROM INV1 T1 INNER JOIN OINV T0 ON T1.DocEntry = T0.DocEntry
ORDER by T0.DocNum
SAP AG 2004
Sel ec t i on f r om Sever al Tabl es and Rel at i onshi ps
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.Code
Code is the reference between the 2 tables, like CardCode, ItemCode
If 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 field
To join both, you need to convert the numeric into a character or vice
versa:
CAST(T0.DocNum AS VARCHAR) = T1.Ref1
SAP AG 2004
Pr obl ems w i t h Rel at i onshi ps
SAP AG 2004
DI STI NCT Func t i on t o Show Uni que Val ues
Print a list of all customers for which we have invoices in the system
Need 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 Window
Distinct eliminates the duplicate rows thus making the result unique
SQL Syntax
SELECT DISTINCT(CardCode) from OINV
SAP AG 2004
St r i ng Conc at enat i on
Print FOR REVIEW after the Cardcode in the invoice list
This 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 Window
Insert the string after the correct column and add it with the + sign
Only possible for alphanumeric columns!!!
SQL Syntax
SELECT T0.CardCode + ' FOR REVIEW', T0.DocNum, T0.DocTotal FROM
OINV T0
Print FOR REVIEW after the invoice Total in the invoice list
The column as to be converted into a CHAR field first!!
SQL Syntax
SELECT T0.CardCode, T0.DocNum,
CONVERT(CHAR,T0.DocTotal) + ' FOR REVIEW'
FROM OINV T0
SAP AG 2004
St r i ng Compar i son w i t h LI KE
Display all invoices where the customer name starts with M
SQL Syntax
SELECT Cardcode, Cardname, DocNum, DocTotal from OINV
WHERE Cardname LIKE M%
LIKE
Compares if a string matches a certain pattern
CustomerName LIKE Mai%
In Query Wizard: Starts With
CustomerName LIKE %er
In Query Wizard: Ends With
CustomerName LIKE %aier%
In Query Wizard: Contains
CustomerName NOT LIKE A%
In Query Wizard: Does Not Contain
CustomerName LIKE M[ae]ier
CustomerName LIKE M_ier
SAP AG 2004
Numer i c Condi t i ons Wi t h Ranges
Display all invoices with a total between 100 and 10.000
BETWEEN
Specifies a range for numeric values
WHERE Age BETWEEN 10 and 20
WHERE Age NOT BETWEEN 10 and 20
SQL Syntax
SELECT T0.CardCode, T0.DocNum, T0.DocTotal
FROM OINV T0
WHERE (T0.DocTotal >= 100 AND T0.DocTotal <= 10000 )
SAP AG 2004
DATE Func t i on t o Get Todays Dat e
SQL Function to get todays 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
SAP AG 2004
DATE Func t i ons
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 Syntax
SELECT T0.CardCode, T0.CardName, T0.DocNum, T0.DocTotal,
T0.DocDate FROM OINV T0
WHERE DATEDIFF(d, T0.DocDate, getdate())<=10
SAP AG 2004
DATE Func t i ons
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 Syntax
SELECT T0.CardCode, T0.CardName, T0.DocNum, T0.DocTotal,
T0.DocDate, DATEADD(d, 30, T0.DocDate) FROM OINV
SAP AG 2004
Ot her STRI NG Func t i ons
Replace Characters in a String
REPLACE (exp1, exp2, exp3)
Exp1 is the string to be searched
Exp2 is the pattern to search for
Exp3 is the pattern to replace with
Cut a Part out of a String
SUBSTRING (exp, start, length)
Exp is the string to be searched
Start is the character where the substring begins
Length is the length of the substring
SUBSTRING(C00001, 1, 1) -> C
SAP AG 2004
St eps t o Cr eat e a Quer y
1. Get an overview of the data first by using SELECT * on the main table
2. Choose the needed columns; display the foreign keys of other tables that
you need to join
3. 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 results
4. Add the other tables and write/check the join conditions
5. Now replace the foreign key column by the columns needed from the other
tables
6. 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.
SAP AG 2004
Common Er r or s
Date format problems
Applying a string operation to a numeric field
Applying an arithmetic operation to an alphanumeric field
Wrong assignment of constants (usage of quotes)
Forget the blank when using variables
Wrong numbering when using variables
Variable does not match the data type (quotes)
Mixing up the columns from the different tables by assigning the
wrong aliases
SAP AG 2004
Copyr i ght 2004 SAP AG. Al l Ri ght s Reser ved
No 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.

Das könnte Ihnen auch gefallen