Top Banner
User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries
26

Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Jun 20, 2018

Download

Documents

phungnguyet
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

User Guide Document Version: 2013-02-28

PARTNER

Best Practices of SQL in the SAP HANA Database All Countries

Page 2: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

2 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database Typographic Conventions

Typographic Conventions

Type Style Description

Example Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options.

Textual cross-references to other documents.

Example Emphasized words or expressions.

EXAMPLE Technical names of system objects. These include report names, program names, transaction codes, table names, and key concepts of a programming language when they are surrounded by body text, for example, SELECT and INCLUDE.

Example Output on the screen. This includes file and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools.

Example Exact user entry. These are words or characters that you enter in the system exactly as they appear in the documentation.

<Example> Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system.

EXAMPLE Keys on the keyboard, for example, F2 or ENTER .

Page 3: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database Table of Contents

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 3

Table of Contents

1 Introduction ................................................................................................................................................... 4

2 Data Types ....................................................................................................................................................... 5

3 Predicates, Operators, and Expressions ..................................................................................................... 7

4 SQL Functions ................................................................................................................................................. 8 4.1 String Functions ....................................................................................................................................................... 8 4.2 Math Functions ........................................................................................................................................................ 9 4.3 Date Functions ....................................................................................................................................................... 10 4.4 Conversion Functions ............................................................................................................................................ 14 4.5 Other Functions ..................................................................................................................................................... 16

5 SQL Statements ........................................................................................................................................... 17

6 Stored Procedures ....................................................................................................................................... 19

7 Performance ..................................................................................................................................................22

Page 4: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

4 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database Introduction

1 Introduction

This user guide provides best practices of SQL usage for SAP Business One, version for SAP HANA add-ons. The add-ons include those migrated from SAP Business One in the Microsoft SQL Server database, and those newly-developed for SAP Business One, version for SAP HANA.

The best practices of SQL usage provided are as follows:

• Best practices for migrating SQL statements and scripts from the Microsoft SQL Server database to the SAP HANA database, including the mapping of data types and functions

• Best practices of special SQL grammar in SAP HANA, for example, stored procedure, cursor, temporary table, and so on.

• Best practices for achieving optimal performance in SAP HANA

SQL in SAP Business One, version for SAP HANA add-ons include all SQL statements and scripts that you use either in the SAP HANA database or in the add-on codes. The following are some examples:

• Query passed to the Recordset.DoQuery (string QueryStr) method

• Query passed to the DataTable.ExecuteQuery (string QueryStr) method

• User-defined queries

• Stored procedure called by the Recordset.Command.Execute method

• Transaction Notification stored procedure

• Queries and stored procedures called by add-on codes via ODBC/JDBC

For more information about SQL usage in SAP HANA, see SAP HANA SQL Reference and SAP HANA SQL Script Reference on SAP Help Portal at http://help.sap.com/hana_appliance.

Page 5: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database Data Types

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 5

2 Data Types

This section describes best practices for data types.

Topic Description

Converting NVARCHAR(max) to NVARCHAR(n)

You must convert data type NVARCHAR(max) in the Microsoft SQL Server database to NVARCHAR(n) so that it can run successfully in the SAP HANA database, because there is no data type in SAP HANA with a large storage size that at the same time can provide functions such as string comparison.

Unicode string identifier

When a unicode string is preceded by an N identifier (N stands for National Language in the SQL-92 standard), the N prefix must be in uppercase.

Example

SELECT 'Brian' "character string 1", '100' "character string 2", N'abc' "unicode string" FROM DUMMY

Mapping of data types between the Microsoft SQL Server database and the SAP HANA database

Data Type Category Data Type in MS SQL Server Data Type in SAP HANA

Exact numerics bigint bigint

bit tinyint

decimal decimal

int integer

numeric decimal

smallint smallint

smallmoney smalldecimal

money decimal

tinyint tinyint

Approximate numerics float float

real real

Date and time date date

datetime2 timestamp

datetime timestamp

datetimeoffset N/A

smalldatetime seconddate

time time

Character strings char char

Page 6: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

6 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database Data Types

Topic Description

varchar varchar

text text

Unicode character strings

nchar nchar

nvarchar nvarchar

ntext nclob

Binary strings binary binary

varbinary varbinary

image blob

Other Data Types cursor cursor

timestamp timestamp

hierarchyid N/A

uniqueidentifier nvarchar

sql_variant N/A

xml N/A

table N/A

Page 7: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database Predicates, Operators, and Expressions

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 7

3 Predicates, Operators, and Expressions

This section describes best practices for predicates, operators, and expressions.

Topic Description

Rounding on arithmetic calculation

The default rounding methods in the Microsoft SQL Server database and in the SAP HANA database are different.

Example

SELECT 1/2 FROM DUMMY will return different results in the two databases.

In the SAP HANA database, it will return 0.5.

In the Microsoft SQL Server database, it will return 0.

To round the result accordingly, use functions such as FLOOR and CEILING.

String concatenation To connect two or more strings, use the '||' operator.

Example

SELECT ‘Hello ‘ || ‘World!’ FROM DUMMY

Variable assignment To assign a value to a variable in stored procedures, use ':='.

Variable reference To reference a variable in stored procedures, use ':' before the variable symbol.

Example

Create Procedure DemoProc1

AS

NUMBER INTEGER := 10;

BEGIN SELECT TOP :NUMBER "DocEntry" FROM OINV;

END;

Page 8: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

8 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database SQL Functions

4 SQL Functions

This section describes best practices for SQL functions.

Note

Values in square brackets ("[]") are alternative strings that can be used within the function.

4.1 String Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

ASCII (s) ASCII (s) ASCII ('A') ASCII ('A')

CHAR (n) CHAR (n) CHAR (5) CHAR (5)

CONCAT (str1, str2) str1 + str2 CONCAT ('wt', 'f') 'wt' + 'f'

LEFT (str, n) LEFT (str, n) LEFT ('xyz', 1) LEFT ('xyz', 1)

LCASE (str) LOWER (str) LCASE ('XYZ') LOWER ('XYZ')

LENGTH (str) LEN (str) LENGTH ('xyz') LEN ('xyz')

LOCATE (expressionToSearch, expressionToFind)

CHARINDEX (expressionToFind ,expressionToSearch [, start_location ])

LOCATE ('length in char', 'char')

CHARINDEX ('char', 'length in char')

LOWER (str) LOWER (str) LOWER ('XYZ') LOWER ('XYZ')

LPAD (str, n [, pattern])

N/A LPAD ('end', 15, '12345')

N/A

LTRIM (str [, remove_set])

LTRIM (str) LTRIM ('xyz') LTRIM ('xyz')

NCHAR (n) NCHAR (n) NCHAR (123) NCHAR (123)

REPLACE (original_string, search_string, replace_string)

REPLACE (original_string, search_string, replace_string)

REPLACE ('DOWNGRADE DOWNWARD', 'DOWN', 'UP')

REPLACE ('DOWNGRADE DOWNWARD', 'DOWN', 'UP')

RIGHT (str, n) RIGHT (str, n) RIGHT ('HI0123456789', 3)

RIGHT ('HI0123456789', 3)

RPAD (str, n [, N/A RPAD ('end', 15, N/A

Page 9: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database SQL Functions

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 9

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

pattern]) '12345')

RTRIM (str [, remove_set])

RTRIM (str) RTRIM ('xyz') RTRIM ('xyz')

SUBSTRING (target, start_position [, string_length])

SUBSTRING (target, start_position, string_length)

SUBSTRING ('1234567890', 4, 2)

SUBSTRING ('1234567890', 4, 2)

SUBSTR_AFTER (str, pattern)

N/A SUBSTR_AFTER ('Hello My Friend', 'My')

N/A

SUBSTR_BEFORE (str, pattern)

N/A SUBSTR_BEFORE ('Hello My Friend', 'My')

N/A

TRIM ([[LEADING | TRAILING | BOTH] trim_char FROM] target_string)

LTRIM (RTRIM(str)) TRIM ('abc') LTRIM (RTRIM ('abc'))

UCASE (target) UPPER (target) UCASE ('abc') UPPER ('abc')

UNICODE (c) UNICODE (c) UNICODE ('#') UNICODE ('#')

UPPER (target) UPPER (target) UPPER ('abc') UPPER ('abc')

4.2 Math Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

ABS (n) ABS (n) ABS (-1), ABS (-1),

ABS (7.0) ABS (7.0)

ACOS (n) ACOS (n) ACOS (0), ACOS (0),

ACOS (1) ACOS (1)

ASIN (n) ASIN (n) ASIN (0.14), ASIN (0.14),

ASIN (-1) ASIN (-1)

ATAN (n) ATAN (n) ATAN (-45.1), ATAN (-45.1),

ATAN (197) ATAN (197)

ATAN2 (n, m) ATN2 (n, m) ATAN2 (35.175643, 129)

ATAN2 (35.175643, 129)

BITAND (n, m) N/A BITAND (255, 123) N/A

CEIL (n) CEILING (n) CEILING (14.5) CEILING (14.5)

Page 10: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

10 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database SQL Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

COS (n) COS (n) COS (14.78) COS (14.78)

COSH (n) N/A COSH (0.5) N/A

COT (n) COT (n) COT (124.13) COT (124.13)

EXP (n) EXP (n) EXP (1) EXP (1)

FLOOR (n) FLOOR (n) FLOOR (14.5) FLOOR (14.5)

GREATEST (n1 [, n2]...)

N/A GREATEST ('aa', 'ab', 'ba', 'bb')

N/A

LEAST (n1 [, n2]...)

N/A LEAST ('aa', 'ab', 'ba', 'bb')

N/A

LN (n) LOG (n) LN (9) LOG (9)

LOG (b, n) N/A LOG (10, 2) N/A

MOD (n, d) N/A MOD (15, 4) N/A

POWER (n, y) POWER (n, y) POWER (2, 10) POWER (2, 10)

4.3 Date Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

ADD_DAYS (d, n) DATEADD (day [/ dd / d], n, datetime)

ADD_DAYS ('1.1.2012', 4)

DATEADD (day [/ dd / d], 4, '1.1.2012')

ADD_MONTHS (d, n)

DATEADD (month [/ mm / m], n, datetime)

ADD_MONTHS ('1.1.2012', 4)

DATEADD (month [/ mm / m], 4, '1.1.2012')

ADD_YEARS (d, n) DATEADD (year [/ yy / yyyy], n, datetime)

ADD_YEARS ('1.1.2012', 4)

DATEADD (year [/ yy / yyyy], 4, '1.1.2012')

ADD_SECONDS (t, n)

DATEADD(second [/ ss / s], n, datetime)

ADD_SECONDS ('23:30:45', 30)

DATEADD(second [/ ss / s], 4, GETDATE())

DAYS_BETWEEN (date1, date2)

DATEDIFF (day [/ dd / d], startdate, enddate)

DAYS_BETWEEN ('01-01-2012', CURRENT_TIMESTAMP)

DATEDIFF (day [/ dd / d], '1.1.2012', GETDATE())

DAYNAME (date) DATENAME (weekday [/ dw], date)

DAYNAME (CURRENT_TIMESTAMP)

DATENAME (weekday [/ dw*],* GETDATE())

DAYOFMONTH DATEPART (day [/ DAYOFMONTH DATEPART (day [/ dd /

Page 11: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database SQL Functions

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 11

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

(date) dd / d], date), (CURRENT_TIMESTAMP) d], GETDATE()),

DAY (date) DAY ('01.01.2012')

DAYOFYEAR (date) DATEPART (dayofyear [/ dy / y], date)

DAYOFYEAR (CURRENT_TIMESTAMP)

DATEPART (dayofyear [/ dy / y], GETDATE())

EXTRACT ([YEAR | MONTH | DAY | HOUR | MINUTE | SECOND] FROM datetime_value)

DATEPART (datepart, date)

EXTRACT (HOUR FROM CURRENT_TIMESTAMP)

DATEPART (HOUR, GETDATE())

HOUR (expression)

DATEPART (hour [/ hh], time)

HOUR ('12:34:56‘) DATEPART (HOUR [/ hh], '12:34:56')

LAST_DAY (date) DATEADD (dd, -DAY (DATEADD (m, 1, date)),

LAST_DAY (TO_DATE ('2010-01-04', 'YYYY-MM-DD'))

DATEADD (dd, -DAY (DATEADD (m, 1, GETDATE())),

DATEADD (m, 1, date))

DATEADD (m, 1, GETDATE()))

MINUTE (exp) DATEPART (minute [/ mi / m], time)

MINUTE ('12:34:56‘) DATEPART (minute [/ mi / m], '12:32:43')

MONTH (date) DATEPART (month [/ mm / m], date),

MONTH ('1.1.2012') DATEPART (month [/ mm / m], '01.01.2012'),

MONTH (date) MONTH ('01.01.2012')

MONTHNAME (date) DATENAME (month [/ mm / m], date)

MONTHNAME ('1.1.2012‘)

DATENAME (month [/ mm / m], '01.01.2012')

NEXT_DAY (date) CONVERT (VARCHAR, DATEADD (DAY, +1, GETDATE()), 23)

NEXT_DAY ('2009-12-31')

CONVERT (VARCHAR, DATEADD (DAY, +1, GETDATE()), 23)

NOW () CURRENT_TIMESTAMP, NOW () CURRENT_TIMESTAMP,

GETDATE () GETDATE ()

SECOND (date) DATEPART (second [/ ss / s], GETDATE ())

SECOND (‘12:34:56‘) DATEPART (second [/ ss / s], GETDATE ())

SECONDS_BETWEEN (d1, d2)

DATEDIFF (second [/ ss / s], startdate, enddate)

SECONDS_BETWEEN ('2009-12-05', '2010-01-05')

DATEDIFF (second [/ ss / s], startdate, enddate)

CURRENT_DATE CONVERT (date, GETDATE ()),

CURRENT_DATE CONVERT (date, GETDATE ())

CONVERT (date,

Page 12: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

12 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database SQL Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

SYSDATETIME ()),

CONVERT (date, SYSDATETIMEOFFSET ()),

CONVERT (date, CURRENT_TIMESTAMP)

Note

For Microsoft SQL Server 2005, you can only use CONVERT (datetime, GETDATE ()), and CONVERT (datetime, CURRENT_TEIMSTANP).

CURRENT_TIME CONVERT (time, GETDATE ()),

CURRENT_TIME CONVERT (time, GETDATE ())

CONVERT (time, SYSDATETIME ()),

CONVERT (time, SYSDATETIMEOFFSET ()),

CONVERT (time, CURRENT_TIMESTAMP)

Note

For Microsoft SQL Server 2005, you can only use CONVERT (datetime, GETDATE ()), and CONVERT (datetime, CURRENT_TEIMSTANP).

CURRENT_TIMESTAMP

CURRENT_TIMESTAMP, CURRENT_TIMESTAMP CURRENT_TIMESTAMP,

GETDATE () GETDATE ()

Page 13: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database SQL Functions

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 13

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

CURRENT_UTCDATE CONVERT (date, GETUTCDATE ()),

CURRENT_UTCDATE CONVERT (date, GETUTCDATE ())

CONVERT (date, SYSUTCDATETIME ())

Note

For Microsoft SQL Server 2005, you can only use CONVERT (datetime, GETDATE ()), and CONVERT (datetime, CURRENT_TEIMSTANP).

CURRENT_UTCTIME CONVERT (time, GETUTCDATE ()),

CURRENT_UTCTIME CONVERT (time, GETUTCDATE ())

CONVERT (time, SYSUTCDATETIME ())

Note

For Microsoft SQL Server 2005, you can only use CONVERT (datetime, GETDATE ()), and CONVERT (datetime, CURRENT_TEIMSTANP).

CURRENT_UTCTIMESTAMP

GETUTCDATE () CURRENT_UTCTIMESTAMP

GETUTCDATE ()

WEEK (d) DATEPART (week [/ wk / ww], date)

WEEK ('2012-07-25') DATEPART (week [/ wk / ww], '2012-07-25')

WEEKDAY (date) DATEPART (dw, date)

WEEKDAY ('2012-07-25') + 1

DATEPART (dw, '2012-07-25')

YEAR (date) DATEPART (yyyy [/ yy], date),

YEAR ('2012-07-25') DATEPART (yyyy [/ yy], '2012-07-25'),

Page 14: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

14 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database SQL Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

YEAR (date) YEAR ('2012-07-25')

4.4 Conversion Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

CAST (expression AS data_type)

CAST (expression AS data_type)

CAST ('10' AS int) CAST ('10' AS int)

TO_ALPHANUM (exp) CAST (exp AS char [(n)]),

TO_ALPHANUM ('xyz') CAST ('XYZ' AS char (3)),

CONVERT (char [(n)], exp)

CONVERT (char (3), 'xyz')

TO_BIGINT (exp) CAST (exp AS bigint),

TO_BIGINT ('11) CAST ('11' AS bigint),

CONVERT (bigint, exp)

CONVERT (bigint, '11')

TO_BLOB (expression) CAST (expresion AS varbinary (max)),

TO_BLOB ('expression')

CAST ('hhh' AS varbinary (max)),

CONVERT (varbinary (max), expression [, style])

CONVERT (varbinary (max), 'miso')

TO_CLOB (expression [, format])

CAST (expresion AS varchar (max)),

TO_CLOB ('xxx') CAST ('qqqq' as varchar (max)),

CONVERT (varchar (max), expression [, style])

CONVERT (varchar (max), CAST ('qqq' AS Date), 105)

TO_DATE (expression [, format])

CAST (exp AS date), TO_DATE ('20120730', 'yyyymmdd')

CAST ('20120730' as date),

CONVERT (date, exp [, style ])

CONVERT (date, '20120730', 112)

TO_DATS (exp) CONVERT (VARCHAR, CAST (exp AS date), 112)

TO_DATS ('2010-01-12')

CONVERT (VARCHAR, CAST ('2012-01-01' AS date), 112)

TO_DECIMAL (exp [, precision, scale])

CAST (exp AS DECIMAL [(precision, scale)]),

TO_DECIMAL ('1.2', 5, 4)

CAST ('1.2' AS DECIMAL (5, 4)),

CONVERT (DECIMAL CONVERT

Page 15: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database SQL Functions

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 15

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

[(precision, scale)], exp)

(DECIMAL(5,4), '1.2')

TO_DOUBLE (exp) CAST (exp AS float),

TO_DOUBLE ('1.2') CAST ('1.2' AS float),

CONVERT (float, exp)

CONVERT (float, '1.2')

TO_INT (exp) CAST (exp AS int), TO_INT ('10') CAST (10 AS int),

CONVERT (int, exp) CONVERT (int, 10)

TO_INTEGER (exp) CAST (exp AS int), TO_INTEGER ('10') CAST (10 AS int),

CONVERT (int, exp) CONVERT (int, 10)

TO_NCLOB (expression)

CAST (expresion AS nvarchar (max)),

TO_NCLOB ('xxx'), CAST ('1.1.2008' as nvarchar (max)),

CONVERT ( nvarchar (max) , expression [ , style])

CONVERT (nvarchar (max), CAST ('1.1.2008' AS Date), 105)

TO_NVARCHAR (expression [, format])

CAST (expresion AS nvarchar [(n)]),

TO_NVARCHAR ('1.1.2008', 'dd/mm/yyyy')

CAST ('1.1.2008' as nvarchar),

CONVERT ( nvarchar [(n)] , expression [, style])

CONVERT (nvarchar, CAST ('1.1.2008' AS Date), 105)

TO_REAL (exp) CAST (exp AS real), TO_REAL ('10.2') CAST ('10.2' AS real),

CONVERT (real, exp) CONVERT (real, '10.2')

TO_SMALLINT (exp) CAST (exp AS smallint),

TO_SMALLINT ('10') CAST (10 AS smallint),

CONVERT (smallint, exp)

CONVERT (smallint, 10)

TO_TINYINT (exp) CAST (exp AS tinyint),

TO_TINYINT ('10') CAST (10 AS tinyint),

CONVERT (tinyint, exp)

CONVERT (tinyint, 10)

TO_TIME (expression [, format])

CAST (exp AS TIME), TO_TIME ('08:30 AM', 'HH:MI AM')

CAST ('3:3' AS TIME),

CONVERT (time,exp) CONVERT (time, '3:3')

TO_TIMESTAMP CAST (expression AS TO_TIMESTAMP CAST ('1.1.2008

Page 16: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

16 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database SQL Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

(expression [, format])

DATETIME), ('2010-01-11 13:30:00', 'YYYY-MM-DD HH24:MI:SS')

12:34:56.54' AS DATETIME),

CONVERT (DATETIME, expression [, style])

CONVERT (datetime, '04 Nov 2011 11:45:34:243', 113)

TO_VARCHAR (expression [, format])

CAST (expression AS varchar),

TO_VARCHAR ('1.1.2008', 'dd/mm/yyyy')

CAST ('1.1.2008' as varchar),

CONVERT ( varchar, expression [, style])

CONVERT (varchar, CAST ('1.1.2008' AS Date), 105)

4.5 Other Functions

Format in SAP HANA Format in MS SQL Example in SAP HANA Example in MS SQL

COALESCE (expression_list)

COALESCE (expression [ ,...n])

COALESCE (null, 50) COALESCE (null, 50)

NULLIF (exp1, exp2)

NULLIF (exp1, exp2)

NULLIF ('diff', 'same')

NULLIF ('diff', 'same')

CURRENT_SCHEMA db_name () select CURRENT_SCHEMA from DUMMY

select db_name ()

CURRENT_USER SUSER_NAME (), SELECT CURRENT_USER from DUMMY

SELECT SUSER_NAME (),

CURRENT_USER SELECT CURRENT_USER

GROUPING_ID (column_name_list)

GROUPING_ID(column_name_list)

SELECT customer, year, product, SUM (sales), GROUPING_ID (customer, year, product) FROM guided_navi_tab GROUP BY GROUPING SETS ((customer, year, product), (customer, year), (customer, product), (year, product), (customer), (year), (product));

SELECT customer, year, product, SUM (sales), GROUPING_ID (customer, year, product) FROM guided_navi_tab GROUP BY GROUPING SETS ((customer, year, product), (customer, year), (customer, product), (year, product), (customer), (year), (product));

Page 17: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database SQL Statements

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 17

5 SQL Statements

This section describes best practices for SQL statements.

Topic Description

Table names and field names in statements

For table names and field names that contain lower case letters, add double quotation marks.

Example

SELECT "FieldId" FROM CUFD WHERE "AliasID" = 'CorrType'

User-defined table names in statements

To create a schema/table/column name that begins with a digit or some special character, such as '@', you must add double quotation marks to the name. In SQL statements, you must add double quotation marks to all user-defined table names.

Example

SELECT "U_String" FROM "@BCENOTE"

create schema "100_TEST_SCHEMA";

create table "100_TEST_TAB" ("@COL1" INT);

CREATE TABLE AS In the Microsoft SQL Server database, you use the SELECT INTO statement, while in the SAP HANA database, you use the CREATE TABLE AS statement.

Example

In the Microsoft SQL Server database, you write: SELECT * INTO T1 FROM T2

In the SAP HANA database, you write: CREATE TABLE T1 AS (SELECT * FROM T2)

FROM DUMMY If there is no FROM clause in the statement,, use FROM DUMMY.

Example

SELECT 'B1' FROM DUMMY;

Query order SAP HANA is a unicode database. For varchar, and nvarchar column types, SAP HANA currently supports only one collation.

Example

Running the following sets of statements in the SAP HANA database and the Microsoft SQL Server database returns different results.

Run the following in the SAP HANA database:

drop table test_order;

create column table test_order (id integer, name nvarchar(100));

Page 18: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

18 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database SQL Statements

Topic Description

insert into test_order values (1,N'China');

insert into test_order values (2,N'canada');

insert into test_order values (3,N'america');

insert into test_order values (4,N'Ausstralia');

select *, UNICODE(name) from test_order order by 2

Run the following in the Microsoft SQL Server database:

drop table test_order;

create table test_order(id integer, name nvarchar(100) collate Latin1_Genaral_CS_AI);

insert into test_order values (1,N'China');

insert into test_order values (2,N'canada');

insert into test_order values (3,N'america');

insert into test_order values (4,N'Australia');

select *, UNICODE(name) from test_order order by 2

Statements in temporary tables

In SAP HANA Platform Edition 1.0 SP4 Rev41, you cannot perform certain operations in column-based temporary tables.

Example

In column-based temporary tables, the following commands will fail.

create local temporary column table #local_column_test(col1 int);

insert into #local_column_test values(1);

update #local_column_test set col1 = 2;--this feature is not supported

delete from #local_column_test;--this feature is not supported

truncate table #local_column_test;

drop table #local_column_test;

However, in row-based temporary tables, there are no such restrictions. The following commands can run successfully.

create local temporary row table #local_row_test(col1 int);

insert into #local_row_test values(1);

update #local_row_test set col1 = 2;

delete from #local_row_test;

truncate table #local_row_test;

drop table #local_row_test;

Page 19: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database Stored Procedures

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 19

6 Stored Procedures

This section describes best practices for stored procedures.

Topic Description

IF and ENDIF In stored procedures, when there is an IF, you must add an END IF.

Example

CREATE PROCEDURE IF_ELSE_IF_TEST(in id INT)

LANGUAGE SQLSCRIPT

AS

cnt INT := 1;

BEGIN

SELECT COUNT(*) INTO cnt FROM SINF;

IF :cnt = 1

THEN SELECT 'cnt == 1' FROM DUMMY;

ELSE IF :cnt = 2

THEN SELECT 'cnt == 2' FROM DUMMY;

ELSE IF :cnt = 3

THEN SELECT 'cnt == 3' FROM DUMMY;

ELSE

SELECT 'cnt <>1,2,3' FROM DUMMY;

END IF;

END IF;

END IF;

END;

You can also use IF-ELSEIF-ELSE-END IF as in the following example.

Example

create procedure p1(in idx int)

as begin

if :idx = 1 then

select 1 from dummy;

elseif :idx = 2 then

select 2 from dummy;

else

select 100 from dummy;

end if;

Page 20: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

20 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database Stored Procedures

Topic Description

end;

Table variable You can use table variables in stored procedures.

Example

Create Procedure DemoProc

AS

BEGIN

v_table1 = SELECT "DocEntry" FROM OINV;

v_table2 = SELECT "DocEntry" FROM ORIN;

v_Out =CE_UNION_ALL(:v_table1, :v_table2);

SELECT * FROM :v_Out;

END;

Dynamic strings of schema names

In stored procedures, if you want to concatenate a dynamic SQL statement with a schema name, you must enclose the schema name with double quotation marks, because the schema name may be case sensitive or begin with numbers.

Example

SELECT count(*) into ctmp FROM sys.views WHERE view_name = 'SRI1_LINK' AND "SCHEMA_NAME" = CURRENT_SCHEMA;

IF ctmp > 0 then

exec('DROP VIEW ' || '"'|| CURRENT_SCHEMA || '"' || '.SRI1_LINK');

end if;

EXEC In a stored procedure, if you cannot compile a statement because some object (table, view, or type) does not exist when the stored procedure is being compiled, use EXEC in the statement.

Example

View V1 may not exist when the stored procedure is being compiled. If you use drop view v1, the stored procedure cannot be compiled. You must use exec ('drop view v1') instead.

Cursor Example

CREATE PROCEDURE sp_cursor_test

language sqlscript

AS

ItemCode nvarchar (20);

BatchNum nvarchar (32);

WhsCode nvarchar ;

CURSOR Currs for

select "ItemCode","BatchNum","WhsCode"

Page 21: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database Stored Procedures

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 21

Topic Description

from OIBT;

begin

create local temporary table #t1 ("ItemCode" nvarchar(100));

Open Currs;

Fetch Currs Into ItemCode,BatchNum,WhsCode;

While not Currs::NOTFOUND do

insert into #t1 values (ItemCode);

Fetch Currs Into ItemCode,BatchNum,WhsCode;

end while;

select * from #t1;

Close Currs;

drop table #t1;

end;

Page 22: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

22 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database Performance

7 Performance

This section describes best practices for achieving optimal performance in SAP HANA. The information is mainly quoted from the following two guides. For more information, see detailed descriptions in the two guides.

• SAP HANA™ Database - Development Guide Beta Preview - How to Use SQL and SQLScript for Data Modeling

• SAP HANA SQL Script Reference on SAP Help Portal at http://help.sap.com/hana_appliance.

Topic Description

Columnar and row-based data storage

Database programmers have to understand the advantages and disadvantages of both storage techniques in order to find a suitable balance.

Column-based tables have advantages in the following circumstances:

• Calculations are typically executed on single columns or on only a few columns.

• The table is searched based on the values of a few columns.

• The table has a large number of columns.

• The table has a large number of rows, and columnar operations are required (aggregate, scan, and so on).

• High compression rates can be achieved because the majority of the columns contain only a few distinct values (compared to the number of rows).

Row-based tables have advantages in the following circumstances:

• The application needs to process only a single record at one time (many selects and/or updates of single records).

• The application typically needs to access a complete record (or row).

• The columns contain mainly distinct values so that the compression rate would be low.

• Neither aggregations nor fast searching are required.

• The table has a small number of rows (e. g. configuration tables).

Calculation engine plan operators

The calculation engine plan operators deliver good performance. For example, use CE_UNION_ALL instead of UNION ALL to improve performance. However, avoid mixing calculation engine plan operators and SQL queries. Mixing calculation engine plan operators and SQL may lead to missed opportunities to apply optimizations as calculation engine plan operators and SQL statements are optimized independently.

SQLPrepare If you use ODBC API to call any type of procedures for the sake of better performance, prepare it before execution. Use SQLPrepare and SQLExecute, instead of SQLExecDirect.

Finding index and primary keys of tables

If you want to find out the index and primary keys of many tables in a scenario that has a critical performance requirement, DO NOT use SQLStatistics. Use the following SELECT statement instead:

SELECT IFNULL(CONSTRAINT,'NUNIQUE'),INDEX_NAME,COLUMN_NAME FROM INDEX_COLUMNS WHERE SCHEMA_NAME = '%s'

AND TABLE_NAME = '%s' ORDER BY INDEX_OID,POSITION

Sequence The performance of a sequence may be closely related to the way in which the sequence is

Page 23: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

Best Practices of SQL in the SAP HANA Database Performance

PARTNERError! Reference source not found. © 2013 SAP AG. All rights reserved. 23

Topic Description

created.

Example

To create a temporary sequence that can be reset when the database is restarted, the command CREATE SEQUENCE DUMMY_S1 is much slower than CREATE SEQUENCE DUMMY_S2 RESET BY SELECT 0 FROM DUMMY.

Avoid read redundant data

To minimize the data transferred from the database to the application layer, use appropriate WHERE conditions, field lists, and aggregations.

Avoid transferring large data sets from and to the DBMS

Building a large result set and transferring it from the database to the application layer requires more space in the database and takes more time. If you have such SQL in your application, perform an evaluation whether code pushdown can avoid transferring mass data from the SAP HANA database to the application.

Push code down to SAP HANA

Code pushdown to SAP HANA can take advantage of the analytics function of SAP HANA, and also avoid transferring large data sets from and to the DBMS.

Use bulk inserts instead of single record inserts

Insert a set of data records into the database because a single unit is much more efficient than inserting the records one by one.

Identify potential performance improvement areas

• Identify database intensive parts that are modularized and accessed by other parts as a black box.

• Identify parts that transfer massive amounts of data from the DBMS to the application server to be processed there.

• Identify database intensive parts that are frequently called and/or that are very expensive.

Identify Common Sub-Expressions

If you split a complex query into logical sub queries it can help the optimizer to identify common sub expressions and to derive more efficient execution plans.

Multi-Level-Aggregation

In the special case of multi-level aggregations, SQLScript can exploit results at a finer grouping for computing coarser aggregations and return the different granularities of groups in distinct table variables. This could save the client the effort of reexamining the query result.

Understand the Costs of Statements

Employ the explain plan facility to investigate the performance impact of different SQL queries.

Exploit Underlying Engine

SQLScript can exploit the specific capabilities of the OLAP- and JOIN-Engine by relying on views modeled appropriately.

Reduce Dependencies

As SQLScript is translated into a dataflow graph, and independent paths in this graph can be executed in parallel, reducing dependencies enables better parallelism, and thus better performance.

Page 24: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

24 Error! Reference source not found. © 2013 SAP AG. All rights reserved.

Best Practices of SQL in the SAP HANA Database Performance

Topic Description

Avoid Using Cursors

Check if use of cursors can be replaced by (a flow of) SQL statements for better opportunities for optimization and exploiting parallel execution.

Avoid Using Dynamic SQL

Executing dynamic SQL is slow because compile time checks and query optimization must be done for every invocation of the procedure. Another related problem is security because constructing SQL statements without proper checks of the variables used may harm security.

Page 25: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries
Page 26: Best Practices of SQL in the SAP HANA Database€¦ · User Guide Document Version: 2013-02-28 PARTNER Best Practices of SQL in the SAP HANA Database All Countries

www.sap.com/contactsap

© 2013 SAP AG. All rights reserved. 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, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, System ads, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries, xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+, POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of IBM Corporation. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated 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. SAP, R/3, xApps, xApp, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, 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.