Você está na página 1de 31

SYBASE ADAPTIVE SERVER ENTERPRISE

Filed in Sybase on May.27, 2009

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.


Filed in Sybase on May.26, 2009

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.


Filed in Sybase on May.26, 2009

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.


Filed in Sybase on May.16, 2009

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.

 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


Filed in Standard of Sybase on May.14, 2009

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


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

Leave a Comment

Sybase Formatting Control Structures Standard


Filed in Sybase on May.14, 2009

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


Filed in Sybase on May.14, 2009

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
Filed in Sybase on May.14, 2009

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


Filed in Sybase on May.14, 2009

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).

Sybase Standard For Index and Guideline


Filed in Sybase on May.13, 2009

Rule
1. Primary and Unique Key constraints are automatically indexed by the database
when the constraint is enabled and cannot be indexed separately.
2. Foreign Key columns should only be indexed where they improve performance.
3. Additional non-unique indexes must only be created for specific performance
reasons on the basis of demonstrated need.
4. Redundant Indexes must be removed.
5. Two indexes must not share the same leading edge, i.e. The same column(s) as
the first part(s) of the index.
6. Indexes must be named <table name>_<index type><seq> where <index type>
is: ‘PK’, ‘AK’, ‘FK’ or ‘IK’ and <table name> is truncated to 25 characters. 
Note: ‘PK’ refers to a Primary Key index,  ‘FK’ refers to a Foreign Key index,
‘AK’ refers to an Alternate Key index,  ‘IK’ refers to a non-unique index.
7. Indexed columns must be specified in order of decreasing selectivity, i.e. the first
column in the index should have the highest number of distinct values. Note: This
is to enhance performance.
8. Columns with only a few distinct values relative to the total number of records
must not be indexed. Bitmap Indexes should be used only when there is little or
no update activity and tables have low cardinality.  Note: A serial scan through
the table is faster.

Guidelines

1. A further consideration to the ordering of columns in indexes is that it may be


possible to cover a number of  indexing requirements through only one index.
2. The indexing of frequently updated columns should be carefully considered as the
cost of maintaining the index may outweigh the benefits of the index.  Note: If a
column is frequently updated then having an index on it will impact performance
because the index will also need to be maintained and this may not be acceptable.

Leave a Comment

Constraints and Guidlines


Filed in Sybase on May.12, 2009

Standards to create the constraints

Rule

1. Each table must have one or more unique identifiers. At least one must be
implemented as a primary key.
2. The unique identifier must have true business meaning where possible, and not
simply be a generated sequence number. A surrogate key may be used where
performance considerations would warrant it.
3. If relationships exist between tables then they should be enforced using a foreign
key constraint (unless triggers are being used to enforce advanced RI)
4. Check constraints must be used to restrict the allowable values of columns for
appropriate business rules where the list of values is relatively small.

Guidlines

1. Primary keys constraints should be named PK_<table name>


2. Alternate/unique constraint should be named AK_<table name>_<seq>
3. Foreign keys constraints should be named FK_<table name>_<seq>
4. Default constraints should be named DF_<constraint name>
5. Check constraints must be named CC_<constraint name>

Leave a Comment

Sybase Column Creation Standard


Filed in Standard of Sybase on May.12, 2009

Standard to create the columns:

1. The column name should be of the form XX<Abbr/Name><suffix> (XXX


represents the abbreviation of the Table Name.It should be a meaningful
abbreviation of the table name to which the column belongs.<suffix> is a
meaningful suffix).
2. Column name should  not be  longer than 30  Alphanumeric characters.
3. Column name (<Abbr/Name> only) should be same throughout an  application
even though the field may be present in more than one table.

The following suffixes can be used for better understanding.

ata Suffix
CODES Code
IDENTIFIER Id
INDICATOR/FLAG Flag
AMOUNT Amount
RATES Rate
KEY Key
Number Number
Name Name
Type Type
Leave a Comment

Sybase Tables Creation Standard


Filed in Standard of Sybase on May.12, 2009

Standards to create the tables:

1. The table name should be the same as the logical entity name or should bear some
significance to the data stored therein.
2. The table must have a primary key that uniquely identifies each row.
3. The column names will be same as logical attribute name.
4. Columns must be defined as NOT NULL wherever possible.
5. Table names should be no more than 30 alphanumeric characters.

For Examples creating the tables : AccountMaster , CashBalance , TransactionDetail

Guidelines to create the tables:

1. Keep table names to around 20 characters. This will prevent the truncation of
table name in the naming of other objects that contain the table name as part of
the object name. e.g. Indexes
2. Columns may only be denormalized to improve performance, but this should be
very carefully balanced against the additional update that may be required.

Leave a Comment

Naming Conventions in Sybase


Filed in Sybase on May.11, 2009

 General Naming Conventions

1.  Names must be a maximum of 30 characters long.


2. Unless absolutely necessary only alphanumeric characters and underscores should
be used.
3. Each word in a name must be separated by an underscore.
4. Names are not to be considered case-sensitive.
5. A name cannot be a Sybase SQL Server Reserved Word or Keyword. (Please
refer to the Sybase Adaptive Server Reference manual for a full list)
6. A database object name must be unique across the database

Leave a Comment

Sybase CODE REVIEW CHECKLIST


Filed in Sybase on May.11, 2009
No. Item
1 Standards/documentation
  Database objects names less than or equal to 30 characters
  Stored procedures P<event type>_< procedure_name >.
Event Type:
P – Process, S – Select, I – Insert, U – Update, D – Delete, IU –
Insert/Update
  Conformance to coding standards
Naming conventions to be followed for database objects such as
tables,indexes,views,constraints,triggers.
  Documentation in code:
Sufficient
Redundant
Correct (conforms to code)
   
2 Logic coverage
  Programming logic:
correct (conforms to specifications)
Use transactions inside stored procedures and check the return
status .
   
3. Data reference
  Variables initialized with proper datatype and size. Specify Null and
output,if required
  No unused variables.
  Define global variables for error checking and count.
   
4 Control flow
  Condition for loop termination exists(while, if-else) .No abnormal
exits.
  Loops to have break/continue for exception handling.
  Boundary conditions and value range covered
  GOTO for looping purposes.
   
5. Interface
  Datatypes of parameters passed/ received are consistent
  Lengths of parameters passed/received are correct
  Return codes correct.
   
6. Formatting and indentation
  Blocks for header,declaration,executable and exception sections.
  Proper indentation within the blocks.
  Proper formatting for DDL and DML  statements.
   
No. Item
7. Others
  Comments for understanding logic flow.
  No unused functions/code.
  Raise error messages, if any.
   

Leave a Comment

Sybase ASE tip: Tempdb Space Management


Filed in Sybase on Apr.23, 2009

A default installation of Sybase ASE has a small tempdb located on the master device.
Almost all ASE implementations need a much larger temporary database to handle sorts
and worktables and therefore DBA’s need to increase tempdb.

This document gives some recommendations how this could be done and describes
various techniques to guarantee maximum availability of tempdb.

Content
• About Segments
• Prevention of a full logsegment
• Prevention of a full segment for data
• Separation of data and log segments
• Using the dsync option
• Moving tempdb off the master device
• Summary of the recommendations

About Segments
Tempdb is basically just another database within the server and has three segments:
’system’ for system tables like sysobjects and syscolumns, ‘default’ to store objects such
as tables and ‘logsegment’ for the transaction log (syslogs table). This type of
segmentation, no matter the size of the database, has an undefined space for the
transaction log; the only limitation is the available size within the database. The
following script illustrates that this can lead to nasty problems.

create table #a(a char(100) not null)


go
declare @a int

Running the script populates table #a and the transaction log at the same time, until
tempdb is full. Then the log gets automatically truncated by ASE, allowing for more rows
to be inserted in the table until tempdb is full again. This cycle repeats itself a number of
times until tempdb is filled up to the point that even the transaction log cannot be
truncated anymore. At that point the ASE errorlog will show messages like  “1 task(s) are
sleeping waiting for space to become available in the log segment for database tempdb”.

When you log on to ASE to resolve this problem and you run an sp_who, you will get
“Failed to allocate disk space for a work table in database ‘tempdb’. You may be able to
free up space by using the DUMP TRANsaction command, or you may want to extend
the size of the database by using the ALTER DATABASE command.”.

Your first task is to kill off the process that causes the problem, but how can you know
which process to kill if you even can’t run an sp_who? This problem can be solved with
the lct_admin function. In the format lct_admin(“abort”,0,) you can kill sessions that are
waiting on a log suspend. So you do a:

select @a = 1

while @a > 0
begin
insert into #a values(“get full”)
end
go

select lct_admin(“abort”,0,2) –- 2 is dbid for tempdb.

When you execute the lct_admin function the session is killed but tempdb is still full. In
fact it’s so full that the table #a cannot be dropped because this action must also be
logged in the transaction log of tempdb. Besides a reboot of the server you would have no
other option than to increase tempdb with just a bit more space for the logsegment.

alter database tempdb log on <some_device> = <number of Mb’s>

This extends tempdb and makes it possible to drop table #a and to truncate the transaction
log.

In a real-life situation this scenario could cause significant problems for users.

Prevention of a full logsegment


One of the database options that can be set with the sp_dboption stored procedure can be
used to prevent this. When you do:

sp_dboption tempdb,”abort tran on log full”,true

(for pre 12.5.1: followed by a checkpoint in tempdb) the transaction that fills up the
transaction log in tempdb is automatically aborted by the server.

Default or system segments are full


The default or system segments in tempdb, where the actual data is stored, can also get
full, just like any ordinary database. Your query is cancelled with a Msg 1105 “Can’t
allocate space for object ‘#a_____00000180017895422′  in database ‘tempdb’ because
‘default’ segment is full/has no free extents. If you ran out of space in syslogs, dump the
transaction log. Otherwise, use ALTER DATABASE or sp_extendsegment to increase
size of the segment”.

This message can be caused by a query that creates a large table in tempdb, or an internal
worktable created by ASE used for sorts, etc.
Potentially, this problem is much worse than a full transaction log since the transaction is
cancelled. A full log segment leads to “sleeping” processes until the problem is resolved.
However, a full data segment leads to aborted transactions.

Prevention of a full segment for data


The Resource Governor in ASE allows you to deal with these circumstances. You can
specify just how much space a session is allowed to consume within tempdb. When the
space usage exceeds the specified limit the session is given a warning or is killed. Before
using this feature you must configure ASE to use the Resource Governor:

sp_configure “allow resource limits”,1

After a reboot of the server (12.5.1. too) you can use limits:

sp_add_resource_limit “petersap”,null,”at all times”,”tempdb_space”,200

This limit means that the user petersap is allowed to use 200 pages within tempdb. When
the limit is exceeded the session receives an error message (Msg 11056) and the query is
aborted. Different options for sp_add_resource_limit make it possible to kill the session
when the limit is exceeded.
Just how much pages a user should be allowed to use in tempdb depends on your
environment.
Things like the size of tempdb, the number of concurrent users and the type of queries
should be taken into account when setting the resource limit. When a resource limit for
tempdb is crossed it is logged into the Sybase errorlog. This makes it possible to trace
how often a limit is exceeded
and by who. With this information the resource limit can be tuned.
When you use multiple temporary databases the limit is enforced on all of these.

Separation of data and log segments


For performance reasons it makes sense to separate the system+default and the
logsegment from each other. Not all sites follow this policy. It’s a tradeoff between
flexibility to have data and log combined and some increased performance. Since tempdb
is a heavily used database its not a
bad idea to invest some time into an investigation of the space requirements.

The following example illustrates how tempdb could be configured with separate devices
for the logsegment and the data. The example is based on an initial setting of tempdb on
the master device.
First we increase tempdb for the system and data segments:

alter database tempdb on <your data device> = <number of Mb>

Then we extend tempdb for the transaction log:

alter database tempdb log on <your log device> = <number of Mb>

When you have done this and run an ‘sp_helpdb tempdb’ you will see that data and log
are still on the same segment. Submit the following to resolve this:

sp_logdevice tempdb, <your log device>

Please note that tempdb should not be increased on the master device.

Using the dsync option


The dsync option for devices allows you to enable/disable I/O buffering to file systems.
The option is not available for raw partitions and NT files. To get the maximum possible
performance for tempdb use dedicated device files, created with the Sybase disk init
command. The files should be
placed on file system, not on raw partitions. Set the dsync option off as in the following
example:

disk init name = “tempdb_data”,  size= “500M”,


physname= “/var/sybase/tempdb_data.dat”,
dsync = false

Moving tempdb off the master device


When you have increased tempdb on separate devices you can configure tempdb so that
the master device is unused. This increases the performance of tempdb even further.
There are various techniques for this, all with their pros and cons but I recommend the
following.
Modify sysusages so that segmap will be set to 0 for the master device. In other words,
change the segments of tempdb so that the master device is unused. This can be done
with the following statements:

sp_configure “allow updates to system tables”,1


go
update master..sysusages
set segmap = 0
where dbid = 2
and lstart = 0
go
sp_configure “allow updates to system tables”,0
go
shutdown -- reboot now!
go
When you use this configuration you should know the recovery procedure just in case
one of the devices of tempdb gets corrupted or lost. Start your ASE in single user mode
by adding the –m switch to the dataserver options. Then submit the following statements:

update master..sysusages set segmap = 7


where dbid = 2
and lstart = 0
go
delete master..sysusages
where dbid = 2
and lstart > 0
go
shutdown -- reboot now!
go

Remove the –m switch from the dataserver options and restart ASE. Your tempdb is now
available with the default allocation on the master device.

Summary of the recommendations


• Set the option “abort tran on log full” for tempdb to on
• Create resource limits
• Place data and log segments on separate devices
• Place tempdb on filesystem with dsync set to false
• Move tempdb off the master device by modifying the segmap attribute

Você também pode gostar