Sybase Training

126
Overview and Transact-SQL GSDC Brazil – OSS Team

description

Sybase internal

Transcript of Sybase Training

Page 1: Sybase Training

Slide titleIn CAPITALS

50 pt

Slide subtitle 32 pt

Overview and Transact-SQL

GSDC Brazil – OSS Team

Page 2: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-242

Agenda

Sybase ASE Overview Adaptive Server clients Creating tables, modifying/querying data in tables Using temporary tables and system tables Data integrity Writing Transact-SQL code with functions, variables

and control-of-flow statments Managing transactions and locking

Page 3: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-243

Sybase ASE Overview Objectives

Introduce the relational database concepts

Describe how the ASE organizes the information

Describe the properties of a Relational Database

Page 4: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-244

Sybase ASE Overview Relational Database

RDMS – Relational Database Management System

The data and relations are organized in tables

A table is a collection of records (rows) with the same fileds (columns)

Page 5: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-245

Sybase ASE Overview Relational Database - Properties

Unique Rows

Same kind for columns values

Rows and columns sequence are insiginificant

Unique name for each column.

Join operation is used to select columns from two or more tables.

Page 6: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-246

Adaptive Server clientsObjectives

Describe the most common ASE clients.– Interactive SQL– SQL Advantage– Sybase Central

Describe the benefits of each client

Page 7: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-247

Adaptive Server clientsInteractive SQL

Interactive SQL parser to Adaptive Server.

CLI – Command line interface

Access local or remote server

Located in $SYBASE/$SYBASE_OCS/bin

Page 8: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-248

Adaptive Server clientsInteractive SQL

isql [-b] [-e] [-F] [-p] [-n] [-v] [-X] [-Y] [-Q] [-a display_charset] [-A packet_size] [-c cmdend] [-D database] [-E editor] [-h header] [-H hostname] [-i inputfile] [-I interfaces_file]

Page 9: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-249

Adaptive Server clientsInteractive SQL

[-J client_charset] [-K keytab_file] [-l login_timeout] [-m errorlevel] [-o outputfile] [-P password] [-R remote_server_principal] [-s colseparator] [-S server_name] [-t timeout] -U username [-V [security_options]] [-w columnwidth] [-z locale_name] [-Z security_mechanism]

Page 10: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2410

Adaptive Server clientsInteractive SQL

To terminate a command:go To clear the query buffer:reset To call the default editor:vi To execute an operating system command:!! command To exit from isql:quitorexit

Page 11: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2411

Adaptive Server clientsInteractive SQL

Example 1 Puts you in a text file where you can edit the query. When you write and save the file, you are returned to isql. The query appears; type “go” on a line by itself to execute it:

isql -Ujoe -Pabracadabra1> select *2> from authors3> where city = "Oakland"4> vi

Example 2 reset clears the query buffer. quit returns you to the operating system:isql -UalmaPassword:1> select *2> from authors3> where city = "Oakland"4> reset1> quit

Page 12: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2412

Adaptive Server clientsInteractive SQL

Example 3 Specifies that you are running isql from a Macintosh against a server that is using the roman8 character set:

isql -a mac -J roman8

Example 4 Creates column separators using the “#” character in the output in the pubs2 database for store ID 7896:

isql -Usa -P -s#1> use pubs22> go1> select * from sales where stor_id = "7896"#stor_id#ord_num #date ##-------#--------------------#--------------------------##7896 #124152 # Aug 14 1986 12:00AM##7896 #234518 # Feb 14 1991 12:00AM#(2 rows affected)

Page 13: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2413

Adaptive Server clientsSQL Advantage

SQL Advantage is an easy-to-use Transact-SQL (T-SQL) editor that helps you compose syntactically correct T-SQL command statements with the assistance of T-SQL command templates and point-and-click tools. You can then execute your T-SQL queries, and view the results either as text, or within a gridded, spreadsheet-like display.

SQL Advantage can save results data in common PC file formats that can then be imported into other applications (for example, Microsoft Excel).

Page 14: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2414

Page 15: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2415

Adaptive Server clientsSQL Advantage: Multiple text result

Page 16: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2416

Adaptive Server clientsSQL Advantage: Single text result

Page 17: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2417

Adaptive Server clientsSQL Advantage: Grid result

Page 18: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2418

Adaptive Server clientsSybase Central

Sybase Central is a graphical tool that provides a common interface for administering Sybase products. Products such as Adaptive Server Enterprise, Adaptive Server Anywhere, or NetImpact Dynamo include plug-ins that allow you to manage them through Sybase Central.

Page 19: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2419

Adaptive Server clientsSybase Central

Using Sybase Central, you can manage most aspects of Adaptive Server, including the following:

– Adaptive Server configuration and processes – Data caches – Disk devices – Databases and tables – Access to Adaptive Server (logins, users, roles, and

groups) – Application queues (engine groups and execution classes) – Component Integration Services connections

Page 20: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2420

Creating tables, modifying/querying data in tables Describe how to:

– create a new table– Query data– Modify data (Insert/update/delete)

Page 21: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2421

Creating tables

The create table statement:– Defines each column in the table.– Provides the column name and datatype and specifies how

each column handles null values.– Specifies which column, if any, has the IDENTITY property.– Defines column-level integrity constraints and table-level

integrity constraints. Each table definition can have multiple constraints per column and per table.

– Defines computed columns when a table is created.– Defines the table’s partition property when the table is

created.

Page 22: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2422

Creating tables

Using IDENTITY columns– An IDENTITY column contains a value for each row, generated

automatically by Adaptive Server, that uniquely identifies the row within the table.

– Each table can have only one IDENTITY column. You can define an IDENTITY column when you create a table with a create table or select into statement, or add it later with an alter table statement.

– You define an IDENTITY column by specifying the keyword identity, instead of null or not null, in the create table statement. IDENTITY columns must have a datatype of numeric and scale of 0, or any integer type. Define the IDENTITY column with any desired precision, from 1 to 38 digits, in a new table:

create table table_name(column_name numeric(precision ,0) identity)

Page 23: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2423

Creating tables

create table [database .[owner ].]table_name (column_name datatype[default {constant_expression | user | null}]{[{identity | null | not null}][off row | [ in row [ (size_in_bytes) ] ][[constraint constraint_name ]{{unique | primary key}[clustered | nonclustered] [asc | desc][with { fillfactor = pct,max_rows_per_page = num_rows, }reservepagegap = num_pages }][on segment_name]| references [[database .]owner .]ref_table[(ref_column )][match full]| check (search_condition)}]}[match full]...| [constraint constraint_name]{{unique | primary key}[clustered | nonclustered]

Page 24: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2424

Creating tables

(column_name [asc | desc][{, column_name [asc | desc]}...])[with { fillfactor = pctmax_rows_per_page = num_rows ,reservepagegap = num_pages } ][on segment_name]|foreign key (column_name [{,column_name}...])references [[database.]owner.]ref_table[(ref_column [{, ref_column}...])][match full]| check (search_condition) ... }[{, {next_column | next_constraint}}...])[lock {datarows | datapages | allpages }][with { max_rows_per_page = num_rows,exp_row_size = num_bytes,reservepagegap = num_pages,identity_gap = value } ][on segment_name ][ partition_clause ][ [ external table ] at pathname ]

Page 25: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2425

Creating tables

Example 1 Creates the titles table:create table titles(title_id tid not null,title varchar(80) not null,type char(12) not null,pub_id char(4) null,price money null,advance money null,total_sales int null,notes varchar(200) null,pubdate datetime not null,contract bit not null)

Example 2 Creates the sales table and a clustered index in one step with a unique constraint. (In the pubs2 database installation script, there are separate create table and create index statements):

create table sales(stor_id char(4) not null,ord_num varchar(20) not null,date datetime not null,unique clustered (stor_id, ord_num))

Page 26: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2426

Creating tables

Example 3 Creates the salesdetail table with two referential integrity constraints and one default value. There is a table-level, referential integrity constraint named salesdet_constr and a column-level, referential integrity constraint on the title_id column without a specified name. Both constraints specify columns that have unique indexes in the referenced tables (titles and sales). The default clause with the qty column specifies 0 as its default value:

create table salesdetail(stor_id char(4) not null,ord_num varchar(20) not null,title_id tid not nullreferences titles(title_id),qty smallint default 0 not null,discount float not null,constraint salesdet_constrforeign key (stor_id, ord_num)references sales(stor_id, ord_num))

Page 27: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2427

Creating tables

Example 3 Creates the salesdetail table with two referential integrity constraints and one default value. There is a table-level, referential integrity constraint named salesdet_constr and a column-level, referential integrity constraint on the title_id column without a specified name. Both constraints specify columns that have unique indexes in the referenced tables (titles and sales). The default clause with the qty column specifies 0 as its default value:

create table salesdetail(stor_id char(4) not null,ord_num varchar(20) not null,title_id tid not nullreferences titles(title_id),qty smallint default 0 not null,discount float not null,constraint salesdet_constrforeign key (stor_id, ord_num)references sales(stor_id, ord_num))

Page 28: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2428

Creating tables

Example 4 Specifies the ord_num column as the IDENTITY column for the sales_daily table. The first time you insert a row into the table, Adaptive Server assigns a value of 1 to the IDENTITY column. On each subsequent insert, the value of the column increments by 1:

create table sales_daily(stor_id char(4) not null,ord_num numeric(10,0) identity,ord_amt money null)

Page 29: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2429

Altering tables

Adds new columns to a table; drops or modifies existing columns; adds, changes, or drops constraints; changes properties of an existing table; enables or disables triggers on a table.

Supports adding, dropping, and modifying computed columns and to enable the materialized property, nullability, or definition of an existing computed column to be changed.

Partitions and repartitions a table with specified partition strategy, or add partitions to a table with existing partitions. Syntax for altering table partitions is listed separately.

Page 30: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2430

Altering tables

alter table [[database.][owner].table_name{ add column_name datatype}[default {constant_expression | user | null}]{identity | null | not null}[off row | in row][ [constraint constraint_name]{ { unique | primary key }[clustered | nonclustered][asc | desc][with { fillfactor = pct,max_rows_per_page = num_rows,reservepagegap = num_pages }][on segment_name]| references [[database.]owner.]ref_table[(ref_column)][match full]| check (search_condition) ] ... }[, next_column]...| add {[constraint constraint_name]{ unique | primary key}

Page 31: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2431

Altering tables

[clustered | nonclustered](column_name [asc | desc][, column_name [asc | desc]...])[with { fillfactor = pct,max_rows_per_page = num_rows,reservepagegap = num_pages}][on segment_name]| foreign key (column_name [{, column_name}...])references [[database.]owner.]ref_table[(ref_column [{, ref_column}...])][match full]| check (search_condition)}| drop {column_name [, column_name]...| constraint constraint_name }| modify column_name datatype [null | not null][, next_column]...| replace column_namedefault { constant_expression | user | null}| { enable | disable } trigger| lock {allpages | datarows | datapages } }| with exp_row_size=num_bytes| partition number_of_partitions| unpartition| partition_clause| add_partition_clause

Page 32: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2432

Dropping tables

Use drop table to remove a table from a database.drop table [[database.]owner.] table_name[, [[database.]owner.] table_name]...

This command removes the specified tables from the database, together with their contents and all indexes and privileges associated with them.

Rules or defaults bound to the table are no longer bound, but are otherwise not affected

Page 33: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2433

Querying data in tables

Retrieves rows from database objects. A query has three main parts:

– the select clause,– the from clause, and – the where clause.

Page 34: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2434

Querying data in tablesSelect statementselect [ all | distinct ][top unsigned_integer]select_list[into_clause ][from_clause ][where_clause ][group_by_clause][having_clause ][order_by_clause ][compute_clause ][read_only_clause ][isolation_clause ][browse_clause ][plan_clause ]

Page 35: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2435

Querying data in tablesSelect statement Renaming columns in query results

– select Publisher = pub_name, pub_id from publishers– select pub_name Publisher, pub_id from publishers– select pub_name as Publisher, pub_id from publishers

Using expressions– select expression [, expression]...from table_list

Computed values in the select list– & Bitwise and (two operands)– | Bitwise or (two operands)– ^ Bitwise exclusive or (two operands)– ~ Bitwise not (one operand)

Eliminating duplicate query results with distinct– select distinct au_id from titleauthor

Substituting a value for NULLs– select isnull(notes, "unknown") from titles

Page 36: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2436

Querying data in tablesSelect statement from_clause from table_reference [,table_reference]...

– table_referencetable_view_name | ANSI_join– table_view_name

[[database.]owner.] {{table_name | view_name}[as] [correlation_name][index {index_name | table_name }][parallel [degree_of_parallelism]][prefetch size ][lru | mru]}

[holdlock | noholdlock][readpast][shared]– ANSI_join

table_reference join_type join table_referencejoin_conditions

join_type ::= inner | left [outer] | right [outer]join_conditions ::= on search_conditions

Page 37: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2437

Querying data in tablesSelect statement where_clausewhere search_conditions (expression comparison_operator

expression)o = Equal too > Greater thano < Less thano >= Greater than or equal too <= Less than or equal too <> Not equal too != Not equal to (Transact-SQL extension)o !> Not greater than (Transact-SQL extension)o !< Not less than (Transact-SQL extension)o Ranges (between and not between)o Lists (in and not in)o Matching character strings: likeo Testing a column for null values (is null or is not null)

Page 38: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2438

Querying data in tablesSelect statement group_by_clausegroup by [all] aggregate_free_expression [, aggregate_free_expression]...

sum([all | distinct] expression) Total of the (distinct) values in the expression

avg([all | distinct] expression) Average of the (distinct) values in the expression

count([all | distinct] expression) Number of (distinct) non-null values in the expression returned

as an integer.count_big [all | distinct] expression) Number of (distinct) non-null values in

the expression returnedas a bigint..count(*) Number of selected rows as an integer.count_big(*) Number of selected rows as a bigint.max(expression) Highest value in the expressionmin(expression) Lowest value in the expression

Page 39: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2439

Querying data in tablesSelect statement having_clausehaving search_conditions

order_by_clauseorder by sort_clause [, sort_clause]...

sort_clause{ [[[database.]owner.]{table_name.|view_name.}]column_name| select_list_number| expression }[asc | desc]

Page 40: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2440

Querying data in tablesCombining queries: the union operator

The syntax of the union operator is as follows:query1[union [all] queryN ] ...[order by clause][compute clause]

where:• query1 is:select select_list[into clause][from clause][where clause][group by clause][having clause]• queryN is:select select_list[from clause][where clause][group by clause][having clause]

Page 41: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2441

Querying data in tablesJoin

There are several types of joins, such as equijoins, natural joins, and outer joins. The most common join, the equijoin, is based on equality. The following join finds the names of authors and publishers located in the same city:

select au_fname, au_lname, pub_namefrom authors, publisherswhere authors.city = publishers.cityau_fname au_lname pub_name-------- -------- --------------------Cheryl Carson Algodata InfosystemsAbraham Bennet Algodata Infosystems(2 rows affected)

Page 42: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2442

Querying data in tablesJoin

You can embed a join in a select, update, insert, delete, or subquery. Other join restrictions and clauses may follow the join conditions. Joins use the following syntax:

start of select, update, insert, delete, or subqueryfrom {table_list | view_list}where [not][table_name. | view_name.]column_name join_operator[table_name. | view_name.]column_name[{and | or} [not][table_name.|view_name.]column_name join_operator[table_name.|view_name.]column_name]...End of select, update, insert, delete, or subquery

Page 43: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2443

Querying data in tablesJoin

The terms outer table and inner table describe the placement of the tables in an outer join:

– In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the rowpreserving and null-supplying tables, respectively.

– In a right join, the outer table and inner table are the right and left tables respectively.

– For example, in the queries below, T1 is the outer table and T2 is the inner table:

T1 left join T2T2 right join T1Or, using Transact-SQL syntax:T1 *= T2T2 =* T1

Page 44: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2444

Querying data in tablesSubqueries

A subquery is a select statement that is nested inside another select, insert, update, or delete statement, inside a conditional statement, or inside another subquery

Subqueries, also called inner queries, appear within a where or having clause of another SQL statement, or in the select list of a statement.

You can use subqueries to handle query requests that are expressed as the results of other queries

In Transact-SQL, a subquery can also be used almost anywhere an expression is allowed, if the subquery returns a single value

Page 45: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2445

Querying data in tablesDatatype

Page 46: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2446

Querying data in tablesDatatype

Page 47: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2447

Querying data in tablesDatatype

Page 48: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2448

Querying data in tablesDatatype

Page 49: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2449

Querying data in tablesExamples Example 1 Selects all rows and columns from the publishers table:select * from publisherspub_id pub_name city state------ --------------------------- -------------------- -----0736 New Age Books Boston MA0877 Binnet & Hardley Washington DC1389 Algodata Infosystems Berkeley CA

Example 2 Selects all rows from specific columns of the publishers table:select pub_id, pub_name, city, state from publishers

Example 3 Selects all rows from specific columns of the publishers table, substituting one column name and adding a string to the output:

select "The publisher's name is",Publisher = pub_name, pub_idfrom publishersPublisher pub_id----------------------- ----------------------------- ------The publisher’s name is New Age Books 0736The publisher’s name is Binnet & Hardley 0877The publisher’s name is Algodata Infosystems 1389

Page 50: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2450

Querying data in tablesExamples Example 4 Selects specific columns and rows, placing the results into the temporary table

#advance_rpt:select pub_id, total = sum (total_sales)into #advance_rptfrom titleswhere advance < $10000and total_sales is not nullgroup by pub_idhaving count(*) > 1

Example 5 Concatenates two columns and places the results into the temporary table #tempnames:

select "Author_name" = au_fname + " " + au_lnameinto #tempnamesfrom authors

Example 6 Selects specific columns and rows, returns the results ordered by type from highest to lowest, and calculates summary information:

select type, price, advance from titlesorder by type desccompute avg(price), sum(advance) by typecompute sum(price), sum(advance)

Page 51: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2451

Querying data in tablesExamples Example 7 Gives an optimizer hint for the parallel degree for the query:select ord_num from salesdetail(index salesdetail parallel 3)

Example 8 Joins the titleauthor and the titles tables on their title_id columns. The result set only includes those rows that contain a price greater than 15:

select au_id, titles.title_id, title, pricefrom titleauthor inner join titleson titleauthor.title_id = titles.title_idand price > 15

Example 9 Joins the titleauthor and the titles tables on their title_id columns. The result set only includes those rows that contain a price greater than 15:

select au_id, titles.title_id, title, pricefrom titleauthor inner join titleson titleauthor.title_id = titles.title_idand price > 15Or select au_id, titles.title_id, title, pricefrom titleauthor where titleauthor.title_id = titles.title_idand price > 15

Page 52: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2452

Querying data in tablesExamples Example 10 The result set contains all the authors

from the authors table. The authors who do not live in the same city as their publishers produce null values in the pub_name column. Only the authors who live in the same city as their publishers, Cheryl Carson and Abraham Bennet, produce a non-null value in the pub_name column:

select au_fname, au_lname, pub_namefrom authors left join publisherson authors.city = publishers.city

Page 53: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2453

Querying data in tablesExamples Subquery examples:

select au_fname, au_lname from authors where au_id in (select au_id from titleauthor where royaltyper > 75)

select au1.au_lname, au1.au_fname, au1.city from authors au1 where au1.city in (select au2.city from authors au2 where au2.au_fname = "Livia“ and au2.au_lname = "Karsen")

au_lname au_fname city----------- --------- -------Green Marjorie OaklandStraight Dick OaklandStringer Dirk OaklandMacFeather Stearns OaklandKarsen Livia Oakland(5 rows affected)

update titles set price = price * 2 where pub_id in (select pub_id from publishers where pub_name = "New Age Books")

Page 54: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2454

Adding changing and deleting Data

The commands you use to add, change, or delete data are called data modification statements. These commands are:

– insert - adds new rows to a table.– update - changes existing rows in a table.– delete - removes specific rows from a table.– truncate table - removes all rows from a table.– writetext - adds or changes text, unitext, and image data

without writing lengthy changes in the system’s transaction log.

Page 55: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2455

Adding changing and deleting DataAdding new data

insert [into] [database.[owner.]]{table_name|view_name}[(column_list)]{values (expression [, expression]...)|select_statement [plan "abstract plan"] }

Page 56: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2456

Adding changing and deleting DataAdding new data

Example 1:insert into publishers (pub_id, pub_name)values ("1756", "The Health Center")

Example 2:insert authorsselect *from newauthors

Page 57: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2457

Adding changing and deleting DataChanging existing dataupdate [top unsigned_integer][[database.]owner.]{table_name | view_name}set [[[database.]owner.]{table_name.|view_name.}]column_name1 ={expression1 | NULL | (select_statement)} |variable_name1 ={expression1 | NULL | (select_statement)}[, column_name2 ={expression2 | NULL | (select_statement)}]... |[, variable_name2 ={expression2 | NULL | (select_statement)}]...[from [[database.]owner.]{view_name [readpast]|table_name [readpast][(index {index_name | table_name}[ prefetch size ][lru|mru])]}[,[[database.]owner.]{view_name [readpast]|table_name [readpast][(index {index_name | table_name }[ prefetch size ][lru|mru])]}]...][where search_conditions][plan "abstract plan"]

Page 58: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2458

Adding changing and deleting DataChanging existing data Example 1 All the McBaddens in the authors table are now MacBaddens:update authorsset au_lname = "MacBadden"where au_lname = "McBadden“

Example 2 Modifies the total_sales column to reflect the most recent sales recorded in the sales and salesdetail tables. This assumes that only one set of sales is recorded for a given title on a given date, and that updates are current:

update titlesset total_sales = total_sales + qtyfrom titles, salesdetail, saleswhere titles.title_id = salesdetail.title_idand salesdetail.stor_id = sales.stor_idand salesdetail.ord_num = sales.ord_numand sales.date in(select max(sales.date) from sales)

Page 59: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2459

Adding changing and deleting DataDeleting existing datadelete[top unsigned_integer][from] [[database.]owner.]{view_name|table_name}[where search_conditions][plan "abstract plan"]delete [[database.]owner.]{table_name | view_name}[from [[database.]owner.]{view_name [readpast]|table_name [readpast][(index {index_name | table_name }[ prefetch size ][lru|mru])]}[, [[database.]owner.]{view_name [readpast]|table_name [readpast][(index {index_name | table_name }[ prefetch size ][lru|mru])]} ...][where search_conditions] ][plan "abstract plan"]delete [from] [[database.]owner.]{table_name|view_name}where current of cursor_name

Page 60: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2460

Adding changing and deleting DataDeleting existing data Example 1 Deletes all rows from the authors table:delete authors

Example 2 Deletes a row or rows from the authors table:delete from authorswhere au_lname = "McBadden“

Example 3 Deletes rows for books written by Bennet from the titles table.delete titlesfrom titles, authors, titleauthorwhere authors.au_lname = 'Bennet'and authors.au_id = titleauthor.au_idand titleauthor.title_id = titles.title_id

Page 61: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2461

Using temporary tables and system tables Temporary tables (concept, create and using) System tables (where to find, examples)

Page 62: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2462

Temporary tablesConcept

Temporary tables are created in the tempdb database.

To create a temporary table, you must have create table permission in tempdb. create table permission defaults to the Database Owner.

To make a table temporary, use the pound sign (#) or “tempdb..” before the table name in the create table statement.

There are two kinds of temporary tables:

Page 63: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2463

Temporary tablesCreating and using

Tables that can be shared among Adaptive Server sessions Create a shareable temporary table by specifying tempdb as part of the table name in the create table statement. For example, the following statement creates a temporary table that can be shared among Adaptive Server sessions:

create table tempdb..authors(au_id char(11))drop table tempdb..authors

– Adaptive Server does not change the names of temporary tables created this way. The table exists until the current session ends or until its owner drops it using drop table.

Page 64: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2464

Temporary tablesCreating and using

Tables that are accessible only by the current Adaptive Server session or procedure

– Create a nonshareable temporary table by specifying a pound sign (#) before the table name in the create table statement. For example:

create table #authors(au_id char (11))

– The table exists until the current session or procedure ends, or until its owner drops it using drop table.

Page 65: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2465

System tablesDescription

The master database contains system tables that keep track of information about Adaptive Server.

Each database (including the master database) contains system tables that keep track of information specific to that database.

A master database and its tables are created automatically when Adaptive Server is installed.

The system tables in a user database are created when the create database command is issued.

The names of all system tables start with "sys".

Page 66: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2466

System tablesDiagram

Page 67: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2467

System procedures

The names of all system procedures begin with "sp_". They are located in the sybsystemprocs database, but you can

run many of them in any database by issuing the stored procedure from the database or by qualifying the procedure name with the database name

Examples:– sp_configure– sp_helpdevice– sp_dboption– sp_helpindex– sp_depends– sp_helpkey– sp_help– sp_helprotect– sp_helpdb– sp_lock

Page 68: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2468

Data integrity

Transact-SQL provides two methods for maintaining data integrity in a database:

– Defining create table integrity constraints– Defining rules, defaults, indexes, and triggers

Page 69: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2469

Constraints

Types of constraints:– unique and primary key constraints require that no two

rows in a table have the same values in the specified columns. In addition, a primary key constraint requires that there not be a null value in any row of the column.

– Referential integrity (references) constraints require that data being inserted in specific columns already have matching data in the specified table and columns. Use sp_helpconstraint to find a table’s referenced tables.

– check constraints limit the values of data inserted into columns.

Page 70: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2470

Constraints

table-level

create table my_publishers(pub_id char(4),pub_name varchar(40),constraint my_chk_constraintcheck (pub_id in ("1389", "0736", "0877")or pub_name not like "Bad News Books"))

column-level

create table my_publishers(pub_id char(4) constraint my_chk_constraintcheck (pub_id in ("1389", "0736", "0877")),pub_name varchar(40))

Page 71: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2471

Defaults and Rules

A default is a value that Adaptive Server inserts into a column if a user does not explicitly enter a value for that column.

In database management, a rule specifies what you are or are not allowed to enter in a particular column or in any column with a given user-defined datatype.

Page 72: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2472

Using Defaults

Creating:create default [owner.]default_nameas constant_expression

Binding:sp_bindefault advancedflt, "titles.advance"

After you create a default, the source text describing the default is stored in the text column of the syscomments system table.

Unbiding:sp_unbindefault objname [, futureonly]

Dropping:drop default [owner.]default_name[, [owner.]default_name] ...

Page 73: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2473

Using Rules

Creating:create rule [owner.]rule_nameas condition_expression

Binding:sp_bindrule rulename, objname [, futureonly]

The following restrictions apply to rules:– You cannot bind a rule to a text, unitext, image, or timestamp datatype column.– Adaptive Server does not allow rules on system tables.

Unbinding:sp_unbindrule objname [, futureonly]:

Dropping:drop rule [owner.]rule_name[, [owner.]rule_name] ...

Page 74: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2474

Defaults and RulesExamples Create Defaults:create default advancedflt as "UNKNOWN"

create default citydfltas "Oakland"

Here is how the rule permitting five different pub_id numbers and one dummy value (99 followed by any two digits) was created:

create rule pub_idruleas @pub_id in ("1389", "0736", "0877", "1622", "1756")or @pub_id like "99[0-9][0-9]"

The following example creates a rule that forces the values you enter to comply with a particular picture. In this case, each value entered in the column must begin with "415" and be followed by 7 more characters:

create rule phoneruleas @phone like "415_______"

Page 75: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2475

Data integrity with Indexes

A unique index permits no two rows to have the same index value, including NULL. The system checks for duplicate values when the index is created, if data already exists, and checks each time data is added or modified with an insert or update

Sintax:create unique index [index_name] on

[[database.]owner.]table_name(column_expression [asc | desc][, column_expression [asc | desc]]...)

Page 76: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2476

Data integrity with Triggers

A trigger is a stored procedure that instructs the system to take one or more actions when a specific change is attempted. By preventing incorrect, unauthorized, or inconsistent changes to data, triggers help maintain the integrity of a database

Triggers can also protect referential integrity enforcing rules about the relationships among data in different tables. Triggers go into effect when a user attempts to modify data with an insert, delete, or update command

You can use triggers to perform a number of automatic actions, such as cascading changes through related tables, enforcing column restrictions, comparing the results of data modifications, and maintaining the referential integrity of data across a database

Triggers can nest to a depth of 16 levels, and can call local or remote stored procedures or other triggers.

Page 77: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2477

Data integrity with Triggers

Triggers are automatic.

Example of use: For example, to prevent users from removing any publishing

companies from the publishers table, you could use this trigger:create trigger del_pubon publishersfor deleteasbeginrollback transactionprint "You cannot delete any publishers!"end

Page 78: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2478

Data integrity with Triggers

Triggers are most useful in these situations:– Triggers can cascade changes through related tables in the database. For

example, a delete trigger on the title_id column of the titles table can delete matching rows in other tables, using the title_id column as a unique key tolocating rows in titleauthor and roysched.

– Triggers can disallow, or roll back, changes that would violate referential integrity, canceling the attempted data modification transaction. Such a trigger might go into effect when you try to insert a foreign key that does not match its primary key. For example, you could create an insert triggeron titleauthor that rolled back an insert if the new titleauthor.title_id valuedid not have a matching value in titles.title_id.

– Triggers can enforce restrictions that are much more complex than those that are defined with rules. Unlike rules, triggers can reference columns or database objects. For example, a trigger can roll back updates that attempt to increase a book’s price by more than 1 percent of the advance.

– Triggers can perform simple “what if” analyses. For example, a trigger can compare the state of a table before and after a data modification and take action based on that comparison.

Page 79: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2479

Data integrity with Triggers

Using triggers vs. integrity constraints– Cascade changes through related tables in the database– Enforce complex restrictions by referencing other columns

or database objects– Perform “what if” analyses

create trigger [owner.]trigger_nameon [owner.]table_name{for {insert , update , delete}as SQL_statements

Page 80: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2480

Data integrity with Triggers

If you use the if update clause, enter:create trigger [owner.]trigger_nameon [owner.]table_namefor {insert , update}as[if update (column_name )[{and | or} update (column_name )]...]SQL_statements[if update (column_name )[{and | or} update (column_name )]...SQL_statements ]...

Page 81: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2481

Data integrity with Triggers

Adaptive Server uses two special tables in trigger statements: the deleted table and the inserted table. These are temporary tables used in trigger tests.

The deleted table stores copies of the affected rows during delete and update statements. During the execution of a delete or update statement, rows are removed from the trigger table and transferred to the deleted table. The deleted and trigger tables ordinarily have no rows in common.

The inserted table stores copies of the affected rows during insert and update statements. During an insert or an update, new rows are added to the inserted and trigger tables at the same time. The rows in inserted are copies of the new rows in the trigger table.

An update is, effectively, a delete followed by an insert; the old rows are copied to the deleted table first; then the new rows are copied to the trigger table and to the inserted table.

Page 82: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2482

Data integrity with Triggers

The following trigger compares the title_id values from the inserted table with those from the titles table. It assumes that you are making an entry for the foreign key and that you are not inserting a null value. If the join fails, the transaction is rolled back.

create trigger forinsertrig1on salesdetailfor insertasif (select count(*)from titles, insertedwhere titles.title_id = inserted.title_id) !=@@rowcount/* Cancel the insert and print a message.*/beginrollback transactionprint "No, the title_id does not exist intitles."end/* Otherwise, allow it. */elseprint "Added! All title_id’s exist in titles."

Page 83: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2483

Writing Transact-SQL code

Batches and control-flow Functions Stored procedures

Page 84: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2484

Writing Transact-SQL codeBatches and control-flow Transact-SQL allows you to group a series of statements as a batch,

either interactively or from an operating system file.

You can also use Transact- SQL’s control-of-flow language to connect the statements, using programming constructs.

A variable is an entity that is assigned a value. This value can change during the batch or stored procedure in which the variable is used.

Adaptive Server has two kinds of variables: local and global. Local variables are user-defined, where as global variables are supplied by the system and are predefined

You can submit one or more batches of Transact-SQL statements to isql from an operating system file. A file can include more than one batch, that is, more than one collection of statements, each terminated by the word “go.”

Page 85: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2485

Writing Transact-SQL codeBatches and control-flow if and else:If boolean_expressionstatement[else[if boolean_expression]statement ]

case expression

casewhen search_condition1 then result1when search_condition2 then result2. . .when search_conditionn then resultnelse resultx

end

Page 86: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2486

Writing Transact-SQL codeBatches and control-flow

Case expression – examples

select stor_id, title_id, qty, "Book Sales Catagory" =

casewhen qty < 1000 then "Low Sales Book"when qty >= 1000 and qty <= 3000 then "Medium

Sales Book"when qty > 300 then "High Sales Book"

endfrom salesdetail

Page 87: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2487

Writing Transact-SQL codeBatches and control-flow

Case expression – examplesselect title, pub_id, "Publisher" =case pub_id

when "0736" then "New Age Books"when "0877" then "Binnet & Hardley"when "1389" then "Algodata Infosystems"else "Other Publisher"

endfrom titlesorder by pub_id

Page 88: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2488

Writing Transact-SQL codeBatches and control-flow

coalesce– coalesce examines a series of values (value1, value2, ...,

valuen) and returns the first non-null value. The syntax of coalesce is:

coalesce(value1, value2, ..., valuen)

nullif– nullif compares two values; if the values are equal, nullif

returns a null value. If the two values are not equal, nullif returns the value of the first value

nullif(value1, value2)

Page 89: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2489

Writing Transact-SQL codeBatches and control-flow

begin...end - The begin and end keywords enclose a series of statements so that they are treated as a unit by control-of-flow constructs like if...else. A series of statements enclosed by begin and end is called a statement block.

The syntax of begin...end is:beginstatement blockend

Page 90: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2490

Writing Transact-SQL codeBatches and control-flow

begin...end - example:

if (select avg(price) from titles) < $15begin

update titlesset price = price * 2select title, pricefrom titleswhere price > $28

end

Page 91: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2491

Writing Transact-SQL codeBatches and control-flow

while and break...continue

while boolean expressionbegin

statement[statement]...break[statement]...continue[statement]...

end

Page 92: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2492

Writing Transact-SQL codeBatches and control-flow

while and break...continue

while (select avg(price) from titles) > $20beginupdate titlesset price = price / 2if (select max(price) from titles) < $40

breakelseif (select avg(price) from titles) < $20

continueprint "Average price still over $20"

end

Page 93: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2493

Writing Transact-SQL codeBatches and control-flow Goto - The goto keyword causes unconditional branching to a

user-defined label.

Syntax:label:goto label

Example:declare @count smallintselect @count = 1restart:print "yes"select @count = @count + 1while @count <=4goto restart

Page 94: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2494

Writing Transact-SQL codeBatches and control-flow

Comments - Use the comment notation to attach comments to statements, batches, and stored procedures. Comments are not executed.

/* A comment here might explain the rules** associated with using an asterisk as** shorthand in the select list.*/

Page 95: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2495

Writing Transact-SQL codeLocal Variables

Local variables are declared, named, and typed with the declare keyword and are assigned an initial value with a select statement. They must be declared, assigned a value, and used within the same batch or procedure.

Local variables are often used as counters for while loops or if...else blocks in a batch or stored procedure. When they are used in stored procedures, they are declared for automatic, non-interactive use by the procedure when it executes

Page 96: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2496

Writing Transact-SQL codeLocal Variables

To declare a local variable’s name and datatype use:declare @variable_name datatype[, @variable_name datatype]...

It is more efficient in terms of memory and performance to write:

declare @a int, @b char(20), @c float

Page 97: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2497

Writing Transact-SQL codeLocal Variables

Local variables and select statements

declare @c1 float, @c2 floatselect @c1 = 1000/1000select @c2 = @c1/30select @c1 , @c2

declare @veryhigh moneyselect @veryhigh = max(price)from titlesselect @veryhigh

Page 98: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2498

Writing Transact-SQL codeLocal Variables

If the select statement that assigns values to a variable returns more than one value, the last value that is returned is assigned to the variable.

declare @m moneyselect @m = advance from titlesselect @m(18 rows affected)------------------------8,000.00(1 row affected)

Page 99: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-2499

Writing Transact-SQL codeLocal Variables Local variables and update statements You can assign variables directly in an update statement. You do not

need to use a select statement to assign a value to a variable. When you declare a variable, it has the value NULL. Here is the syntax:update [[database.]owner.] {table_name | view_name}set [[[database.]owner.]{table_name. | view_name.}]column_name1 ={expression1 | null | (select_statement)} |variable_name1 = {expression1 | null}[, column_name2 = {expression2 | null |(select_statement)}]... |[, variable_name2 = {expression2 | null}]...[from [[database.]owner.]{table_name | view_name}[, [[database.]owner.] {table_name |view_name}]]...[where search_conditions]

Page 100: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24100

Writing Transact-SQL codeLocal Variables Local variables and subqueries - A subquery that assigns a value to the

local variable must return only one value. Here are some examples:declare @veryhigh moneyselect @veryhigh = max(price)from titlesif @veryhigh > $20print "Ouch!“

declare @one varchar(18), @two varchar(18)select @one = "this is one", @two = "this is two"if @one = "this is one"print "you got one"if @two = "this is two"print "you got two"else print "nope"

Page 101: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24101

Writing Transact-SQL codeLocal Variables Local variables and while loops and if…else blocks The

following example uses local variables in a counter in a while loop, for doing matching in a where clause, in an if statement, and for setting and resetting values in select statements

/* Determine if a given au_id has a row in au_pix*//* Turn off result counting */set nocount on/* declare the variables */declare @c int,@min_id varchar(30)/*First, count the rows*/select @c = count(*) from authors/* Initialize @min_id to "" */select @min_id = ""

Page 102: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24102

Writing Transact-SQL codeLocal Variables/* while loop executes once for each authors row */while @c > 0begin/*Find the smallest au_id*/select @min_id = min(au_id)from authorswhere au_id > @min_id/*Is there a match in au_pix?*/if exists (select au_idfrom au_pixwhere au_id = @min_id)beginprint "A Match! %1!", @min_idendselect @c = @c -1 /*decrement the counter */end

Page 103: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24103

Writing Transact-SQL codeGlobal variables

Global variables are system-supplied, predefined variables. They are distinguished from local variables by the two @ signs preceding their names— for example, @@error. The two @ signs are considered part of the identifier used to define the global variable.

Users cannot create global variables and cannot update the value of global variables directly in a select statement. If a user declares a local variable that has the same name as a global variable, that variable is treated as a local variable.

Page 104: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24104

Writing Transact-SQL codeGlobal variables Checking for errors with @@errorif @@error != 0

Checking IDENTITY values with @@identity @@identity contains the last value inserted into an IDENTITY column in the current

user session. @@identity is set each time an insert, select into, or bcp attempts to insert a row into a table.

Checking the status from the last fetch@@sqlstatus

Value Meaning0 The fetch statement completed successfully.1 The fetch statement resulted in an error.2 There is no more data in the result set. This warning occurs

if the current cursor position is on the last row in the result set and the client submits a fetch command for that cursor

Page 105: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24105

Writing Transact-SQL codeGlobal variables @@rowcount

– Contains the number of rows affected by the last query. @@rowcount is set to 0 by any command that does not return rows, such as an if, update, or delete statement. With cursors, @@rowcount represents the cumulative number of rows returned from the cursor result set to the client, up to the last fetch request.

@@max_connections – Contains the maximum number of simultaneous connections that can be

made with Adaptive Server in the current computer environment. You can configure Adaptive Server for any number of connections less than or equal to the value of @@max_connection, using number of user connections configuration parameter.

@@servername– Contains the name of this Adaptive Server. Define a server name with

sp_addserver, and then restart Adaptive Server.

@@version – Contains the date of the current release of Adaptive Server.

Page 106: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24106

Writing Transact-SQL codegoto The goto keyword causes unconditional branching to a user-

defined label. Goto and labels can be used in stored procedures and batches. Here is the syntax:

label:goto label Here is an example that uses goto and a label, a while loop, and a

local variable as a counter:declare @count smallintselect @count = 1restart:print "yes"select @count = @count + 1while @count <=4goto restart

Page 107: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24107

Writing Transact-SQL codereturn and print The return keyword exits from a batch or procedure unconditionally The

syntax is:return [int_expression]

The print keyword, displays a user-defined message or the contents of a local variable on the user’s screen. The syntax is:

print {format_string | @local_variable |@@global_variable} [,arg_list]

declare @tabname varchar(30)select @tabname = "titles"declare @username varchar(30)select @username = "ezekiel"print "The table '%1!' is not owned by the user '%2!'.",@tabname, @username

Page 108: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24108

Writing Transact-SQL codeBuildin-function

Built-in functions are a Transact-SQL extension to SQL that return information from the database.

The general syntax of the system functions is:select function_name(argument[s]) Examples:

Function Argument Resultcol_length (object_name,

column_name)Returns the defined length of column. Use datalength to see the actual data size.

db_id ([ database_name]) Returns the database ID number

Page 109: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24109

Writing Transact-SQL codeBuildin-function

Function Argument Resultdb_name ([database_id ]) Returns the database name

user Returns the user’s name.

user_id ([user_name]) Returns the user’s ID number. Reports the number from sysusers in the current database. If no user_name is supplied, it returns the ID of the current user.

isnull (expression1, expression2)

Substitutes the value specified in expression2 when expression1 evaluates to NULL.The datatypes of the expressions must convert implicitly, or you must use the convert function.

Page 110: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24110

Writing Transact-SQL codeBuildin-function

Function Argument Resultright (expression, integer_expr) Returns the part of the character or binary

expression starting at the specified number of characters from the right. Return value has the same datatype as the character expression.

rtrim (char_expr) Removes trailing blanks. Only values equivalent to the space character in the SQL special character definition are removed.

substring (expression, start, length) Returns part of a character or binary string. start specifies the character position at which the substring begins. length specifies the number of characters in the substring.

Page 111: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24111

Writing Transact-SQL codeStored Procedures

A stored procedure is a named collection of SQL statements or control-of-flow language.

You can create stored procedures for commonly used functions and to increase performance.

Adaptive Server also provides system procedures to perform administrative tasks and to update the system tables.

Page 112: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24112

Writing Transact-SQL codeStored Procedures

When you run a stored procedure, Adaptive Server prepares a plan so that the procedure’s execution is very fast. Stored procedures can:

– Take parameters– Call other procedures– Return a status value to a calling procedure or batch to

indicate success or failure and the reason for failure– Return values of parameters to a calling procedure or batch– Be executed on remote Adaptive Servers

Page 113: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24113

Writing Transact-SQL codeStored Procedures A parameter is an argument to a stored procedure. You can optionally declare one or more parameters in a create procedure

statement. The value of each parameter named in a create procedure statement must be

supplied by the user when the procedure is executed.

create proc au_info @lastname varchar(40),@firstname varchar(20) asselect au_lname, au_fname, title, pub_namefrom authors, titles, publishers, titleauthorwhere au_fname = @firstnameand au_lname = @lastnameand authors.au_id = titleauthor.au_idand titles.title_id = titleauthor.title_idand titles.pub_id = publishers.pub_id Now, execute au_info:au_info Ringer, Anne

Page 114: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24114

Writing Transact-SQL codeStored Procedures

User-generated return values You can generate your own return values in stored procedures by

adding a parameter to the return statement. You can use any integer outside the 0 through -99 range. The following example returns 1 when a book has a valid contract and returns 2 in all other cases:

create proc checkcontract @titleid tidasif (select contract from titles wheretitle_id = @titleid) = 1return 1elsereturn 2

Page 115: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24115

Writing Transact-SQL codeStored Procedures This stored procedure performs multiplication on two integers (the

third integer, @result, is defined as an output parameter):create procedure mathtutor@mult1 int, @mult2 int, @result int outputasselect @result = @mult1 * @mult2 Usingdeclare @result intexec mathtutor 5, 6, @result output(return status = 0)Return parameters:-----------30

Page 116: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24116

Writing Transact-SQL codeStored Procedures System procedures used for security administrationsp_addloginsp_addusersp_dropusersp_helprotectsp_password System procedures used for remote serverssp_addremoteloginsp_addserversp_helpserver System procedures for managing databasessp_dboptionsp_helpdb

Page 117: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24117

Writing Transact-SQL codeStored Procedures

System procedures used for data definition and database objects

sp_bindcachesp_bindefaultsp_bindrulesp_dependssp_helpsp_helpcachesp_helptextsp_spaceused

Page 118: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24118

Managing transactions and locking

Transactions Lock

Page 119: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24119

TransactionsDescription

A transaction groups a set of Transact-SQL statements so that they are treated as a unit.

Adaptive Server automatically manages all data modification commands, including single-step change requests, as transactions.

Use the following commands to create transactions: • begin transaction – marks the beginning of the transaction block. The syntax is:

begin {transaction | tran} [transaction_name]

Page 120: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24120

Transactions

Transactions and consistency - In a multiuser environment, Adaptive Server must prevent simultaneous queries and data modification requests from interfering with each other.

Transactions and recovery - A transaction is both a unit of work and a unit of recovery. The fact that Adaptive Server handles single-step change requests as transactions means that the database can be recovered completely in case of failure

Page 121: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24121

Transactions

Rolling back and saving transactions

begin transtatements Group Asave tran mytranstatements Group Brollback tran mytran Rolls back group Bstatements Group Ccommit tran Commits groups A and C

Page 122: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24122

Transactions

Checking the state of transactions The global variable @@transtate keeps track of the

current state of a transaction. Adaptive Server determines what state to return by keeping track of any transaction changes after a statement executes. @@transtate may contain the following values:

– 0 Transaction in progress. A transaction is in effect; the previous statement executed successfully.

– 1 Transaction succeeded. The transaction completed and committed its changes.

– 2 Statement aborted. The previous statement was aborted; no effect on the transaction.

– 3 Transaction aborted. The transaction aborted and rolled back any changes.

Page 123: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24123

LockingConcept

Consistency of data means that if multiple users repeatedly execute a series of transactions, the results are correct for each transaction, each time. Simultaneous retrievals and modifications of data do not interfere with each other: the results of queries are consistent.

If a query needs to read or update many rows in a table:

– It can acquire just one table-level lock– It can acquire a lock for each page that contained one of

the required rows– It can acquire a lock on each row

Page 124: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24124

LockingConcept

Adaptive Server provides these locking schemes:– Allpages locking, which locks datapages and index pages– Datapages locking, which locks only the data pages– Datarows locking, which locks only the data rows

Allpages locking locks both data pages and index pages.

In datapages locking, entire data pages are still locked, but index pages are not locked.

In datarows locking, row-level locks are acquired on individual rows on data pages.

Page 125: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24125

References

ASE Sybase 15.0.2– Transact-SQL User’s Guide– System Tables Diagram– System Adminstration Guide 1– Reference manual commands– Performance and Tuning Locking

Page 126: Sybase Training

Top right corner for field-mark, customer or partner logotypes. See Best practice for example.

Slide title 40 pt

Slide subtitle 24 pt

Text 24 pt

Bullets level 2-520 pt

Ericsson Confidential Sybase Internal Training 2009-03-24126