Sunteți pe pagina 1din 22

http://dba.fyicenter.

com/Interview-Questions/SYBASE/
Sybase Interview Questions and Answers:Theoritical
1
what is stored procedure?what is the maximum parameter can pass through it?
It is a db objects that exists independly of the table ,Which contain a set of q
uery.maximum paraperters pass through it is 255
2
what is Advantage of stored procedure?
faster execution,reduce network traffic,Modular programming,reduced operator ero
r,enforced consistency
3
what is Trigger?how many trigger can a table have and what are?
It is internal part of a statement that fired when insert,update,delete operatio
n taken place.Three trigger,Triggers are special kind of stored procedures that
get executed automatically when an INSERT, UPDATE or DELETE operation takes plac
e on a table.
4
What is magic table?
The table that exists within a trigger named as Inserted and deleted are Magic t
able
5
what is view?how many table can join for creating view?
It is logical way of looking at physical data located in a table,16
6
how will you add a column and drop a column?
Alter table table name [add][drop][modify] column name
7
explain about @@sqlstatus?
It returns the status of the pervious fetch statement in a cursor
8
compare WHERE clause and HAVING clause?
Where clause cannot have Aggeregate function ,and it select the row before the g
roup by function .having select the row after the group by
9
What is dead lock?
A deadlock occurs when there is a cyclic dependency between two or more transact
ions for the same set of resources.
10
What is sp_dboption?
It is used to enable or disable db option for your database
sp_dboption,'select into', true
11
What is CURSOR?
It is a pointer , use for row by row operation
12
Why we should go for Deallocating the cursors?
When we Deallocate the cursor so that server will clear the memory space occupie
d by the cursor we can use that space for some other action
13
How many index can have for a table?
250
14
What is Clustered and Nonclustered index?
When you craete a clustered index on a table, all the rows in the table are stor
ed in the order of the clustered index key. So, there can be only one clustered
index per table. Non-clustered indexes have their own storage separate from the
table data storage. Non-clustered indexes are stored as B-tree structures (so do
clustered indexes), with the leaf level nodes having the index key and it's row
locater
15
How do I get the Duplicate rows from a table?
select * from table group by column having count(*)>1
16
While creating index I forgot to tell what type what will happen?
nonclustered index
17
Compare Primary key and Unique key?
Both primary key and unique enforce uniqueness of the column on which they are d
efined. But by default primary key creates a clustered index on the column, wher
e are unique creates a nonclustered index by default. Another major difference i
s that, primary key doesn't allow NULLs, but unique key allows one NULL only.
18
What is bcp.How do you invoke bcp command
It is used for import and export the values from table to os file and vice-ver.F
ast bcp and Slow bcp
Invoking the bcp command is as follows:-
bcp <database_name> -S <server_name> -U <user_name> -P <password> in|out <datafi
le> -e <err_file> -F <first row> -L <Last row> -b <batch_size>
-t <field_terminator> -r <row_terminator>
bcp -v displays version no of bcp.
19
Compare left and Right Outer Join?
For left join all row was selected in outer table and for inner table row which
are not meet the join condition are filled with NULL. In Right join inner table
all row was selected and for outer table the rows which not meet the join condit
ins will filled with NULL
20
While bcp in default,rules,constraints can be applied?
Only default can apply

21
What is Hotspot?
Whan a multipe processes attempt to modify a same page in table
22
How do I force the lock?
Using Holdlock.
All select/readtext statements acquire shared locks to retrieve their informatio
n. After the information is retrieved, the shared lock(s) is/are released.
The holdlock option is used within transactions so that after the select/readtex
t statement the locks are held until the end of the transaction:
* commit transaction
* rollback transaction

If the holdlock is not used within a transaction, the shared locks are released.
23
What is Isolation levels and explain them?
The categories of locking behavior within transaction that are defined by ANSI,L
evel are 0,1,2,3
Each isolation level specifies the kinds of actions that are not permitted while
concurrent transactions are executing. Higher levels include the restrictions
imposed by the lower levels:
Level 0 - allow reading uncommitted data[allow dirty reads]
Level 1 - Doesnt allow dirty reads.default isolation level for ASE.
Level 2 - prevents non-repeatable reads.
Such reads occur when
one transaction reads a row and a second transaction modifies that row. If
the second transaction commits its change, subsequent reads by the first
transaction yield different results than the original read
Level 3 - prevents phantom rows.
Phantom rows occur when one
transaction reads a set of rows that satisfy a search condition, and then a
second transaction modifies the data (through an insert, delete, update, and
so on). If the first transaction repeats the read with the same search
conditions, it obtains a different set of rows.
24
how to get Yesterday s date?
dataadd(dd,-1,getdate())

25
What is I option in Sybase tools?
It is the name of the interface file to use when trying to find a server to conn
ect to
27
What are defaults? Is there a column to which a default can't be bound?
When you are inserting suppose forgot to enter the value for particular column t
han you will provide some constant value for that .identity ,timestamps column a
re default cannot bound.

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. You can use
defaults and rules to help maintain the integrity of data across the
database.

create default <default_name> as "UNKNOWN"


sp_bindefault <default_name>,<column_name>
28
If I want current database name?
select db_name()
29
If i want creation text of a particular object (such as SP,Trigger,view,rule,def
ault)what shall i do
sp_helptext,defncopy,syscomments

30
Compare Join and SubQuery in performance?
Generally Join queries consume more memory than sub query. Sub query in turn inv
olve intermediate table creation so affects performance, because of high I/Os fe
tches need for processing. If the RAM memory is more, then the Joins can be used
instead of sub queries. Under memory constraints we can go for sub queries.
Sometimes sub queries are flattened to join to improve the performance. Also mak
ing the outer query to compare inner query with equality option can materialize
the subquery.

31
What are the different types of lock in Sybase?
There are three types of locks:
* page and row locks
* table locks
* demand locks
Page Locks
----------
There are three types of page locks:
* shared
* exclusive
* update
Shared locks
Adaptive Server applies shared locks for read operations. If a shared lock
has been applied to a data page or data row or to an index page, other transact
ions can also acquire a shared lock, even when the first transaction is active.
However, no transaction can acquire an exclusive lock on the page or row until a
ll shared locks on the page or row are released. This means that many transactio
ns can simultaneously read the page or row, but no transaction can change data o
n the page or row while a shared lock exists. Transactions that need an exclusiv
e lock wait or block for the release of the shared locks before continuing.
By default, Adaptive Server releases shared locks after it finishes scanni
ng the page or row. It does not hold shared locks until the statement is complet
ed or until the end of the transaction unless requested to do so by the user. Fo
r more details on how shared locks are applied, see Locking for select queries at
isolation Level 1 .
*
Exclusive locks
Adaptive Server applies an exclusive lock for a data modification operatio
n. When a transaction gets an exclusive lock, other transactions cannot acquire
a lock of any kind on the page or row until the exclusive lock is released at th
e end of its transaction. The other transactions wait or block until the exclusive
lock is released.
*
Update locks
Adaptive Server applies an update lock during the initial phase of an upda
te, delete, or fetch (for cursors declared for update) operation while the page
or row is being read. The update lock allows shared locks on the page or row, bu
t does not allow other update or exclusive locks. Update locks help avoid deadlo
cks and lock contention. If the page or row needs to be changed, the update lock
is promoted to an exclusive lock as soon as no other shared locks exist on the
page or row.
In general, read operations acquire shared locks, and write operations acquire e
xclusive locks. For operations that delete or update data, Adaptive Server appli
es page-level or row-level exclusive and update locks only if the column used in
the search argument is part of an index. If no index exists on any of the searc
h arguments, Adaptive Server must acquire a table-level lock.
Table Locks
-----------
There are three types of table locks:
* intent
* shared
* exclusive
intent
An intent lock is held as long as page or row locks are in effect for the transa
ction.
Shared lock
This lock is similar to a shared page or lock, except that it affects the entire
table. For example, Adaptive Server applies a shared table lock for a select co
mmand with a holdlock clause if the command does not use an index. A create nonc
lustered index command also acquires a shared table lock.

Exclusive lock
This lock is similar to an exclusive page or row lock, except it affects the ent
ire table. For example, Adaptive Server applies an exclusive table lock during a
create clustered index command. update and delete statements require exclusive
table locks if their search arguments do not reference indexed columns of the ob
ject.

Demand Locks
------------
A demand lock prevents further shared locks from being set. The SQL Server sets
a demand lock to indicate that a transaction is next in queue to lock a table or
a page.

32
List out all System procedure in your server?
select name from sysobjects where type='P'
33
There's a performance issue What will be your very first step towards the soluti
on?
First you need to identify which query is creating the problem and than to ident
ify where the problem lies in that query. Query that is taking maximum time is t
he first you want to consider for the optimization. To check which query is taki
ng maximum time to execute place getdate() both before and after the query. Iden
tity the type of the query whether it is a data look-up query, or data modificat
ion query.
34
What is @@rowcount?
returns the no of rows affected by the preceding query
35
How do you check whether the rollback was correct?
By checking the @@trancount value before rollback statement execute.
36
What is Index Covering?
Index covering is a mechanism for using the leaf level of nonclustered index the
way the data page of a clustered index would work. Index covering occurs when a
ll columns referenced in a query are contained in the index itself.Index coverin
g can produce dramatic performance improvements as data is read from index and n
ot from the table.
37
How do you select unique rows using Sybase?
using Distinct keyword
39
How many database Sybase 11 have ,list out with explanations?
four.Master,Model,sybsystemprocs,sybsystemdb,tempdb
Master - controls the user databases and the operation of Adaptive Server as a w
hole.
Model- used as a template for creating user database.
sybsystemprocs - contains system procedures
sybsystemdb - contains info about distributed transactions.
tempdb- contains info about temporary tables and those created with tempdb..

40
What is Roll Forward and Roll Back?
Roll forward:Committed transaction not written to data area are rolled forward i
nto the data.
Sybase has provided the log roll forward capability with the snapshot feature to
support rolling the database forward from the restored
snapshot to the last committed transaction.
Roll back :Uncommited transactions are rolled back.All data modification done
with in transaction are reversed.

41
If I want to round the value 999.99 as 1000 ?
round(999.99,0)
42
What is Phantom reads?
when one transaction reads a set of rows that satisfy a search
condition, and then a second transaction modifies the data (through an
insert, delete, update, and so on). If the first transaction repeats
the read with the same search conditions, it obtains a different set
of rows.
43
How will you Restart and Exit on while loop?
continue,break
44
Compare Delete and Truncate?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in t
he transaction log, which makes it slow. TRUNCATE TABLE also deletes all the row
s in a table, but it won't log the deletion of each row, instead it logs the dea
llocation of the data pages of the table, which makes it faster. Of course, TRUN
CATE TABLE can be rolled back.
45
How many columns can table have?
250
46
How will you find second maximum value in a table?
select max(column1) from table where column1<(select max(column1) from table)
47
How shall I simulate from level 0 to level 3 in Isolation?
using holdlock
48
Can I explicitly insert a value in a Identity column?
Yes,using set identity_insert p2000_code_p2k on
insert p2000_code_p2k (class,code) values(101,"PHAN")
49
Can I change the data type of column ?
yes using modify keyword
50
How will you tune a query?
http://sybasease.blogspot.com/
1.set showplan on - shows the query plan that was executed.
2.dbcc traceon (3604,302,310,317)
3604 - Directs trace output to the client,rather than error log
302 - Prints information on index selection.
The output from this trace facility is more detailed than showplan and
statistics io output, but it provides information about why the optimizer
made certain query plan decisions.The query cost statistics printed by dbcc trac
eon(302) can help to explain,
for example, why a table scan is chosen rather than an indexed access, why
index1 is chosen rather than index2, and so on.
310- dbcc traceon(310) provides information about the join
order selection step.dbcc traceon(310) prints the first plan that the optimizer
considers, and
then each cheaper plan, with the heading NEW PLAN.
To see all of the plans, use dbcc traceon(317).
3.set forceplan [on|off]
Instead of forcing a plan you think is best, you may want to consider why the op
timizer is choosing the "wrong" plan. That's where the aforementioned tracing ca
n help.
As a quick fix, though, make sure your statistics and stored procedures are up t
o date! The optimizer depends on its accuracy for the best results.
update statistics table_name [index_name]
exec proc_name with recompile.
--------------------------
4. How to get the list of tables in Sybase?
select * from sysobjects where type = 'U'
6. What are the vital features of Sybase?
1. Manages User Connection
2. Enforces Business Rules
3. Provide Recovery and BackUps
4. Understand T-SQL
5. Optimize Query Execution
6. Maintain Databases with NO Redundancy
7. Supports Data and Referential Integrity
7. What is the command for quitting from Sybase isql session? quit or exit.
10. What is a bind cache?
sp_bindchache <cache_name>,<object name> --> Binding a db object to a cache.
15. How to find the 2 minimum salaries in a table?
select min(sal) from salaries where sal>(select min(sal) from salaries)
20. A column name is given to you. You have to find out which table has that col
umn. Database has 230 tables. For example: empid (column name) For this how do y
ou find out which table has the column (empid) ?
select name from sysobjects where type = 'U' and id = ( select id from syscolumn
s where name = 'empid')

22. What is the difference between sybase 12.5 and 15?


1.Login triggers: Were introduced in ASE 15.0
A login trigger is basically a regular ASE stored procedure, which is automatica
lly executed in the background when a user successfully logs in to ASE.
2.Fast bcp: In 15.0.2, fast BCP is also allowed for indexed tables. Rest all thi
ngs about bcp remain same, like select into/bulkcopy/pllsort' is enabled; loggin
g only the page allocations in log etc.
3.sp_displaylogin displays when and why a login was locked & also when you last
logged in.
4.Semantic partitions/smart partitioning: ASE 15 makes large databases easy to m
anage. And more efficient by allowing you to divide tables into smaller partitio
ns which can be individually managed. You can run maintenance tasks on selected
partitions to avoid slowing overall performance, and queries run faster because
ASE 15's smart query optimizer bypasses partitions that don't contain relevant d
ata.
5.Scrollable cursors: With large data sets, filing through a mountain of results
data can be difficult. ASE 15?s bi-directional scrollable cursors make it conve
nient to work with large result sets because your application can easily move ba
ckward and forward through a result set, one row at a time. This especially help
s with Web applications that need to process large result sets but present the u
ser with subsets of those results
6.Computed columns: Often applications repeat the same calculation over and over
for the same report or query. ASE 15 supports both virtual and materialized col
umns based on server calculations. Columns can be the computed result of other d
ata in the table, saving that result for future repeated queries
7.Functional indexes: When applications need to search tables based on the resul
t of a function, performance can suffer. Functional indexes allow the server to
build indexes on a table based on the result of a function. When repeated search
es use that function, the results do not need to be computed from scratch
8.Plan viewer in the form of a GUI: Plans for solving complicated queries can be
come very complex and make troubleshooting performance issues difficult. To make
debugging queries simpler, ASE 15 provides a graphical query plan viewer that l
ets you visualize the query solution selected by ASE's optimizer.
9.In ASE 15.0, Update statistics is not necessary after index rebuild. Also sp_r
ecompile is not necessary after index rebuild.

10.ASE 15 allows you to assign two billion logical devices to a single server, w
ith each device up to 4 Tb in size. ASE 15 supports over 32,767 databases, and t
he maximum size limit for an individual database is 32 terabytes, extending the
maximum storage per ASE server to over 1 million terabytes!
11.As of release 12.5.1, all changes to data cache are dynamic
12.ASE 15.0 and later versions no longer use vdevno. i.e. the disk init syntax d
oesn?t need to mention the vdevno parameter.
13.Disk init syntax in 12.5 expects size parameter in K, M, and G only. From 15.
0 and onwards, T (Terabyte) can be specified.
Also, pre 15.0; the maximum size of a device was 32GB
14.The configuration parameter ?default database size? was static in ASE 12. In
ASE 12.5, it was made dynamic.
For ASE 15.0, the below table is specified by Sybase.
Logical Page Size 2K 4K 8K 16K
Initial default database size 3MB 4 MB 8 MB 16 MB
All system tables, initially 1.2 MB 2.4 MB 4.7 MB 9.4 MB
15.In 12.5.0, auto database extension was not present. It was introduced in 12.5
.1 and later versions.
16.The Dump/Load Database and Dump/Load Tran syntax differ from version 12.5.0.3
and 12.5.2(and hence later versions) (See sybooks for more information. The com
pression levels 1-9
were introduced.)
17.ASE 12.5.0.3 and earlier versions used to allow only one tempdb in the server
. But all the later versions allow creation of multiple temporary databases.
18.Before 15.0, after changing a database option we need to use that database an
d do checkpoint on it. But ASE15.0 doesn?t need this.
19.Restricting proxy authorization is available in 12.5.2 and later releases onl
y.
20.From version 12.5.2 and onwards, cache creation is made dynamic (sp_cacheconf
ig [cachename [,"cache_size [P|K|M|G]?] It was static earlier.
21.Till 12.5.2, backing up a database with password was not possible. ASE 12.5.2
and later allow dump database with passwd.
22.Cross platform dumps and loads were introduced in ASE 12.5.3
23.MDA tables (Monitoring and Diagnostic Tables) are available in 12.5.3 and lat
er releases.
24. Row Level Locking: In ASE 15.0 all the system tables were converted into dat
arows format.
23. What is Sybase Adaptive Server Enterprise?
Adaptive Server Enterprise (ASE) is Sybase Corporation's flagship enterprise-cla
ss relational model database server
25. What are table partitions? how is it different with ASE 15.0 version?
Partition is a old technology helps to access data faster (not actually faster)
in almost all the databases. Sybase ASE 15.0 opens up a new possiblity of this.
Sybase ASE contains semantic Partioning which is not available in Oracle latest
version called "Semantic Partioning" Because of this at the time of table defini
tion itself you can mention a certain set of data (for example Countrycode 'US'
) can sit on a separate partionin. More over it has range based partition and al
gorithm based partition.
26. When you change a database option when will it take effect?
In pre sybase 15 all database options will take effect after a use database and
checkpoint command is run.
For Sybase 15 the option take effect immediately since all sp_dboption commands
have an automatic checkpoint.
28. What are the steps for Switching to a different Sybase database?
select * from <new database>..<table name>
use <new database>
29. What are the similarity between Oracle and sybase?
http://www.rocket99.com/sybase/syb_vs_ora.html
30. What are the mandatory options required for BCP command utility?
bcp <database name> in|out -S server_name -U user_name -P password <os file name
> -t <row separator> -r <field separator>
31. how to check the long running transaction ?
In addition to syslogshold one can look at master.sysprocess and the physical_io
. If this is large (several hundred thousand) you are probably looking at a quer
y doing a table scan. syslogshold tends to only store theh*longest* running tran
saction.
32. What is the default table size in Sybase?
1 extent whixh is 8 pages.
33. how to clear the logsegment when the Secondary truncation point is on ?
When the database log is full, Adaptive Server cannot continue to process update
s. To solve this problem you must truncate the log. However, you should not trun
cate transactions from the log before the RepAgent has passed them successfully
to the Replication Server.
Adaptive Server uses truncation points to ensure that only transactions processe
d by the RepAgent are truncated. A secondary truncation point marks the place in
the primary database log up to which the RepAgent has processed transactions. T
he RepAgent periodically updates the secondary truncation point to reflect trans
actions successfully passed to the Replication Server. Adaptive Server will not
truncate the log past the secondary truncation point.
To truncate the database log at the secondary truncation point:
Verify that the secondary truncation point is set for the database.
Execute dbcc gettrunc.A 1 in the ltm_trunc_state column indicates the secondary tr
uncation point is turned on.
Turn off the secondary truncation point in the database.
dbcc settrunc(ltm, ignore)
Dump the database log.
Finally, you should dump the transaction log.
This may result in the loss of updates to the replicate database.
Set the secondary truncation point.
Before you restart a RepAgent, you need to reestablish the secondary truncation
point using dbcc settrunc(ltm,valid)
After resetting the locater for the database in the rs_locater table, resume the
Replication Server to restart the RepAgent.
The RepAgent begins scanning the log from the page returned in the ltm_truncpage
column by the dbcc gettrunc command.
34. Why can a user create 249 non clustered indexes over a given table as agains
t only one clustered index over a table?
There can only be one way in which a table can be ordered as per the clustered i
ndex.
Since there are 249 other columns and assuming a non-clustered index for each co
lumn,249 indexes can be created.
35. what is a deferred update in sybase?
A deferred update is a two-step procedure
in which the row is deleted from the original partition and then inserted in the
new partition.
36. What is the use of sp_helprotect in Sybase?
sp_helprotect reports permissions on a stored procedure
37. What is the role of Replication Server in Sybase?
moves data from one place to another.
38. What is the method for deleting a table in Sybase?
drop table <table_name>
39. what is forcing an index concept in sybase
All the columns of the key used in the query..leads to performace improvement.

41. What are the data types supported by Sybase?


http://www.sfu.ca/sasdoc/sashtml/accdb/z0439559.htm

43. How to list the objects in Sybase?


sp_help
select * from sysobjects
44. What is the difference between 'dump tran database to physical name' 'dump t
ran database with truncate_only' and dump tran database with no_log'and In real
time when we go to truncate the log?
To truncate the log without making a backup copy:- dump tran[saction] database_n
ame with truncate_only
To truncate a log that is filled to capacity. Use only as a last resort:-dump tr
an[saction] database_name with no_log
Dumps the transaction log to a tape
:- dump tran database to physical name
45. What are the types of Sybase index?
clustered and non-clusted
48. What is defncopy and it's usage.
Copies source text to os file.

50 How many defaults can be placed on one column of a able.If this col had an ex
isting default, what will happen if one more is added?
If a default already exists on a column, you must remove it before binding a new
default.
51. Difference between natural join and equi join?
Equijoins compare the values
in the columns being joined for equality and then include all the columns in the
tables being joined in the results.
select *
from authors, publishers
where authors.city = publishers.city
In the results of this statement, the city column appears twice. By definition,
the
results of an equijoin contain two identical columns. Because there is usually
no point in repeating the same information, one of these columns can be
eliminated by restating the query. The result is called a natural join.
The query that results in the natural join of publishers and authors on the city
column is:
select publishers.pub_id, publishers.pub_name,
publishers.state, authors.*
from publishers, authors
where publishers.city = authors.city
=====================================
52. Which one is faster count(*) or count(1) ?
49. What is the major differences between oracle & sybase
http://www.rocket99.com/sybase/syb_vs_ora.html
describe architecture of sybase ?
A Sybase server consists of:
A) two processes, data server and backup server ;
B) devices which house the databases; one database (master) contains system and
configuration data ;
C) a configuration file which contains the server attributes.
Memory Model
The Sybase memory model consists of:
A) the program area, which is where the dataserver executable is stored;
B) the data cache, stores recently fetched pages from the database device
C) the stored procedure cache, which contains optimized sql calls
The Sybase dataserver runs as a single process within the operating system; when
multiple users are connected to the database, only one process is managed by th
e OS. Each Sybase database connection requires 40-60k of memory.
The "total memory" configuration parameter determines the amount of memory alloc
ated to the server. This memory is taken immediately upon startup, and does not
increase.
What's a natural key in Sybase
natural key is a key for a given table that uniquely identifies the row. For exa
mple, assume that social security numbers are unique (I believe it is strived to
be unique but it's not always the case), then if you had the following employee
table:
employee:
ssn char(09)
f_name char(20)
l_name char(20)
title char(03)
Then a natural key would be ssn. If the combination of f_name and l_name were un
ique at this company, then another natural key would be f_name, l_name. As a mat
ter of fact, you can have many natural keys in a given table but in practice wha
t one does is build a surrogate (or artificial) key. he surrogate key is guarant
eed to be unique because (wait, get back, here it goes again) it's typically a m
onotonically increasing value.
The reason one uses a surrogate key is because your joins will be faster.
http://www.sybaseteam.com/forumdisplay.php?fid=21&page=2

---------------------------------------------------------
The update statistics command helps Adaptive Server make the best
decisions about which indexes to use when it processes a query, by
keeping it up to date about the distribution of the key values in the indexes.
Use update statistics when a large amount of data in an indexed column has
been added,changed,or deleted.The statistics are stored in systabstats and sysst
atistics.
As a database changes, you can optimize original query plans used to access its
tables by recompiling them with sp_recompile. This saves you from having to
find, drop, and re-create every stored procedure and trigger. This example
marks every stored procedure and trigger that accesses the table titles to be
recompiled the next time it is executed.
sp_recompile titles
What is the difference in storage type of numeric and decimal data types in syba
se ?
numeric is used for IDENTITY type columns.
What is procedure cache and data cache in Sybase?
Procedure cache is the memory area where compiled query tree run e.g, procedure,
batch query. Data Cache is the memory area where data that is required for the
current querys running is bought from Disk on to memory for building result set
syb_quit()
Terminates the connection in which the function is executed and returns an error
message.
select syb_quit()
-------------
CT-LIBRARY error:
ct_results(): network packet layer:
internal net library error: Net-Library operation terminated due to disconnect
s.
What is RAID?[RAID, an acronym for redundant array of independent disks or redun
dant array of inexpensive disks]
RAID is a storage system that uses multiple disks to store and distribute data.M
ultiple disks appear as a single logical disk to the server.
The levels are RAID 0,RAID 1,RAID 0+1,RAID 4/RAID 5,RAID 7..tempdb should be at
RAID 0+1.
Well, the log disk is frequently written, so it should not be on RAID 4 or 5. If
your data is infrequently written, you could use RAID 4 or 5 for it, because yo
u don't mind that writes are slow. If your data is frequently written, you shoul
d use RAID 0+1 for it.
A foreign key is a field (or fields) that points to the primary key of another t
able. The purpose of the foreign key is to ensure referential integrity of the d
ata. In other words, only values that are supposed to appear in the database are
permitted.
For example, say we have two tables, a CUSTOMER table that includes all customer
data, and an ORDERS table that includes all customer orders. The constraint her
e is that all orders must be associated with a customer that is already in the C
USTOMER table. In this case, we will place a foreign key on the ORDERS table and
have it relate to the primary key of the CUSTOMER table. This way, we can ensur
e that all orders in the ORDERS table are related to a customer in the CUSTOMER
table. In other words, the ORDERS table cannot contain information on a customer
that is not in the CUSTOMER table.
The structure of these two tables will be as follows:
Table CUSTOMER
column name characteristic
SID Primary Key
Last_Name
First_Name
Table ORDERS
column name characteristic
Order_ID Primary Key
Order_Date
Customer_SID Foreign Key
Amount
In the above example, the Customer_SID column in the ORDERS table is a foreign k
ey pointing to the SID column in the CUSTOMER table.
Below we show examples of how to specify the foreign key when creating the ORDER
S table:
MySQL:
CREATE TABLE ORDERS
(Order_ID integer,
Order_Date date,
Customer_SID integer,
Amount double,
Primary Key (Order_ID),
Foreign Key (Customer_SID) references CUSTOMER(SID));
Oracle:
CREATE TABLE ORDERS
(Order_ID integer primary key,
Order_Date date,
Customer_SID integer references CUSTOMER(SID),
Amount double);
SQL Server:
CREATE TABLE ORDERS
(Order_ID integer primary key,
Order_Date datetime,
Customer_SID integer references CUSTOMER(SID),
Amount double);
Below are examples for specifying a foreign key by altering a table. This assume
s that the ORDERS table has been created, and the foreign key has not yet been p
ut in:
MySQL:
ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);
Oracle:
ALTER TABLE ORDERS
ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);

How do you troubleshoot if your tempdb gets filled


When the transaction log is filled, use dump tran with no_log or dump tran with
truncate_only.
If this does not work, u need to do the following:-
Use the following query to find the spid of the oldest open transaction in a tra
nsaction log that has reached its last-chance threshold:
use master
go
select dbid, spid from syslogshold
where dbid = db_id("name_of_database")
For example, to find the oldest running transaction on the pubs2 database:
select dbid, spid from syslogshold
where dbid = db_id ("pubs2")
dbid spid
------ ------
7 1
Then execute lct_admin.
The syntax for lct_admin abort is:
lct_admin("abort", {process_id [, database_id]})
Before you can abort a transaction, you must first determine its ID. See Getting
the process ID for the oldest open transaction, below for information about deter
mining the transaction s process ID.
To terminate the oldest transaction, enter the process ID (spid) of the process
that initiated the transaction. This also terminates any other suspended transac
tions in the log that belong to the specified process.
For example, if process 83 holds the oldest open transaction in a suspended log,
and you want to terminate the transaction, enter:
select lct_admin("abort", 83)
This also terminates any other open transactions belonging to process 83 in the
same transaction log.
To terminate all open transactions in the log, enter:
select lct_admin("abort", 0, 12)
a good concept of
multiple temp dbs can be implemented and we can create temp
dbs and assign newly created temp db to sa, so that sa
could get the info of the processes that is blocking temp
db, ab=nd by using lct_admin or some other commands we can
abort that blocking transaction.
What is charindex function?
charindex(expr1,expr2) --> Searches expr2 for expr1 and returns the starting pos
ition.
For example,the expression charindex(".",convert(varchar,qty)) searches for a do
t in the qty column.
What is stuff function?
stuff(char_expr1, start, length, char_expr2)
Delete length characters from char_expr1 at start, and then insert char_expr2 in
to char_expr1 at start. To delete characters without inserting other characters,
char_expr2 should be NULL, not " ", which indicates a single space.
In order to replace qty = 11.36 with 11,36 use a combination of stuff and charin
dex as below:-
charindex(".",convert(varchar,qty)) - returns position of decimal point
Replace with stuff function as given below:
stuff(convert(varchar,qty),charindex(".",convert(varchar,qty)),1,",")
Query to find nth highest salary.
---------------------------------
SELECT *
FROM Employee E1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(E2.Salary))
FROM Employee E2
WHERE E2.Salary > E1.Salary)
In the above example, the inner query uses a value of the outer query in its fil
ter condition meaning; the inner query cannot be evaluated before evaluating the
outer query. So each row in the outer query is evaluated first and the inner qu
ery is run for that row.
What is 'forcing an index'?
Causing the optimizer to use an index forcefully.

Update trade_p2k
set trade_ref = 'new'
from transaction_wil (index index_a_new)
where record_no_wil = 11.
Performance and Tuning ..some of the concepts:-
set showplan on - Use the "set showplan on" command to see the plan chosen as "m
ost efficient" by optimizer.
set statistics io on - Use the "set statistics io on" command to see the number
of logical and physical i/o's for a query. Scrutinize those queries with high lo
gical i/o's.
Use the "set statistics time on" command to see the amount of time (elapsed, exe
cution, parse and compile) a query takes to run.
If the optimizer refuses to select the proper index for a table, you can force i
t by adding the index id in parentheses after the table name in the FROM clause.
If the optimizer turns out to be a "pessimizer", use the "set forceplan on" comm
and to change join order to be the order of the tables in the FROM clause.
How do I find the oldest open transaction in Sybase?
select h.spid, u.name, p.cmd, h.name, h.starttime,
p.hostname, p.hostprocess, p.program_name
from master..syslogshold h,
master..sysprocesses p,
master..sysusers u
where h.spid = p.spid
and p.suid = u.suid
and h.spid != 0 /* not replication truncation point */
When are stored procedures compiled in Sybase ?
A stored procedures is compiled:
1. with the first EXECute, when the parse tree is read into cache
2. with every EXECute, if CREATE PROCEDURE included WITH RECOMPILE
3. with each EXECute specifying WITH RECOMPILE
4. if the plans in cache for the procedure are all in use by other processes
5. after EXECute sp_recompile on a referenced table, which increments sysobjects
.schema and thus forces re-compilation

How do I remove duplicate rows from a table in Sybase?


There are a number of different ways to achieve this, depending on what you are
trying to achieve.
Usually, you are trying to remove duplication of a certain key due to changes in
business rules or recognition of a business rule that was not applied when the
database was originally built.
Probably the quickest method is to build a copy of the original table:
select *
into temp_table
from base_table
where 1=2

Create a unique index on the columns that covers the duplicating rows with the i
gnore_dup_key attribute. This may be more columns that the key for the table.
create unique index temp_idx
on temp_table(col1, col2, ..., colN)
with ignore_dup_key
Now, insert base_table into temp_table.
insert temp_table
select * from base_table

You probably want to ensure you have a very good backup of the base_table at thi
s point, coz your going to clear it out!
You will also want to check to ensure that the temp_table includes the rows you
need.
You also need to ensure that there are no triggers on the base table (remember
to keep a copy!) or RI constraints.
You probably do not want any of these to fire, or if they do, you are aware of
the implications.
Now you have a couple of choices. You can simply drop the original table and ren
ame the temp table to the same name as the base table. Alternatively, truncate t
he table and insert from the temp_table into the original table. You would need
to do this last if you did need the RI to fire on the table etc. I suspect that
in most cases dropping and renaming will be the best option.
If you want to simply see the duplicates in a table, the following query will he
lp:
select key1, key2, ...
from base_table
group by key1, key2, key3, key4, ...
having count(*) > 1
How do you identify the triggers associated with a table in a sybase database?
sp_depends <table_name>
How can I execute dynamic SQL with ASE in Sybase?
declare @sqlstring varchar(255)
select @sqlstring = "select count(*) from master..sysobjects"
exec (@sqlstring)
go
How can I tell when my server started?
select crdate from master..sysdatabases where name = 'tempdb'
What will happen if we create more indexes on a sybase table?
As far as i know the retrieval is fast.
as per the standard definitions the insertion will be slow.
To achieve more performance when you are loading large data
please drop indexes on the table and load the data.Once your
load has completed recreate indexes.
It will help your performance.

What is the maximum nesting level of Stored Procedure and Triggers in Sybase?
Triggers can nest to a depth of 16 levels. The current
nesting level is stored in the @@nestlevel global variable.
Nesting is enabled at installation. A System Administrator
can turn trigger nesting on and off with the allow nested
triggers configuration parameter.
the same is applied for Sp with nesting level with a range
or depth from 0 to 16.
if more than 16 then we get an error as :Maximum stored
procedure nesting level exceeded (limit 16).
What is a temp table? how to denote temp table?
Any table with name starting with '#' is automatically put
into tempdb database.
Temp tables allow developers to create and scan tables
within a stored procedure - and
have the tables totally isolated from all other database
connections. This is very
valuable when results need to be processed several times
within a loop, or when
a complex result set is expected (like a crosstab). Note
that temp table transactions
are logged within tempdb (exception: select into create
statements).

# 1
When you install Adaptive Server, it contains these system
databases:
The master database controls the user databases and the
operation of Adaptive Server as a whole. It stores
information about all user databases and their associated
database devices.
The model database is used by Adaptive Server as a template
for creating new user databases.
A new database cannot be smaller than the model
database.
? The sybsystemprocs database contains the system stored
procedures.
The sybsystemdb database contains information about
distributed transactions.
? The temporary database, tempdb, stores temporary objects,
including temporary tables created with the name
prefix ?tempdb..?.
? The sybsecurity database, contains the audit system for
Adaptive Server. It consists of:
The system tables, sysaudits_01, sysaudits_02, ...
sysaudits_08, which contain the audit trail

what is the architechure of sybase ASE?


The Sybase Server
A Sybase server consists of:
a) Two processes, data server and backup server.
b) Devices which house the databases; one database
(master) contains system and configuration data.
c) A configuration file which contains the server
attributes.
Memory Model
The Sybase memory model consists of:
a) The program area, which is where the dataserver
executable is stored.
b) The data cache, stores recently fetched pages
from the database device.
c) The stored procedure cache, which contains
optimized sql calls.
A database device stores the objects that make up
databases.
The term device does not necessarily refer to a
distinct physical device: it can refer to any piece of a
disk (such as a disk partition) or a file in the file
system that is used to store databases and their objects.
Each database device or file must be prepared and made
known to Adaptive Server before it can be used for database
storage. This process is called initialization.
A segment is a label that points to one or more database
devices. When you first create a database, Adaptive Server
creates three segments in the database,
System: Stores the database?s system tables.
Logsegment: Stores the database?s transaction log.
Default: Stores all other database objects?unless you
create additional segments and store tables or indexes on
the new segments by using create table...on segment_name or
create index...on segment_name
what are the properties of relational tables?
Values are atomic

/prod/gbo/bin/process_mail.pl calls Deshaw::GBO::Mail::MailProcessor::process_ma


il
From process_mail, call to Deshaw::GBO::Mail::MIMEMessage::get_action_cmdline_fo
r_mail takes place
From within this,we set the options for the mime-message,like getFromField,getSu
bject(),getMailRecipientList(),do database connection and then get the archival
path and then we use save_mime_msg_to
-----------
perl -w --> causes the interpreter to spit out warnings when the variables used
are not declared.
Why do you want to use strict?
To help you catch typos so you can quickly get on to finding more significant pr
oblems (and so we don't have to catch the typos for you either), among other rea
sons.
Its difficult to spot '$recieve_date' when on the previous page you've been call
ing it '$receive_date'. Also, to give your variables as small a scope as possibl
e so that you don't have to worry about what they're doing to other parts of you
r program (although that's the function of my, it forces you to use my which whe
n properly used helps achieve this goal).
-----------
save transaction <transaction_name>:Used as a savepoint.If I specify a rollback
statement, the transaction will be rolled back upto the savepoint only.
@@transtate global variable contains the current status of a transaction.
@@trancount contains the current nesting level of a transaction.Until it becomes
0, transaction would not be committed.
Two transaction modes in ASE:chained and unchained..
Chained :Every data selection and modification command initiates an implicit
BEGIN transaction.
Unchained:Transaction should be explicitly begun.This is the default mode for sy
base ASE.
@@tranchained global variable contains the current transaction mode. it returns
1 or 0 to specify whether the transaction is at chained or unchained mode.
Default transaction isolation level is set at 1.
The global variable @@isolation contains the current isolation level of your Tra
nsact-SQL session.
To enforce transaction isolation level 2 from a query, use:
select title_id, price, advance
from titles
at isolation 2

---------------------------------
CLUSTERED INDEX --> http://msdn.microsoft.com/en-us/library/aa933131%28v=SQL.80%
29.aspx
================
A clustered index determines the physical order of data in a table. A clustered
index is analogous to a telephone directory, which arranges data by last name. B
ecause the clustered index dictates the physical storage order of the data in th
e table, a table can contain only one clustered index. However, the index can co
mprise multiple columns (a composite index), like the way a telephone directory
is organized by last name and first name.
A clustered index is particularly efficient on columns that are often searched f
or ranges of values. After the row with the first value is found using the clust
ered index, rows with subsequent indexed values are guaranteed to be physically
adjacent. For example, if an application frequently executes a query to retrieve
records between a range of dates, a clustered index can quickly locate the row
containing the beginning date, and then retrieve all adjacent rows in the table
until the last date is reached. This can help increase the performance of this t
ype of query. Also, if there is a column(s) that is used frequently to sort the
data retrieved from a table, it can be advantageous to cluster (physically sort)
the table on that column(s) to save the cost of a sort each time the column(s)
is queried.
Clustered indexes are also efficient for finding a specific row when the indexed
value is unique. For example, the fastest way to find a particular employee usi
ng the unique employee ID column emp_id is to create a clustered index or PRIMAR
Y KEY constraint on the emp_id column.
Before creating clustered indexes, understand how your data will be accessed. Co
nsider using a clustered index for:
* Columns that contain a large number of distinct values.
* Queries that return a range of values using operators such as BETWEEN, >,
>=, <, and <=.
* Columns that are accessed sequentially.
* Queries that return large result sets.
* Columns that are frequently accessed by queries involving join or GROUP BY
clauses; typically these are foreign key columns.
An index on the column(s) specified in the ORDER BY or GROUP BY clause eliminat
es the need for SQL Server to sort the data because the rows are already sorted.
This improves query performance.
* OLTP-type applications where very fast single row lookup is required, typi
cally by means of the primary key. Create a clustered index on the primary key.

Clustered indexes are not a good choice for:


* Columns that undergo frequent changes
This results in the entire row moving (because SQL Server must keep the da
ta values of a row in physical order). This is an important consideration in hig
h-volume transaction processing systems where data tends to be volatile.

NON CLUSTERED INDEX


-===================
Before you create nonclustered indexes, understand how your data will be accesse
d. Consider using nonclustered indexes for:
* Columns that contain a large number of distinct values, such as a combinat
ion of last name and first name (if a clustered index is used for other columns)
. If there are very few distinct values, such as only 1 and 0, most queries will
not use the index because a table scan is usually more efficient.
* Queries that do not return large result sets.
* Columns frequently involved in search conditions of a query (WHERE clause)
that return exact matches.
* Decision-support-system applications for which joins and grouping are freq
uently required. Create multiple nonclustered indexes on columns involved in joi
n and grouping operations, and a clustered index on any foreign key columns.
* Covering all columns from one table in a given query. This eliminates acce
ssing the table or clustered index altogether.

S-ar putea să vă placă și