0 ratings0% found this document useful (0 votes) 48 views26 pagesBest Practices of SQL in The SAP HANA Database
Best Practices of SQL in the SAP HANA Database
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Pe
User Guide PARTNER
Document Version: 2013-02-28
Best Practices of SQL in the SAP HANA Database
All Countries
fo
» a
i
a
= /
“ NTypographic Conventions
Words or characters quoted from the screen. These include field names, screen titles,
ppushibuttons labels, menu names, menu paths, and menu options.
Textual cross-references to ather documents,
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,
Exact user entry. These are words or characters that you enter in the system exactly as they
appear in the documentation.
Keys on the keyboard, for example, F2] or ENTER)
nee Reference soresrettouns est Practeanc gL nt SAP HANA Dsanese
2 Suara alngreneves "ypearphe ConventionsTable of Contents
1 Introduction...
2 Data Types..
3 Predicates, Operators, and Expressions...
4 8QL Function:
41 String Funetions. g
42. Math Functions °
43 Date Functions. 10
4.4 Conversion Functions, 14
45 Other Functions 16
5 SQL Statements
6 Stored Procedures.
7 Performance...
fee recone tL nthe SAP HANA Dane PARTNER teens soret foun
Table of Conte aPacwirgwermenas 31 ‘Introduction
‘This user guide provides best practices of SQL usage for SAP Business One, version for SAP HANA add-ons, The
add-ons include thse 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 areas follows:
‘+ Best practices for migrating SOL 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,
‘SOL 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 Recordeet .Doguery (string Querystz) method
© Query passed to the DataTable .zxecuteguery (string uezystz) method
© User-defined queries
Stored procedure called by the Recordset . Conmand, Execute method
* Transaction Wotific:
.on stored procedure
© Queries and stored procedures called by add-on codes via opac/sD8c
For more information about SQL usage in SAP HANA, see SAP HANA SQL Reference and SAP HANA SOL Script
Reference on SAP Help Portal at http://help.sap.com/hana_appliance.
Eto atreon nica nents
om racine tL nthaSAP Han Deets
4 SD SEPeE Alngererenes
Intec2 Data Types
This section describes best practices for data types.
cd Poel
Converting You must convert datatype NVARCHAR (max) inthe Microsoft SQL Server database to
TNVARCHAR (na) to | NVARCHAR (n) so that it can run successfully in the SAP HANA database, because there is
VARCHAR (n) 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 | When a unicode string is preceded by an N identifier (N stands for National Language in
identifier the SQL92 standard), the N prefix must be in uppercase,
“> Example
SELECT ‘Brian’ “character string 1", '100' "character string
2", Niabe! "unicode string” FROM DuNenr
Mapping of data Data Type Cat CO eee
types between the
Mhesett so, Exact numeries pigint bigint
Server database bit ‘inyint
andthe SAP HANA
soobae eecimal aecimal
int. integer
numeric aecimal
smaliint smallint
smalimoney smalidecinal
money decimal
tinyint tinyint
Approximate numerics | float float
zeal real
Date and time cate ante
datetine? ‘timestamp
eatetine timestamp
datetineottset N/A
smalldatetine seconddate
time time
Character strings char char
saseoramcatcunme sehen TN fate setae
baer Sues cngmmmnes 8Unicode character
strings
ne Reference soreanctound est PacacesctSQLin fhe SAP HANA aabese
6 Siparpesalngrmenenes Data Types3 Predicates, Operators, and Expressions
‘This section describes best practices for predicates, operators, and expressions.
Rounding on arithmetic | The default rounding methods in the Microsoft SQL Server database andiin the SAP
caleulation HANA database are diferent.
© example
SELECT 1/2 FROM Dunedy will return different resultsin the two
databases,
Inthe 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.
Variable assignment Toassign a value to a variable in stored procedures, use ':
‘best PacteasotSQLn te SEP HANADaabeSe PARTNER Reference soreanettouns
Prescates, Operators, ane Exessions uuscaPac wirgwermenes 74 SQL Functions
‘This section describes best practices for SQL functions.
1 Note
‘Values in square brackets (
{are alternative strings that can be used within the function,
4.1 — String Functions
fenear wt.) [eet vet [emer (he) tee |
fae eer soem ee) [ace omy son ony
CHARTNDEX CHARINDEX (‘char',
(expressionToFind ‘iength in char!)
sexpressicnToSearch
L, start_location
D
Leap (str, 2 [, EPAD (‘end’, 15,
pattern]) 12345)
RIGHT (str, n) RIGHT RIGHT
170123456769", 3) | (/Hr0123456 3)
ne Reference soreanctound est PacacesctSQLin fhe SAP HANA Database
8 Sipaepeaalngrmenenes SQL Finetonseer
a) va2345')
ORIN (2t2 L, ORIN (3t2) ERT (xyE") ERIM (xVE")
SUBSTRING (target, | SUBSTRING (target, | SUBSTRING ‘subsTRaNe
start position [, | tart position, (11234567600, 4, | (13234567690", 4,
string_length)) steing_lengen) 2 2
sussmaster (ste, | N/A sUBSSR_AFTER N/a
patter) (Hello my Friend’,
‘age
sussm_serone (str, | N/A sunsen_aerone N/A
pattern) (meno my Friend’,
aT
mam ({(2papmie || uaRme (RERRM(st=)) | ARMM (abe!) ERI (REREL
SRATLING | BOTH] caer)
‘trim char FROM]
target_string)
VoAsE (target) UPPER (target) CASE (‘abo") UPPER ('abo!)
unrcoDE (c) unrcopE (c) UNICODE ("#") UNICODE ('#")
UPPER (target) UPPER (target) UPPER (‘abc') UPPER ('abe!)
4.2 Math Functions
omnes Format in MSS Brae. a cs Se
ABS (n) ABS (n) ABs (-1), ABS (-1),
aps (7.0) ABS (7.0)
Acos (n) ‘Acos (a) Acos (0), Acos (0),
cos (1) cos (1)
ASIN (n) ASIN (n) ASIN (0.14) , ASIN (0.14) ,
ASIN (-1) ASIN (-1)
ERY (n) EAN (n) TAN (-45.3) , EAN (-45.4) ,
ran (197) ATAN (197)
AERNZ (n,m) AMZ (n, m) AATAN2 (35.175643, | PAN (35.175643,
129) 129)
BITAND (n, m) NA BETAND (255, 123) | N/A
cErE (n) CEILING (n) CEILING (14.5) CEILING (14.5)
Bes ractoss ofS the SAPHANA Dae PARTNER teens soret foun
‘SQL Functions uucaPac wirgwermenes 8Gouda aaa eae SCA coun ao
cos (n) cos (n) cos (14.78) cos (14.78)
cose (n) NA cosz (0.5) N/A
cor ay cor in) cor (124.13) cor (124.13)
EXP (a) EXP (n) exe (2) =xe (1)
FLOOR (n) FLOOR (n) FLOOR (14.5) FLOOR (14.5)
GREATEST (ni [, NA GREATEST (‘aa', NA
2]...) tab!, 'ba', 'Bb')
ZEAST (ni [, NA EAST (vaa!, ‘ab’, | N/A
m2]. .) tbat, 'Bb')
a (n) 10s (n) my (9) 103 (9)
0s (b, n) NA Tos (10, 2) NA
MoD (n, 4) NA Mop (15, 4) NA
POWER (a, y) POWER (n, y) FOWER (2, 10) FOWER (2, 10)
4.3 Date Functions
Format in SAP HANA | Format in MS SQL eee
aop_pays (4, n) | DATEADD (day {/ dd | aDD_paYS DATEADD (day [/ dd / 4],
(4), n, datetiney | (2.2.2012", 4) 4, '1.2.2012')
‘ADD_MONTHS (d, | DATEADD (month [/ | ADD_MONTHS DATEADD (month {/ mm /
» mm /m, 2, (1.1.2012", 4) BI, 4, °1.2.2012")
datetine)
‘ADD_YEARS (4, n) | DATEADD (year {/ | ADD_TEARS DATEADD (year {/ yy /
wy / yyy], n, (14.2012", 4) yyvy], 4, '1.2,2012")
datetine)
‘ADD_SECONDS (t, | DATEADD(second [/ ADD_SECONDS DATEADD (second [/ 25 /
») 32/51, 9, (°23:30:45", 30) | s], 4, GeNDaTE())
datetine)
DAYS_BETWEEN DATEDIFF (day [/ | DAYS_BETWEEN ("O1- | DATEDIFF (day [/ 44 /
(daver, aatez) | aa / a, 01-2012", 4], '1.2.2012",
startdate, cunnent_rmescaur) | cETDATE())
enddate)
DAYNAME (date) | DATENAME (weekday DAYNAME DATENAME (weokaay [/
U awl, datey (cunnent_muesrane) | éw*],* GENDATE ())
DAYOFMONTH DATEPART (day [/ | DAYORMONTE DATEPART (day {/ a4 /
net tran neato senrcees cL tha SAP HANA Dota
no Saepanaingrerenenes ‘SQL rnetoneeee Kea
(date)
DAYOFYEAR (date)
dd / di, date),
Day (date)
DATEPART
(dayotyear (/ ay /
yl, date)
[Scud auianed
(CURRENT_ThesTaM@)
DAYOEYEAR
(CURRENT_TrvEsTAMP)
ee
4), GETDATE()),
DAY ('01.01.2012")
DATEPART (dayotyear (/
ey / yl, GETDATEQ)
EXTRACT ([YEAR |
MONTH | DAY |
HOUR | MINUTE |
SECOND] FROM
datetime value)
DATEPART
(Gatepart, date)
EXTRACT (HOUR FROM
(CURRENT_TIMESTAMP)
DATEPART (HOUR,
GETDATE())
HOUR
(expression)
DATEPART (hour [/
nh], time)
HOUR (112:34:56")
DATEPART (HOUR [/ hh) ,
¥22:34:56")
‘IAST_DAY (date)
DATEADD (dd, -DAY
(parzaDD (m, 1,
date)),
DATEADD (m, 1,
date))
TAST_DAY (70_DATE
2010-01-04",
‘yyvy-tat-pp'))
DATEADD (dd, -DAY
(DATEADD (m, 1,
GETDATE())),
DATEADD (m, 1,
GETDATE()))
MINUTE (exp)
DATEPART (minute
U/ mi / m), time
MINUTE (112:34:56°)
DATEPART (minute [/ mi /
nm), 12:32:43")
MONTH (date)
DATEPART (month [/
mm / mJ, date),
MonTH (date)
MONTH (°1.1.2012")
DATEPART (month {/ mm /
nm}, '01.01.2012"),
monTH (+01.02.2012')
MONTENAME (date)
DATENAME (month {/
mm / mj, date)
MONTENAME,
(2.4.2012)
DATENAME (month [/ mm /
nm], '01-01.2012")
NEKT_DAY (date)
CONVERT (VARCHAR,
DATEADD (DAY, +2,
Gerpare()), 23)
NEXT_DAY (*2009-12-
31)
CONVERT (VARCHAR,
DATEADD (DAY, +2,
GErDATE()), 23)
CURRENT_TIMESTAMP,
GerDATE ()
now ()
(CURRENT_TIMESTAMP,
GETDATE ()
SECOND (date)
DATEPART (second
VU ss/ sl,
GEmATE ())
SECOND (112:34:56")
DATEPART (second [/ ss /
5), GETDATE ())
‘SECONDS_BETWEEN
(at, 42)
DATEDIFF (second
U ss / sl,
startaate,
enddate)
SECONDS BETWEEN
(2009-12-05",
"2010-01-05')
ATEDIFF (second [/ ss /
51, startdate, enddate)
CONVERT (date,
GEmDATE ()),
CONVERT (date,
CONVERT (date, GETDATE
o
fee recone tL nthe SAP HANA Dane
‘SQL Functions
PIN Ratrance nica tins
uucaPac wirgwermenesouta aes A ico
SYSDATETIME ()),
CONVERT (date,
SYSDATETIMEOEFSET
or,
CONVERT (date,
1 Note
For Microsoft
SQL Server
2008, you can
only use
CONVERT
(datetime,
ceDare ())
and convert
(datetime,
(CURRENT_TEIM
STANP)
CURRENT_TIMESTAMP)
[Souda aman
aus
(CURRENT_oIME, CONVERT (time,
GETDATE ()),
CONVERT (time,
eYSDATETIME ()),
CONVERT (time,
SYSDATETIMEOEESET
or
CONVERT (time,
1 Note
For Microsoft
SQL Server
2008, you can
only use
CONVERT
(eatetime,
GEDATE ()),
and CONVERT
(datetime,
CURRENT_TEIM
STANP)
(CURRENT_TIMESTAMP)
(CURRENT_oIME
CONVERT (time, GETDATE
o
(CURRENT_TIMESTAM | CURRENT_TIMESTAMP,
(CURRENT_TIMESTAMP
(CURRENT_TIMESTAMP,
Pe
GETDATE () GETDATE ()
Eto atreon nica nents com rane tL nthaSAP Han Deets
| Saarpasaingrmrenenes ‘SQL rnetoneeee Kea
(CURRENT_UTCDATE
CONVERT (date,
[Scud auianed
(CURRENT_UTCDATE
GeTUTCDATE ()),
CONVERT (date,
SYSUTCDATETIME ())
1 Note
For Microsoft
SQLServer
2005, you can
only use
CONVERT:
(datetine,
GemaTE ())
and CONVERT
(datetine,
(CURRENT_TEIM
‘STANP)
ee
CONVERT (date,
G@ETUrCDATE ())
(CURRENT_UICTIME
CONVERT (time,
GeTUTCDATE ()),
(CURRENT_UTCTIME
CONVERT (time,
SYSUTCDATETINE ())
1 Note
For Microsoft
SQL Server
2005, you can
only use
CONVERT
(datetime,
GEZDATE ()),
and CONVERT
(catetine,
(CURRENT_TEIM
STANP)
CONVERT (time,
GETUTCDATE ())
CURRENT_UacTINEs
AMP.
WEEK (4)
GETUTCDATE () (CURRENT_UTCTIMESTAM
DATEPART (week [/
wk / wil, date)
WEEK ("2012-07-25")
GETUTCDATE ()
DATEPART (week [/ wk /
ww], '2012-07-25')
WeexpAY (date)
DATEPART (dw,
date)
WEEXDAY ('2012-07-
25) +4
DATEPART (aw,
25")
"2012-07-
YEAR (date)
DATEPART (yyy [/
yyl, date),
YEAR (2012-07-25!)
DATEPART (yyyy (/ yy),
*2012-07-28'),
fee recone tL nthe SAP HANA Dane
‘SQL Functions
PIN Ratrance nica tins
uuscaPac wirgwermenesFormat in SAP HANA | Format in MS SQL
Example in SAP HANA
aus
YEAR (12012-07-25")
4.4 Conversion Functions
oman
cas? (expression as
data_type)
ome)
cast (expression aS
data_type)
Ou USA MANS
cast (110' AS int)
Example in MS SQL
cast (/10' AS int)
To_ALPHANUM (exp)
cast (exp AS char
tm),
CONVERT (chaz
[ia)1, exp)
‘To_ALPHANUM ("xyz")
cast ('xvz' aS char
ae,
CONVERT (chaz (3),
txyz')
70_BIGINT (exp)
CAST (exp AS
bigint) ,
CONVERT (bigint,
exp)
To_BIGINT ("11)
cast (111! AS
bigint) ,
CONVERT (bigint,
m4)
70_BLOB (expression)
cast (expresion aS
varbinary (max)),
CONVERT (varbinary
(max), expression
t, styten)
70_BLOB
(Cexpression')
CAST (‘hhh’ aS
varbinary (max),
CONVERT (varbinary
(max), 'miso")
To_CLOB (expression
[, format)
cast (expresion AS
varchar (max)),
CONVERT (varchar
(max), expression
[, stytel)
To_CLOB ("20")
cas (‘qaqq' as
varchar (max),
CONVERT (varchar
(max), cast (aaa!
AS Date), 105)
To DATE (expression
[, format)
cast (exp AS date),
CONVERT (date, exp
{style 1)
ro parE
20120730",
"yyyymnda’)
cast ('20120730' as
gate),
CONVERT (date,
"20120730", 132)
mo_pamS (exp)
CONVERT (VARCHAR,
CAST (exp AS date),
232)
to_pAmS ('2010-01-
a2)
CONVERT (VARCHAR,
cas (12012-03-01'
AS date), 112)
T0_DECIMAL (exp [,
precision, scale])
cast (exp as
DECIMAL
[ (precision,
seale)]),
CONVERT (DECIMAL
To_DECIMAL ('1.2',
5, 4)
cast (11.2! as
DECIMAL (5, 4)),
Eto atreon nica nents
ae Sarre alngnrenenes
com rane tL nthaSAP Han Deets
SQL Finetons‘20_DOUBLE (exp)
to_INT (exp)
‘To_INTEGER (exp)
(expression)
‘TO_NVARCHAR
(expression [,
format])
‘T0_REAL (exp)
‘To_SMALLINT (exp)
‘To_TINYINT (exp)
To_TIME (expression
t, format)
70 TIMESTAMP
float) ,
|
cast (exp as int), | to_mNT (110")
}
:
cast (expresion as | o_NVARCHAR
avarchar ((n)1), 1.1.2008",
,
smallint),
|
tinyint) ,
:
cast (expression as | 10 rimesTaMP
cast (exp as TO_DOUBLE ('1.2') | cas (1.2! as
cas (exp AS int), | TO INTEGER ("10") | CAST (10 AS int),
AST (expresion As | TO_NCLOB ('xxx'), | CAST ("1.1.20
dd/nm/yyyy")
cas (exp as reat), | 0 REAL ('10.2') cas? (110.2! as
CAST (exp aS TO_SMALLINT ("10") | cAST (10 as
CAST (exp aS To_sinyint ('10') | casT (10 as
cast (exp as trum), | 70_TIMe ('08:30 cast (13:3' as
aM", 'HEGME aM") ™2),
float),
cast (10 as int),
varchar (max)),
cas? (11.1.2008" as
avarchar) ,
real),
smallint) ,
tinyint) ,
cast _(11.1.2008
best PacteasoSQLin te SAP HANADaabeSS
‘SQL Functions
PARTNER Reference soreanettouns
S2USAP AC Aingrsasenas 1SA Ua ah ad deel excell Eau ad Example in MS SQL
(expression [, DATETIME) , (2010-01-11 12:24:56.54" AS
format) 33:30:00", DATETINE) |
ae-DD 24
CONVERT (DATETIME, CONVERT (datetine,
expression [, 108 Nov 2022
stylel) aa:45:24:243", 113)
‘TO_VARCHAR cast (expreseion as | To VARCHAR cast ('1.1.2008' as
(expression [, varchar), (1.1.2008", varchar),
format) CONVERT ( varchar, ‘aa/an/viyy") CONVERT (varchar,
expression [, cast ('1.1.2008' as
stylel) pate), 105)
4.5 Other Functions
a eu eee
CConLESCE ‘COALESCE Coatesce (null, 50) | COALESCE (null, 50)
(expression ist) | (expression [
poeB])
MULEZF (expi, | MULLIF (exp, | NUMLIF ("aitf", WULLIF (‘dift', ‘same")
exp2) exp2) ‘aame')
CURRENT SCHEMA | db name () select CURRENT SCHEMA | select db name ()
from Dune
CCURRENT_USER SUSER_NAME (), | SELECT CURRENT_USER | SELECT SUSER_NAME (),
from Due
CuRRENT_USER SELECT CURRENT_USER
@RoUPING 2D GROUPING ID(colum | SELECT customer, SELECT customer, year,
(column_nane_iist |n_nane_list) year, product, sum | product, sum (sales),
> (sales), GROUPING 3D | GROUPING xD (customer,
(customer, year, year, product) FROM
product) FROM guided navi tab GROUP
Guided navi tab GROUP | BY GROUPING SETS
BX GROUPING SETS (customer, year,
((custoner, year, | product), (customer,
product), (customer, | year), (customer,
year), (customer, product), (year,
product), (year, Product), (customer) ,
Product), (customer), | (year), (product);
(year), (product);
Enon Renee seen senrcees cL tha SAP HANA Dota
ae Sagres aingmreneves ‘SQL rnetone5 SQL Statements
‘This section describes best practices for SQL statements.
Tablenames and —_| For table names and field names that contain lower case letters, add double quotation
field names in marks,
statements fe
Example
SELECT "Fieldid" FROM CUFD WHERE "AliaszD"
CREATE TABLE As | Inthe Microsoft SQL Server database. you use the SELECT THTO statement, while in the
‘SAP HANA database, you use the CREATE TABLE as statement.
oP Example
Inthe Microsoft SQL Server database, you write: SELZCT * INTO TI FROM
72
Inthe SAP HANA database, youwrite: CREATE TABLE T1 AS (SELECT *
FROM 72)
Query order ‘SAP HANA is a unicode database. For varchar, and nvarchaz column types, SAP.
HANA currently supports only one collation,
o 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
avarchar (100))
‘best PacteasoSQLin te SAP HANADaabese PARTNER Reference soreanettouns
‘SQL Statements S2GAP A AingrsrasenasAnsert into test_order values (1,N'china') ;
Ansert into test_order values (2,N'canada') ;
Ansert 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 Microsott SQL Server database:
drop table test_order;
create table test_order(id integer, name nvarchar (100)
collate Latini_Genaral_cs Ar);
insert into test_order values (1,N'china')
Ansert into test_order values (2,N'canada') ;
Ansert into test_order values (3,Nvamerica’) ;
Ansert into test_order values (4,N'Australia');
select *, UNICODE (name) trom test_order order by 2
Statements in In SAP HANA Platform Ecition 10 SP4 Rev4l, you cannot perform certain operations in
temporary tables _| colummn-based temporary tables.
Example
Incolumn-based temporary tables, the following commands wil fall
create local temporary column table #local_column_test (coli
ant);
Ansert into #local_column_test values (1);
update #iocal_colum test set coli = 2;--this featureis not
supported
delete from #iocal_colum_test ;~this features not supported
truncate table #local_column_test;
drop table #local_colunn_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 (coll int);
insert into #local_row test values (1);
update #local_row test set coli = 2;
delete trom #local_row_test;
truncate table #local_row_test;
drop table #iocal_row_test;
Eto atreon nica nents om rane tL nthaSAP Han Daenase
we Sepasaingrnrenenes ‘SQL Statements6 Stored Procedures
This section describes best practices for stored procedures.
on
‘rEand ENDI
In stored procedures, when theres an 27, you must add an sND ==,
fe
CREATE PROCEDURE IF_BLSE_IF_TEST(in id INT)
EANGUAGE SQLSCRIPT
as
Example
ent INT := 1;
BEGIN
SELECT COUNT(*) INTO cnt FROM SINF;
1
ee
THEN SELECT ‘cnt == 1' FROM DUMMY;
ELSE IF :nt = 2
THEN SELECT ‘cnt == 2' FROM DUMOMY;
ELSE IF :ont = 3
THEN SELECT ‘cnt == 3' FROM DUMOKY;
ELSE
SELECT ‘ent <>1,2,3' FROM DUNO;
END IF;
END IF;
END IF;
END,
You can also use 12-BLSEI#
ELSE-END IF asin the following example.
oP example
exeate proceure pl (in idx int)
as begin
Af idex = 2 then
select 1 from dummy
elseif side = 2 then
select 2 from dummy;
cise
select 100 from dummy;
end 4¢;
fee recone tL nthe SAP HANA PAR TNEREe Reference soreanetoins
‘Stora rocadres|
uuscaPac wirgwersenas 18‘end:
Table variable You can use table variables in stored procedures.
Example
create Procedure DenoProc
as
BEGIN
vtablel = SELECT "Docentry" FROM OINV;
v_table2 = SELECT "DocEntry" FROM ORIN;
Vout =CE_UNION_ALL(:v tablet, :v_table2);
SELECT * FROM :v_out;
=D;
Dynamic strings of | In stored procedures, if you want to concatenate a dynamic SQL statement with a schema
schemanames | 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 =
"SRIL_LINK’ AND "SCHEMA NAME" = CURRENT SCHEMA;
Xe ctmp > 0 then
exec (‘DROP VIEW ' || '"'|| CURRENT_SCHEMA || 1" I]
*.SRIL_LINK')
end af;
EXEC Ina stored procedure, f you cannot compile a statement because some abject (table,
view, or type) does not exist when the stored procedure is being compiled, use £xz¢ in the
statement.
Example
‘View V 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 vi") instead.
Cursor Example
CREATE PROCEDURE sp cursor test
language sqlscript
as
Ttemcode nvarchar (20);
atchium varchar (32);
Wnscode varchar ;
CURSOR Currs for
select "TtemCode", "BatchNun" ,"WhsCode"
Eto atreon nica nents om rane tL nthaSAP Hana Deets
po Suepasalngrmrenenes ‘Stored rocniresfrom OIBT;
begin
create local temporary table #ti ("Ttemcode" avarchar (100))
open currs;
Fetch Currs Into Ttemcode,BatchNum,thsCode
While not Curre::NOZFOUND do
Ansert into #ti values (rtemcode) ;
Fetch Currs Into Itemcode,BatchNum,Whscode;
end while;
select * from #t1:
Close currs;
drop table #t1;
fee recone tL nthe SAP HANA PAR TNEREe Reference soreanetoins
‘Stored roceres| ‘GuolscaPac al rpwerasenae7 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
+ SAPHANA SOL Script Reference on SAP Help Portal at hitp://help.sap.com/hana_appliance.
‘Columnar and
row-based
data storage
sgLPrepare
Sequence
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 pracess only a single record at ane time (many selects and/or
ipdlates 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).
you use opac Aer to call any type of pracedures for the sake of better performance, prepare
it before execution, Use sonerepaze and soLexecute, instead of sguzxecnizect
The performance af a sequence may be closaly related to the way in which the sequence is,
nee Reference soresrettouns est PacacesctSQLin the SAP HANA Database
ze Saaepasaingrreneves BertormanceTopic Description
created.
Example
To create a temporary sequence that can be reset when the database is restarted, the
command CREATE SEQUENCE DULBKr_s1 ismuch slower than CREATE SEQUENCE
Diwe_s2 RESET BY SELECT 0 FROM DUnOW.
Avoid read | To minimize the data transferred from the database to the application layer, use appropriate
redundant | mHERE conditions, fed lists, and aggregations
deta
Avoid Building a large result set and transferring it from the database to the application layer
transferring
large data sets
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
record inserts
fromandto | fromthe SAP HANA database to the application,
the DBMS
Push code | Cade pushdown to SAP HANA can take advantage of the analytics function of SAP HANA, and.
downto SAP | also avoid transferring large data sets from and to the DEMS.
HANA
Use bulk Insert a set of data records into the database because a single unit is much more efficient than
inserts instead | inserting the records one by one.
of single
Dependencies
Identify * Identify database intensive parts that are modularized and accessed by other parts as. a
potential black box.
Performance | . Identify parts that transfer massive amounts of data from the DEMS to the application
improvement server tobe processed there.
areas + Identify database intensive parts that are frequently called and/or that are very expensive
Identity Ifyou split a complex query into logical sub queries it can help the optimizer to identify
Common Sub- | common sub expressions and to derive more efficient execution plans.
Expressions
Multi-Level: | In the special ease of muli-level aggregations, SQLScript can exploit results ata finer grouping
Aggregation for computing coarser aggregations and return the different granularties of groups in distinct
{able variables. This could save the client the effort of reexamining the query result.
Understand | Employ the explain plan facility to investigate the performance impact of different SQL
theCostsot | queries.
Statements
Exploit ‘SQLScript can exploit the specific capabilities of the OLAP- and JOIN-Engine by relying on
Underlying views modeled appropriately.
Engine
Reduce 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.
fen recone tL nthe SAP Hanan :
Petraes
PIN Ratrance nica tins
GuuscaPac wirgwermenas 28‘Avoid Using | Executing dynamic SQLs slow because compile time checks and query optimization must be
Dynamic SQL | done for every invocation ofthe procedure, Another related problemis security because
constructing SQL statements without proper checks of the variables used may harm security
‘eet Reference sore rettouns est Practeanct gL nt SAP HANA Dstanese
2 Suara aingrnvenenes Bertormancewww.sap.com/contactsap
(220s A Alrgsrecre
ogre ne puneston ay barproccesar varanasi any
tormortor ary parpose nthe ne express permesin of SAP AG.
‘Thevfarrasenconanecherennay bechanges thou
‘Saresotvae ponies mites by SAPAG its aseus
‘eran propeetny sft componensct otter setae
ora Winsous Eicel Outock andPovetPont ae epstres
‘easeraraat ereant corporation
IBM, 052.082 UnerssiDstabese System ads. Sytem'S Syste
pSymame5 Syne Sens Sytesio Sram 0 2
aq Notes sSenes Sees sSenen Serer 2M 2/08 ICS,
‘520 0990 09, As/a00 5/90 Perla terpse
‘Server Pawar oar Sentara POWERS POWERS,
POWERS POUERS PONER CperPoner PouerPC Bache,
Badetert. Syste Stage CFS HHCMP FETAN D2
‘ConectRACF Reshsoks 05/2 PraeSysex NUS/ESA. AK,
Iris Nose Ye Spare Natty To ranma
‘epeoraisarregsterc tsar IBN Corarton
Lune regstvea acer ctLeus Ter nteUS se
(eseeralcarrensterctrserrt of ache Ser
Irorpred nt Unt taser curtis
(Cana repaered rserartct ral Corparton
Wid. pen. OS nant ae regstre ademas ofthe
Ceendieup
‘Gri IA Prog Neetberheed. MeaFare rar.
foncSytems
HIML1ML XHTML ana C a waders or egstered
‘vacomataof VC* Worse ise Conor Mares
atid Techs
nis regserestracerark of Sun Meroptens
“naSorpr careers tradorarkct SunMereseers. re.
‘as uncer lare for tecineogy veredand plans
Reta
‘SEP 2/3 tpg xtpp SAP Natio Duet Parag
BjOssgr SAP Braness®Oeaen ardcthe SAP predicts ord
‘ssrvesrnonorec herons olathe epacnelencere
‘eoceraarregnteredacemarte I SAPAGInGermary din
‘serch coin lon tha wors Alter produ and
‘serves reoned ate the tsorarksct har respects
‘caroanes Datzcartanedinthscocumer sansa fomatonal |
pupesescriyNstona predict specfistonsmay ay
‘Treseatvs areata charge thous notes These
str prow SAPAG and ts aflasd compares (SAP
‘Group for rermatealpupceeseiy who. rposertton or
‘ovary tan na ant SAPGraupohlnetbe able ernst
‘rnssors win epecto the raters Theory waar tor SAP
‘Goupprecctsand serves at those tat rsetfonh tho
‘cress vata esters oecomosrna uchreducs ard
snadetend waranty
|