SYBASE ADAPTIVE SERVER ENTERPRISE

Release 12.5 GA and above

INDEX:

I….. .ASE Overview

II…..System Databases and Tables

III….Transact SQL

IV….Transactions

V……Isolation Levels

VI…..Locking

VII…ASE Supported Platforms

VIII..ASE Utilities

IX…..Component Integration Services (CIS)

X……New Features – ASE 15

XI….ASE Resources

XII…SYBASE Data Server & Integration Products

For Details of the INDEX  refer the next pages  w.r .to each INDEX.

Leave a Comment

III. TRANSACT SQL.

III. TRANSACT SQL .

  • Data types
  • List system objects  and attributes
  • Creating a table
  • Altering a table
  • Table creation – Alternatives
  • Indexes
  • Clustered vs. non-clustered indexes
  • Creating constraints
  • Defaults
  • Table partitioning
  • Object permissions
  • Binding Rules
  • Modifying a Column
  • Moving an object
  • Views
  • Stored Procedures
  • Triggers

Datatypes:–

Note:–Table with contents to be drawn……..

.

.

.

.

.

.

.

.

List System Objects & Attributes:–

  • List all table names for current database

select name
from sysobjects where type = ‘U’
go
OR
use system SP sp_tables

  • List all trigger names for current database

select name
from sysobjects where type = ‘T’
go

  • List all procedure names for current database

select name
from sysobjects where type = ‘P’
go

  • Display column definitions and indexes for emp table

sp_help emp
go

  • Display space used for emp table

sp_spaceused emp
go

  • Display source code for emp_proc

sp_helptext emp_proc
go

Creating a table:–

  • Defines each column in the table.
  • The table definition provides the column name, 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.

Design of Table for creating a table :–

  • Decide what columns you need in the table, the datatype, length, precision, and scale, for each column.
  • Create any new user-defined datatypes before you define the table where they are to be used.
  • Decide which column, if any, should be the IDENTITY column.
  • Decide which columns should and should not accept null values.
  • Decide what integrity constraints or column defaults, if any, you need to add to the columns in the table. This also includes rules, indexes, and triggers to enforce data integrity.
  • Decide whether you need defaults and rules, and if so, where and what kind. Consider the relationship between the NULL and NOT NULL status of a column and defaults and rules.
  • Decide what kind of indexes you need and where. Indexes are discussed later

Examples of creating a table:–

1.)
create table emp (
emp_id    numeric(8,0)  identity,
emp_name    varchar(50)   not null,
salary    money         not null,
dept_cd   char(3)       not null,
fax_no    integer       null
)
go

2.)
create table invoice (
invoice_id     numeric(8,0)  identity,
sales_rep_id   numeric(8,0)  not null,
date           smalldatetime not null,
comment        varchar(255)  null )
on data_seg2
go

3.)
create table  err_cd (
err_id       integer       not null,
err_desc     varchar(60)   not null,
constraint pk_err_cd primary key clustered (err_id)
)
go

Altering a table:–

Alter table examples
- alter table employee add cell_no numeric(10) null
go
- alter table employee drop constraint     ‘emp_dept_constr’
go
Default
alter table charge_item replace price_overridable_ind default 0
go

Change column name (quotes required)
sp_rename ‘emp.dept’,dept_name
go

Table Creation – Alternatives:—-

If you already have a table and would like to create another with the same column definitions, use ‘select into’
select * into my_copy from source_table

To capture a subset of the columns, replace * with names
select col1, col2 into my_copy from source_table

The above also copy the data to the new table

To skip the data copy, use an ‘empty where clause’
select * into my_copy
from source_table
where 1=0

Default rules are not copied to the new table
Indexes are not created on the new table
The database option
“select into/bulkcopy/pllsort” must be on in this database to use ‘select into’

Indexes:—

  • create unique clustered index emp_idx

on emp (emp_id)
go

  • create index emp_name_idx

on emp (emp_name)
go

  • create unique clustered index pk_invoice_data on invoice_data  with  sorted_data on segment1

go /* Creates sorted index on a segment */

  • Clustered
  • Non-clustered

Typically,
Clustered index will be created on the primary key of a table

Non-clustered indexes are used where needed.

Clustered Vs Non-clustered indexes:—

Clustered indexes:

  • Records in table are sorted physically by key values
  • Only one clustered index per table
  • Higher overhead on inserts, if re-org on table is required
  • Best for queries requesting a range of records
  • Index must exist on same segment as table

Non-clustered indexes:

  • Leaves are stored in b-tree
  • Lower overhead on inserts, vs. clustered
  • Best for single key queries
  • Last page of index can become a ‘hot spot’
  • Clustered indexes are sorted physically only upon creation if a table is created with “lock datapages” or “lock datarows” . The clustered index, thereafter behave as a non-clustered index

Creating a constraint:—

Constraints are used to define primary keys, enforce uniqueness, and to describe foreign key relationships. By default, indexes are created upon creation of unique or primary key constraints.

  • Primary key for the employee table
    alter table emp add constraint
    emp_constr primary key(emp_id)
    go
  • Add unique requirement for invoice table
    alter table invoice add constraint
    inv_constr unique nonclustered(cust_id,inv_date)
    go
  • Add foreign key for relationship between invoice and emp tables
    alter table invoice add constraint inv_fk_emp
    foreign key (sales_rep_id)
    references emp(emp_id)
    go

Defaults:–

  • Creating Defaults
    create default def_highsal as 15000
    go
  • Binding defaults
    sp_bindefault def_highsal,’emp.salary’
    go
  • Creating your own custom defaults has an advantage that the name of the default can be chosen to reflect the application/functionality.

Table Partitioning:–
Insert performance on partitioned tables is improved, as multiple ‘entry points’ (last page entries) are created. Partitioned tables require slightly more disk space and small bit of additional memory.

  • Create partitions for a table

alter table invoice — creates 3 partitions on invoice table
partition 3
go

  • Tables which span multiple segments

Tables containing large amounts of data (> 2 GB) need to be spread across several devices, using sp_placeobject. Note that this procedure affects only         future operations – if a table load of more than 2 GB is to be performed, it would have to be split into two or more stages.

  • Command – Span Multiple Segments

sp_placeobject ‘data_seg2′,’invoice’
go

Object Permissions:–

Object security is fairly straightforward and is handled using the ‘grant’ Transact SQL statement.

  • grant all on emp to Srinath

go

  • grant select on emp to Prashanth

go

  • grant update on emp to Prashanth

go

  • revoke select on emp from Prashanth

go

Stored procedure security allows you to grant access on a business logic basis. For example, if you had a stored proc that updated the invoice table and selected data from the customer table, you could grant the execute privilege on the stored proc, and you’re done. The user would be able to run the procedure to update/select from the tables, but will not get to the tables directly.

  • grant execute

on proc_upd_invoice to Srinath
go

Binding Rules to Columns:–
Default values for columns can be specified at the time a table is created, or afterwards via the modify command.

Examples
create table emp (
emp_id   integer  not null,
emp_name varchar(50) null,
salary   money    default 15000
)
go

alter table emp replace salary default 19000
go

Modifying Column:–

To modify/alter a column type you need to be “dbo” and have select into option enabled, in the database defaults.

create table emp (
emp_id   integer  not null,
emp_name varchar(50)  null,
salary   money    default 0
)
go

/* make the name column longer */
alter table emp modify emp_name varchar(100) not null
go

/* rename the column */
sp_rename ‘emp.emp_name’, name
go

Move objects to segments:–

When databases contain more segments, it is often necessary to move tables between segments.

Examples

  • Move a table entirely to a new segment

drop index ‘employee.idx_employee’
go
create clustered index on emp (emp_id) on new_seg
go

  • Leaving the table in the existing location but future allocations go to the new segment

sp_placeobject new_seg , ‘emp’
go

  • To leave a table in the existing location and use a new segment for future allocations of the text column (emp_notes):

sp_placeobject new_seg, ‘emp.emp_notes’

go

Views:–
Views offer an alternative way to look at data and can also be used to enforce security by limiting the data that is seen by users.

  • Create Views

create view emp_view
as select emp_id, emp_name from emp
where emp_id > 1 and emp_id < 101

  • Retrieve data via Views

select * from emp_view

  • Updates on views are possible but there are restrictions. Some update restrictions are:
  1. Views created with computed columns in the view definition.
  2. Underlying table objects having NOT NULL columns.
  3. Check option used for creation of views.
  4. Deletes are not allowed on views created with multiple objects.
  • The data accessed via a view must require permissions irrespective of the permissions existing in the underlying tables that are used to create the view. The data in the underlying tables that is not included in the view are not visible to the users.
  • Advantages:
  1. Provide the data to view that is of interest to a particular set of users.
  2. In cases where joins must be used in queries frequently, create a view with the underlying objects and the joins once and use select * from view
  3. Display different data to different target users with multiple views created using the same underlying data.

Stored Procedures:–

Stored procedures are compiled versions of SQL statements. Performance benefits are significant as network traffic is reduced, and the optimizer does not need to re-parse the code.

Stored Procedures are classified into:

  • System Stored Procedures – Defined by SYBASE and delivered as part of ASE.

Examples:
- sp_who –Provides information on users on ASE
- sp_help – Provides a information/listing of all objects in the current database.
All of the System Stored Procedures start with “sp_” and are located in the ‘sybsystemprocs’ system database

  • User Stored Procedures – Defined by the users of ASE in a designated user database.
  • Stored procedure to retrieve

create procedure proc_rtv_invoice
(@inv_id numeric(8,0) ) as
select inv_id, inv_date, salesrep_emp_id
from invoice
where inv_id = @inv_id
return
go

  • Execute the stored procedure

exec proc_rtv_invoice 325
go

Triggers:–
Trigger is a special type of SP that gets executed automatically when any DML operation takes place on a table.

  • Triggers are used to enforce referential integrity.
  • Triggers are used to cascade changes to related tables.
  • Triggers can be used to apply complex restrictions than that enforced using rules.
  • Trigger can perform analysis before and after changes to the table.
  • Triggers cannot have the following:
  1. create and drop commands.
  2. alter table, alter database, truncate table.
  3. Load database and transactions.
  4. Grant and revoke statements.
  5. update statistics
  6. reconfigure
  7. disk init, disk mirror, disk refit, disk reinit, disk remirror, disk unmirror
  8. select into
  • Trigger creation

create trigger emp_trigger
on emp
for insert, update, delete
as

  • Trigger Example

create trigger emp_trigger
on emp
for delete
as
delete payment
from payment, deleted
where payment.empid = deleted.empid

Leave a Comment

II. SYSTEM DATABASES AND TABLES.

II.   SYSTEM DATABASES AND TABLES.

When ASE is installed following databases are installed.

* master
* model
* sybsystemprocs
* tempdb

Optional databases that can be installed are

* sybsecurity
* sybsystemdb
* dbcc
* sybdiag
* pubs2  and pubs3

ASE  databases:

master database:–

Controls the operation of ASE and stores the information of user databases and devices on the ASE server

No.… Information…………………………………………….System Table
1        User accounts :……………………………………………….syslogins

2       Remote user accounts :…………………………………… sysremotelogins

3      Remote servers that this servercan interact with:….sysservers
4      Ongoing processes :………………………………………….sysprocesses
5      Configurable environment variables :………………….sysconfigures
6      System error messages:…………………………………….sysmessages
7      Databases on Adaptive Server:…………………………..sysdatabases
8     Storage space allocated to each database:……………..sysusages
9    Tapes and disks mounted on the system:……………… sysdevices
10    Active locks:…………………………………………………..syslocks
11    Character sets:………………………………………………..syscharsets
12    Languages:…………………………………………………….syslanguages
13    Users who hold server-wide roles:……………………. sysloginroles
14    Server roles:………………………………………………….syssrvroles
15    Adaptive Server engines that are online:…………….sysengines

model database:–-

All new user databases use model database as a template database. ASE copies this database whenever a new database is created and extends the space of the new user database as specified in the ‘create database’ command Use sp_tables system SP to get the list of system tables in model database.

sybsystemprocs:-–

All ASE system stored procedures are stored in this database.

tempdb :–-

This is a temporary database used by ASE. “tempdb” database is used to store temporary tables and other working structures.
tempdb is installed by default during ASE installation.
Multiple tempdb(s) can be created based on need.
Optional databases::

sybsecurity :–-

This database contains the audit system to audit database users activity on ASE.
sysbsystemdb:-–

This is used by ASE to store information of distributed transactions and provides transaction coordination for remote servers using RPCs and CIS services.

dbcc :-–

This database is used to store configuration information of target database operation activity and results of the operation from ‘dbcc checkstorage’

sybdiag :–-

This database may be created and used by SYBASE Technical Support to troubleshoot the system. The database holds diagnostic information.

pubs2 and pub3 :-–

These are learning databases provided by SYBASE.

Leave a Comment

I. Adaptive Server Enterprise(ASE) Overview.

I. A S E  OVERVIEW.

  • ASE Server
  • Memory Model
  • Transaction Processing
  • Backup Procedures
  • Recovery Procedures
  • ASE Logins
  • ASE Groups
  • Security and Account Setup
  • Database Creation
  • Storage Concepts
  • Transact SQL
  • Transact SQL Extensions

ASE Server:–

ASE server consists of

  • Two processes, data server and backup server.
  • Devices house the databases. Master database contains system and configuration data.
  • Configuration file contains the server attributes.
  • The logical page size of the server can vary between 2K to 16K (2K, 4K, 8K and 16K). 2K page size is the default.

Memory Model:–

The ASE executable runs as a single process within the OS. Multiple users connect to the database. Only one process is managed by the OS. Each Sybase database connection requires memory.

memory-model-ase

  • ASE executable or the dataserver executable resides in the program area.
  • Cache stores both Data Cache and Procedure Cache. Both have independent memory allocation.
  • The data cache stores recently fetched pages from the database device.
  • The procedure cache contains information of optimized sql calls.

Transaction Processing:–

  • Transactions are written to the data cache first and then they advance to the transaction log and database device.
  • Pages are discarded from the data cache on rollback.
  • Transaction logs are used to restore data in event of a hardware failure.
  • Checkpoint operation flushes all updated/committed memory pages to their respective tables.
  • Transaction logging is required for all databases. Image (blob) fields may be exempt.
  • During update transaction, the data page(s) containing the row(s) are locked.
  • Row level record locking is available and can be enabled. To facilitate this, the table structures may need to be tuned.

Backup Procedures :–

  • Backup procedures are facilitated by the backup server.
  • Backup procedure is carried out using “dump database” operation.
  • Backup operation can be performed when the database is on-line or offline.
  • Transactions can be dumped using “dump transaction” commands.

Recovery Procedures:–

  • Load procedures are facilitated by the backup server.
  • Load procedure is carried out using “load database” operation.
  • Load operation loads the designated database with the named dump file.
  • Transactions can be loaded using “load transaction” commands.
  • Transaction commands can then be issued to load multiple transaction dump files.

ASE Logins:–

Each Adaptive Server user must have a
login account. Characteristics of Login accounts

  • A login name is unique on the server
  • Password is required to login
  • A default database (optional) is assigned.
  • A default language (optional).
  • A full name (optional).

ASE Groups:–

  • A group is created within a database.
  • The Database Owner is responsible for creating groups and assigning users to them.
  • A login/user is always a member of the “public” group, which includes all users on Adaptive Server.
  • The login/user can also belong to one other group.
  • Use sp_helpuser system stored procedure to find out what group the user belongs to.

Security and Account Setup:–

  • The initial login shipped with ASE is “sa” (system administrator).
  • The “sa” login has the role “sa_role” which is the super-user.
  • User logins are added at the server level.
  • The login is granted access to one or more databases by adding the login as a user of the respective database.
  • Access is granted to one or more tables and objects within a database.
  • A user in a database can be aliased as “dbo”.
  • “dbo” has all rights within a database.

Database Creation:–

  • Databases are initialized with the “create database” command.
  • Many databases can exist in one ASE server.
  • Tables are created within each database.
  • ASE databases can reside on one or more segments/devices.

Storage Concepts:–

  • Tables are stored in segments.
  • Segment is an area within a device with a name and a size. A segment/device is allocated for a database.
  • The transaction log is stored in its own segment, usually on a separate device.

Transact-SQL:–

  • Transact-SQL is a robust programming language created by SYBASE to access the database and the underlying data in the tables.
  • ANSI 89 and 92 compliant.
  • Used for managing ASE database and server(s).

Transact SQL Extensions:–

  • Any number of result sets can be returned to calling applications via SELECT statements.
  • Triggers and Stored procedures (System and User) are supported for writing SQL that are stored in a compiled format, which allows for automatic execution and faster execution of DML SQL code.
  • Cursors are supported for row by row processing.
  • Functions (System/Arithmetic/Date/String), Rules and Defaults are supported.
  • Temporary tables are supported, which allows customized private work tables to be created for complex processes.
  • Global and Local variable support.
  • Flow control statements (IF-ELSE, WHILE …).
  • Federal Information Processing Standards (fipsflagger).

Leave a Comment

Sybase Exception Handling Standard

Exception Handlers:

In SQL server the errors are always written to sysmessages table, so no exception can be handled here. The type of access to the SQL server from the front end determines the state of the error and how the error information can be retrieved.

Eg.

a).  For ODBC type of access the error messages are stored in the  SQLError object of the SQL server, the front end should query that object to get the error message.

b).  For OLE-DB type of access the error messages are stored in the ISQLServerErrorInfo object. So the OLE-DB provider library

RAISERROR('Test Only',  1,  2) WITH SETERROR
SELECT @@ERROR
RAISERROR (101,  1,  2) WITH SETERROR
SELECT @@ERROR
Here is the result set:
Msg 50000,  Level 1,  State 50000
Test Only
-----------
50000
(1 row(s) affected)
Msg 101,  Level 1,  State 101
Line 0: SQL syntax error.
-----------
101
(1 row(s) affected)

The first RAISERROR returns an @@ERROR value of 50000. The second returns the syntax error message used by Microsoft® SQL Server™ with an @@ERROR value of 101.

Formatting T-SQL Blocks:

T-SQL blocks have the following sections:

  1. Header
  2. Declaration section
  3. Executable section.
  4. Exception section.

PROCEDURE (Parameters)
RETURN DATATYPE
AS
Variables DATATYPE;

BEGIN
Executable_statements;
If err then goto Err_block
RETURN Value

Err_block:
Process error and return the error string
END
GO

Recommendations:

  1. All the executable statements after the BEGIN and error handling block are indented in from the BEGIN
  2. Include a blank line after each section.
  3. IS statement to be on a new line where everused.

Formatting SQL  statement:

SELECT
INSERT
UPDATE
DELETE
SELECT  FROM WHERE GROUP BY HAVING ORDER BY
INSERT INTO VALUES OR INSERT INTO SELECT
UPDATE SET WHERE
DELETE FROM WHERE


Leave a Comment

Sybase Formatting Control Structures Standard

Control Structures

IF <expression> THEN
Executable_statements
ELSE
Executable_Statements

If executable statements are more than one statement then use BEGIN … END block for grouping the statements.

Recommendation:

  1. One line space after executable statements
  2. Executable statements should be indented atleast by 3  spaces.
  3. If the executable statements inside an IF statement clause themselves contain another IF statement, then IF- ELSE and keywords should be indented inside the enclosing IF statements for the inner IF should be indented further so that they are clearly with in the nested IF.

Formatting Loops

Transact-SQL offers the WHILE loop. The GOTO statement can also be used for looping purposes.

Syntax:

WHILE Boolean_expression
{sql_statement | statement_block}
[BREAK] [CONTINUE]

Eg:
WHILE condition
Executable_Statements
END

BREAK / CONTINUE can be used within the loop to encounter the exceptions.

Each loop has a loop boundary and a loop body. The loop body should be indented from the boundary.

Leave a Comment

Other Sybase Standard and Guidelines

Rule

  1. Where possible, areas of common processing must be implemented by procedures. Note: Maximize re-use of pre-parsed statements.
  2. For triggers of any complexity the detailed logic must be coded in procedures which are invoked from within the trigger body.
  3. Object names must not be qualified with the owner name. Note: The statement cannot be run in another schema if the owner is specified.
  4. Whenever an explicit insert statement is used, the list of columns into which data is being inserted must be specified. Note: Insert statements must take the form INSERT INTO table (col1, col2) VALUES (val1,val2).
  5. SELECT * FROM table_name should be avoided. You must explicitly name the columns being selected.
  6. Transact SQL variables holding values for a particular column should be named @<column_name>.
  7. Stored procedure parameters should be named @p_<parameter  name>.
  8. A variable/parameter domain should be evident from the name.   

Leave a Comment

Sybase Naming Convention Standard

The naming convention for variables and constants is as follows:

1.  Program Structure

The following should be the templates used in T-SQL source code files.

Any T-SQL source file should have a file header of the following format (Header) followed by the body of the procedure. Since SQL server doesn’t support the concept of Packages the only type of header is as follows:

/*
**  (C) <Year>, Deutsche Bank Group

**  Name  :  (name of the package/procedure/function)

**  Description :

**  Author  :

**  MODIFICATION  HISTORY :
**  The history  of changes should be in chronological sequence

Date       Name of the Proc/ Func       Author        Reasons for Change

[Comments by Version control system will be included in this block].
[The position of the same depends on the version control software and projects].
*/

Some general rules to be followed for functions / procedures.

  • The calling procedure/function should always have to check the   return status and proceed with further processing.
  • For example, the following statement should not be used

Insert into table_one select * from table_two;

The select * statement should not be used because, the statement would be invalid in case the structure of the table changes. So the columns have to be explicitly mentioned.

1.1 Indenting

Tabbing is used for indenting. Statement blocks used with the following statements are indented one tab stop from the corresponding statements.

  • Loops and
  • Conditional Statements.

1.2  Spacing

A single space should be placed before and after all operators.  A single space should also be placed after the comma of each argument in function parameter lists.

1.3  Comments

  • Comments should be placed at the beginning of scripts. Comments at the beginning of functions/procedures should describe the valid values for parameters and what the possible return codes are.
  • Global and Local variable declarations should also contain comments that identify their usage.
  • Comments should be placed at the place of modification. In case of a change request, change request number also has to be placed.

Leave a Comment

Sybase Standard for Stored Procedures and Triggers

Rule for Stored Procedures

  1. Procedures should be named PROC_<procedure_name>

Rule for Triggers

  1. Triggers must be named TR<type>_<table name>_<seq> where <type> is ‘I’, ‘U’ or ‘D’ and <table_name> is truncated to 24 characters. (‘I’ represents Insert; ‘U’ represents Update; and ‘D’ represents a delete).


Leave a Comment

Sybase Identity Columns Creation Standard

Rule

  1. Identity columns should be used for all generated numbers where a gap in the sequence is not significant. i.e surrogate primary keys.
  2. If control of a sequence needs to be retained then this should be implemented using a row in a specific table which holds the next available number in the sequence, this should be locked, used and then updated.

Leave a Comment