Search This Blog

LINQ programming model

LINQ is a programming model that introduces queries as a first-class concept into any Microsoft .NET language. However, complete support for LINQ requires some extensions in the language used. These extensions boost productivity, thereby providing a shorter, meaningful,and expressive syntax to manipulate data.

Following is a simple LINQ query for a typical software solution that returns the names of customers in Italy:
var query =
from c in Customers
where c.Country == "Italy"
select c.CompanyName;


Do not worry about syntax and keywords (such as var) for now. The result of this query is a
list of strings. You can enumerate these values with a foreach loop in C#:

foreach ( string name in query ) {
Console.WriteLine( name );
}

Both the query definition and the foreach loop just shown are regular C# 3.0 statements. At
this point, you might wonder what we are querying. What is Customers? Is this query a new
form of embedded SQL? Not at all. The same query (and the following foreach code) can be
applied to an SQL database, to a DataSet, to an array of objects in memory, or to many other
kinds of data. Customers could be a collection of objects:

Customer[] Customers;
Customers could be a DataTable in a DataSet:
DataSet ds = GetDataSet();
DataTable Customers = ds.Tables["Customers"];

Customers could be an entity class that describes a physical table in a relational database:
DataContext db = new DataContext( ConnectionString );
Table Customers = db.GetTable();
Finally, Customers could be an entity class that describes a conceptual model and is mapped to
a relational database:
NorthwindModel dataModel = new NorthwindModel();
ObjectQuery Customers = dataModel.Customers;

As you will see, the SQL-like syntax used in LINQ is called a query expression. Languages thatimplement embedded SQL define only a simplified syntax to put SQL statements into a different language, but these statements are not integrated into the language’s native syntax and
type system. For example, you cannot call a function written using the host language in the middle of an SQL statement, although this is possible in LINQ. Moreover, LINQ is not limited to querying databases, as embedded SQL

Oracle9i AS: Basic Administrations

Exam : 1Z0-301
Title : Oracle9i AS: Basic Administrations
Sample 3- Questions With Answer

# QUESTION 1
The machine hosting your Oracle9iAS Infrastructure has been stopped and the
operating system has been restarted.
Which three steps do you need to take to get Oracle Internet Directory working?
(Choose three)
A. Start Enterprise Manager daemon.
B. Start the Oracle9iAS metadata repository and the database listener.
C. Start Oracle Management Server in order to get connected to OEM Web site.
D. Navigate to the infrastructure homepage, select Oracle Internet Directory, and then
click Start.
E. Navigate to the Farm page, select the Oracle9iAS Infrastructure instance, and click
Start All to start Oracle9iAS metadata repository and the database listener and all OID
components.
F. Navigate to the Oracle Internet Directory home page and start the Distributed
Administration Service.
Answer: E

# QUESTION 2
Exhibit:
Examine the configuration context in which Oracle HTTP Server configuration
directives can be used.
Not all directives can be used everywhere. The Oracle HTTP Server distinguishes
between the configuration context and a per-directive basis. (Every directive has a fixed
set of contexts in which it is allowed.)
Which three statements are true? (Choose three)
A. The or container is allowed inside a directory container.
B. If you want to match URLs you need to use or
directives.
C. Box 1 represents the directory container built by or
directives.
D. The or container is allowed inside a or
container.
E. Box 1 represents a or container with directives that are
applied to a particular URL and its subareas.
Answer: A, B, C

# QUESTION 3
Exhibit:
You have a single installation of J2EE and Web Cache on a single host.
Which two Web server types does this topology support? (Choose two)
A. A Web server that has enabled single sign-on functionality.
B. A Web server that has a central user management repository.
C. A Web server that is preconfigured for caching of Web pages.
D. A Web server that is enabled to connect to an Oracle Directory Server.
E. A Web server that supports the deployment of J2EE-compliant applications.
F. A Web server that supports the deployment of Oracle Forms-based applications.
Answer: C, E

# QUESTION 4
Which two are appropriate directives for the default-web-site.xml file? (Choose two)
A.
B.
C.
D.
E.
F.
Answer: D, F

# QUESTION 5
Which three metrics can you get from the OC4J Instance page on OEM? (Choose three)
A. CPU usage
B. JDBC Connections
C. Application up time
D. 9iAS Instance up time
E. OC4J Instance up time
Answer: A, B, E

# QUESTION 6
Exhibit:
You are managing an Oracle9iAS Cluster as illustrated un the image.
During a period of high volume activity, an OC4J process on one of the nodes goes
down.
How is this detected, and which two activities takes place at that time? (Choose two)
A. The OC4J process death will be detected by the DCM process, and that process will
automatically start a replacement OC4J process.
B. The OC4J process death will be detected by an OHS process, which updates the
routing tables.
New OC4J requests will be routed to surviving OC4J processes.
C. The OC4J process death will be detected by the OPMN process, which updates the
routing tables.
New OC4J requests will be routed to surviving OC4J processes.
D. The OC4J process death will be detected by the DCM process, which updates the
routing tables.
New OC4J requests will be routed to surviving OC4J processes.
E. The OC4J process death will be detected by the OPMN process, and that process will
automatically start a replacement OC4J process.
Answer: C, E

# QUESTION 7
Exhibit:
dcmctl deployApplication -file name -a app_name
[-co comp_name] [-rc root_context]
Examine the syntax of the dcmctl deployApplication command.
You want to deploy the Web application module packages in simple-web-war to your
OC4J instance j2ee1. The Web archive is stored on the application server under the
directory /home/user/to_deploy. The application should be named simple-web and the
application should be accessible as mysimpleweb.
Which is the correct approach using dcmctl to deploy your application?
A. Wrap the Web application into J2EE application (.ear file) before deployment because
dcmctl supports only ear files.
Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deploy/Application \
-f /home/users/to_deploy/simple-web.ear \
-a simple-web -co oc4j -rc mysumpleweb
B. Wrap the Web application into a J2EE application (.ear file) before deployment
because dcmctl supports only ear files.
Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deployApplication \
-f /home/users/to_deploy/simple-web-ear \
-a mysimpleweb -co j2ee1 -rc simple-web
C. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deployApplication \
D. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deployApplication \
-f /home/users/to_deploy/simple-web.war \
-a simple-web -co j2ee1 -rc mysimpleweb
E. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deploy/Application \
-f /home/users/to_deploy/simple-web.war \
-a mysimpleweb -co j2ee1 -rc simple-web
Answer: D

# QUESTION 8
Exhibit:
dcmctl deployApplication -file name -a app_name
[-co comp_name] [-rc root_context]
Examine the syntax of the dcmctl deployApplication command.
You want to deploy a J2EE application to your default OC4J instance that consists of a
Web module named simple-app and that is packaged in the file simple.ear.
The J2EE application should be deployed to your Oracle9iAS Instance named
j2ee.1prod1.us. CertKing .com.
The J2EE archive is stored on the application server under the directory
/home/users/to_deploy. The application should be administered under the name simpletest.
Which is the correct approach using dcmctl to deploy your application?
A. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deployApplication \
-f /home/users/to_deploy/simple.ear \
-a simple-test-co j2ee1.prod1.us. CertKing .com \
-rc simple-test
B. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deploy/Application \
-f /home/users/to_deploy/simple.ear \
-a simple-test -i j2ee1.prod.us. CertKing .com \
-rf simple-app
C. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deployApplication \
-f /home/users/to_deploy/simple.ear \
-a simple-test -i j2ee1.prod1.use. CertKing .com
D. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deployApplication \
-f /home/users/to_deploy/simple-app.war \
-a simple-test -i j2ee1.prod1.us. CertKing .com
E. Enter the following commands on your application server:
$> cd $ORACLE_HOME/dcm/bin
$> dcmctl deployApplication \
-f /home/users/to_deploy/simple-app.war \
-a simple-app -i j2ee1.prod1.us. CertKing .com
Answer: C

# QUESTION 9
A user authenticated to a partner application by Oracle9iAS Single Sign-On accesses
another partner application in the same session.
What does the second application do?
A. Checks the htaccess file to authenticate the user.
B. Uses the mod_osso cookie to authenticate the user.
C. Rewrites the URL and stores it in the SSO database.
D. Checks for the correct URL from the Single Sign-On server.
Answer: D

# QUESTION 10
Most J2EE applications use a database to have a persistent storage for data. Servlets, as
well as JSPs and EJBs, need to communicate with the database.
Which two statements are true? (Choose two)
A. To be portable across application servers J2EE applications use DataSource objects.
B. The JDBC DriverManager class has logical names that make applications that use it
portable.
C. JDBC DriverManager class objects enable portable J2EE applications across
application servers.
D. Every JDBC 2.0 driver has its own implementation of DataSource objects that can be
bound into an external JNDI namespace.
E. Every JDBC 2.0 driver has its own implementation of DriverManager class objects
that can be bound into an external JNDI namespace.
F. Using the JDBC DriverManager class is the recommended way for a J2EE application
to get a connection.
Answer: A, D

# QUESTION 11
Which Oracle9iAS capabilities require an Infrastructure? (Choose all that apply)
A. Single Sign-On
B. Application Server Clusters
C. All Oracle9iAS installation types
D. Oracle9iAS Web Cache Clusters
E. Invoking PL/SQL code via Database Access Descriptors
Answer: A, B, D

# QUESTION 12
Most J2EE applications, servlets as well as JSPs and EJBs, need to communicate with
the database.
Which two are true regarding data sources? (Choose two)
A. J2EE applications use JNDI to look up DataSource objects.
B. J2EE applications retrieve connections to the database through DataSource objects.
C. DataSource objects include the mapping between the logical database connection and
the physical database information.
D. J2EE applications retrieve database connections from the application code itself, that
includes the physical database information.
Answer: B, C

# QUESTION 13
When stopping the Infrastructure instance, which option is correct?
A. Stopping the Infrastructure will stop all of the Oracle9iAS Application Server
instances that use it.
B. You should stop the Infrastructure first, and then stop all of the Oracle9iAS
Application Server instances that use it.
C. You should first stop all of the Oracle9iAS Application Server Instances that use the
Infrastructure, then stop the Infrastructure.
D. Stopping the Infrastructure does not affect the Oracle9iAS Application Server
instances that use it.
Answer: C

# QUESTION 14
Which process of an Oracle9iAS Instance is responsible for managing and tracking the
process in the Instance, as well as propagating events among other Instances in the
Farm?
A. DCM
B. OPMN
C. OC4J
D. The OHS Parent process
E. An OHS Child process
Answer: B

# QUESTION 15
Which six correctly match the item to its description? (Choose six)
A. Dispatcher: Listens for LDAP requests.
B. LDAP server process: Processes LDAP requests.
C. Dispatcher: Sends changes to other OID nodes.
D. Oracle Director Manager: Displays configuration sets.
E. OID Replication process: Sends changes to other OID nodes.
F. LDAP server process: Initiates and terminates OID server processes.
G. OID Control Utility: Accepts commands to start and stop OID instances.
Answer: F

# QUESTION 16
Which two OC4J configuration files are server configuration files? (Choose two)
A. rmi.xml
B. web.xml
C. jms.xml
D. ejb.xml
E. orion-web.xml
Answer: A, C

# QUESTION 17
Which statement is true about the Oracle9iAS Single Sign-On session duration?
A. It is applicable to partner applications only.
B. It is applicable to external applications only.
C. It is applicable to all single sign-on sessions.
D. It is applicable to administrative sessions only.
Answer: C

# QUESTION 18
Exhibit:
You installed one J2EE and Web Cache instance, which is running. Because your
company wants to use the Oracle Internet Directory as a central repository for user
information for an application that should be single sign-on enabled you installed
Oracle9iAS Infrastructure.
Which actions are required in order to use Oracle Internet Directory? (Choose all that
apply)
A. Ensure that the Oracle9iAS Infrastructure instance is up and running.
B. Using Oracle Enterprise Manager Website select the J2EE and Web Cache instance
and associate the J2EE and Web Cache Instance with Oracle9iAS Infrastructure.
C. Using the Oracle Enterprise Manager Web site, select the Oracle9iAS metadata
repository and associate the metadata repository with the J2EE and Web Cache
instance.
D. Stop both instances, J2EE and Web Cache and Oracle9iAS Infrastructure.
Then start the J2EE and Web Cache instance before you start the Oracle9iAS
Infrastructure instance.
E. Restart the J2EE and Web Cache instance to have the instance recognized by
Oracle9iAS Infrastructure.
F. The only required step is to restart both instances, J2EE and Web Cache and
Oracle9iAS Infrastructure.
Answer: A, B

# QUESTION 19
During the installation process, you can choose to install Oracle9iAS Infrastructure.
Which two statements describe the relationship between Oracle9iAS Infrastructure and
Oracle9i Application Server? (Choose two)
A. Oracle9iAS Infrastructure is a prerequisite for all Oracle9i Application Server
Installation types.
B. All Oracle9iAS Instances except the Installation type Portal and Wireless use
Oracle9iAS Infrastructure.
C. Oracle9i Application Server Installation type J2EE and Web Cache does NOT need an
Oracle9iAS Infrastructure as a prerequisite.
D. Oracle9iAS Infrastructure contains Oracle Internet Directory and Oracle Internet
Filesystem to centralized user management.
E. Oracle9i Application Server instances like J2EE and Web Cache need to be single
Oracle9iAS Infrastructure.
F. Oracle9iAS Infrastructure contains a preconfigured database to store all metadata
information necessary for Oracle9iAS instances.
Answer: C, E

# QUESTION 20
Which two are files that Oracle9iAS Web Cache reads at startup? (Choose two)
A. httpd.conf
B. mod_oc4j.xml
C. internal.xml
D. webcache.xml
E. webcacheroot.orc
Answer: A, D

# QUESTION 21
Which two statements describe features of the servlet support in Oracle9iAS Containers
for J2EE (OC4J)? (Choose two)
A. Allows use of WAR files to deploy packaged applications.
B. Requires code changes for distributable web applications.
C. Retains translated servlet code for extended error reporting.
D. Provides simple and complex object relational mapping for entity beans.
E. Replicates state of Web Applications to other servers in the same cluster.
Answer: A, E

# QUESTION 22
Which mod_plsql directive enables you to provide access to a specific PL/SQL
procedure without specifying it in the URL?
A. PlsqlDefaultPage
B. PlsqlDatabaseName
C. PlsqlDatabaseUsername
D. PlsqlDatabasePassword
Answer: A

# QUESTION 23
What does the Delegated Administration Service or Oracle9iAS SSO enable
nonadministrative users to do?
A. Create new SSO servers.
B. Modify SSO user's personal data.
C. Create new Oracle Internet Directories.
D. Modify SSO administrator's schema location.
Answer: B

# QUESTION 24
Exhibit:
Examine the image showing the Oracle Directory Manager Menu and navigation bar.
Oracle Directory Manager has a double window interface. You want to obtain password
credentials about the user appuser created with the Distributed Administration Service
(DAS).
Where do you get the appropriate information?
A. Click the plus sign next to Server Management to expand the subtree, then navigate to
Directory Server, where you get information about the user.
B. Click the plus sign next to Access Control Management, then navigate to the entry
cn=DAS, where you get the information about the user.
C. Click the plus sign next to Entry Management to expand the subtree, then drill down to
the level of cn=Users to obtain the wanted information.
D. Click the plus sign next to Schema Management, then navigate to the entry cn=Users,
where you get the information about the user.
E. Click the plus sign next to Password Policy Management, then navigate to the entry
cn=DAS where you get the information about the user.
F. Click the plus sign next to Password Verifier Management, then navigate to the entry
cn=DAS where you get the information about the user.
Answer: E

# QUESTION 25
You want to use Basic Authentication to protect access to your web site using Oracle
HTTP Server password files. To accomplish this, you will use a or
block container in your httpd.conf configuration file.
Which three Require directives are correct? (Choose three)
A. Require valid-user
B. Require valid_user
C. Require user
D. Require group
Answer: A, C, D

# QUESTION 26
Which component of an Oracle9iAS instance is responsible for accessing the
configuration information for the Farm, reading changes that need to be propagated
throughout the Farm, and updating the configuration information?
A. DCM
B. OPMN
C. OC4J
D. The OHS parent process
E. An OHS child process
Answer: B

# QUESTION 27
Which two protocols are available by default for the Oracle9iAS Containers for J2EE
(OC4J) to receive communication when it is installed as a part of an Oracle9iAS
Instance? (Choose two)
A. HTTP
B. ORMI
C. HTTPS
D. AJP12
E. AJP13
Answer: B, E

# QUESTION 28
In which two directories would you typically find the mod_plsql configuration files?
(Choose two)
A. $ORACLE_HOME/network/admin
B. $ORACLE_HOME/Apache/Apache/conf
C. $ORACLE_HOME/Apache/dads/conf
D. $ORACLE_HOME/Apache/modplsql/conf
E. $ORACLE_HOME/Apache/Apache/htdocs
Answer: B, D

# QUESTION 29
A collection of Oracle9iAS Instances that share the same Infrastructure but do not have
identical configurations is referred to as a _______.
A. Cluster
B. Farm
C. Instance
D. Component Cluster
Answer: B

# QUESTION 30
When you configure your application to run in Single Sign-On environment, you should
register _______.
A. mod_osso as a partner application.

Database :What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered.

Database : What is a trigger?

Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database.

Can you give an example of system defined Stored Procedure?

sp_helpdb , sp_who2, sp_renamedb are a set of system defined stored procedures. We can also have user defined stored procedures which can be called in similar way.

Database : What is a Stored Procedure?

Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements.

Database Performance Monitor (ST04)

Database Performance Monitor (ST04) provides a database-independent tool to analyze
and tune the following components:
< Memory and buffer usage
< Space usage
< CPU usage
< SQL requests
< Detailed SQL items

1. In the Command field, enter transaction ST04 and choose Enter (or from the SAP standard menu, choose Tools ® Administration ® Monitor ® Performance ® Database ®
ST04 - Activity).

2. An initial overview of database activity is provided which pertains to database,operating system, CPU, and memory.Microsoft SQL Server allows the analysis of specific attributes pertaining to memory, space, I/O, and quality of table reads and writes. This information can signal adjustments necessary to improve performance of the database.

a. Memory Usage Procedure cache and Data cache hit ratio can reflect memory problems.These values should be greater than95 percent for optimal memory usage.
b. Server Engine/Elapsed Shows how hard the CPU has beenworking on Microsoft SQL Serverprocesses. You are interested in theratio of busy : idle time.
c. SQL Requests Allows for snapshots of how SQL queries are utilizing table access pertaining to full table or index scans.A high ratio of full table scans vs. index scans can indicate performance bottlenecks.
d. Detail analysis menu

T-SQL Query : How to retrieve only the Nth row from a table?

Method 1

SELECT * FROM t1 a
WHERE  n = (SELECT COUNT(rowid)
             FROM t1 b
            WHERE a.rowid >= b.rowid);

Method 2


SELECT * FROM (
  SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101 )

SQL statement : How to Delete duplicates rows from a table?

Choose one of the following queries to identify or remove duplicate rows from a table leaving only unique records in the table:

Method 1:

Delete all rowids that is BIGGER than the SMALLEST rowid value (for a given key):

SQL> DELETE FROM table_name A WHERE ROWID > (
 2    SELECT min(rowid) FROM table_name B
 3    WHERE A.key_values = B.key_values);

Method 2:


This method is usually faster. However, remember to recreate all indexes, constraints, triggers, etc. on the table when done.

SQL> create table table_name2 as select distinct * from table_name1;
SQL> drop table table_name1;
SQL> rename table_name2 to table_name1;


Method 3:


SQL> delete from my_table t1
SQL> where  exists (select 'x' from my_table t2
SQL>                 where t2.key_value1 = t1.key_value1
SQL>                   and t2.key_value2 = t1.key_value2
SQL>                   and t2.rowid      > t1.rowid);

Oracle FAQ : How can one dump/ examine the exact content of a database column?

Table data can be extracted from the database as octal, decimal or hex values:

SELECT DUMP(col1, 10)
FROM tab1
WHERE cond1 = val1;
DUMP(COL1)
-------------------------------------
Typ=96 Len=4: 65,66,67,32

For this example, type=96 is indicating a CHAR column. The last byte in the column is 32, which is the ASCII code for a space. This tells us that this column is blank-padded.

Oracle FAQ : How to select a random collection of rows from a table?

The following methods can be used to select a random collection of rows from a table:

The SAMPLE Clause

From Oracle 8i, the easiest way to randomly select rows from a table is to use the SAMPLE clause with a SELECT statement. Examples:

SELECT * FROM emp SAMPLE(10);

In the above example, Oracle is instructed to randomly return 10% of the rows in the table.

SELECT * FROM emp SAMPLE(5) BLOCKS;

This example will sample 5% of all formatted database blocks instead of rows.

This clause only works for single table queries on local tables. If you include the SAMPLE clause within a multi-table or remote query, you will get a parse error or "ORA-30561: SAMPLE option not allowed in statement with multiple table references". One way around this is to create an inline view on the driving table of the query with the SAMPLE clause. Example:

SELECT t1.dept, t2.emp
FROM (SELECT * FROM dept SAMPLE(5)) t1,
emp t2
WHERE t1.dep_id = t2.dep_id;

If you examine the execution plan of a "Sample Table Scan", you should see a step like this:

TABLE ACCESS (SAMPLE) OF 'EMP' (TABLE)

ORDER BY dbms_random.value()

This method orders the data by a random column number. Example:

SQL> SELECT * FROM (SELECT ename
2 FROM emp
3 ORDER BY dbms_random.value())
4 WHERE rownum <= 3;
ENAME
----------
WARD
MILLER
TURNER

The ORA_HASH() function

The following example retrieves a subset of the data in the emp table by specifying 3 buckets (0 to 2) and then returning the data from bucket 1:

SELECT * FROM emp WHERE ORA_HASH(empno, 2) = 1;

Oracle FAQ : How does one escape special characters when writing SQL queries?

Escape quotes

Use two quotes for every one displayed. Examples:

SQL> SELECT 'Frank''s Oracle site' AS text FROM DUAL;
TEXT
--------------------
Franks's Oracle site

SQL> SELECT 'A ''quoted'' word.' AS text FROM DUAL;
TEXT
----------------
A 'quoted' word.

SQL> SELECT 'A ''''double quoted'''' word.' AS text FROM DUAL;
TEXT
-------------------------
A ''double quoted'' word.

Escape wildcard characters

The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL. Examples:

SELECT name FROM emp 
WHERE id LIKE '%/_%' ESCAPE '/';
SELECT name FROM emp 
WHERE id LIKE '%\%%' ESCAPE '\';

Escape ampersand (&) characters in SQL*Plus

When using SQL*Plus, the DEFINE setting can be changed to allow &'s (ampersands) to be used in text:

SET DEFINE ~
SELECT 'Lorel & Hardy' FROM dual;

Other methods:

Define an escape character:

SET ESCAPE '\'
SELECT '\&abc' FROM dual;

Don't scan for substitution variables:

SET SCAN OFF
SELECT '&ABC' x FROM dual;

Use the 10g Quoting mechanism:

Syntax
q'[QUOTE_CHAR]Text[QUOTE_CHAR]'
Make sure that the QUOTE_CHAR doesnt exist in the text.
SELECT q'{This is Orafaq's 'quoted' text field}' FROM DUAL;

What are the difference between DDL, DML and DCL commands?

DDL - Data Definition Language: statements used to define the database structure or schema. Some examples:

  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

DML - Data Manipulation Language: statements used for managing data within schema objects. Some examples:

  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

DCL - Data Control Language. Some examples:

  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

TCL - Transaction Control: statements used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

DML are not auto-commit. i.e. you can roll-back the operations, but DDL are auto-commit

SQL server 2008 : LAMBDA EXPRESSIONS

C# 2.0 provided a shorthand method of creating methods and instantiating delegates all in one construct, known as anonymous delegates. C# 3.0 expanded on this idea with a more compact syntactical construct for creating anonymous methods known as lambda expressions. On its most basic level, a lambda expression is simply an anonymous function or method. In Listing 13-8, I've used lambda expressions in two places as arguments to the Average method. The lambda expressions I used were as follows:
p => (float)p.Element("open")
p => (float)p.Element("close")

In both of the preceding lambda expressions, the anonymous function is both declared and instantiated in one expression. Query methods, like the Average method, can accept anonymous functions as parameters— a very powerful feature. Lambda expressions offer many advantages (apart from terseness of code) that .NET 2.0 anonymous delegates do not provide:

SQL server 2008 :LINQ TO XML NAMESPACES

LINQ to XML provides namespace support through the XNamespace object. To create a namespace, just assign the Uniform Resource Identifier (URI) to an XNamespace variable. To use the namespace, just concatenate it to the element name when querying. LINQ to XML automatically expands the namespace-qualified element name out to its fully qualified name internally, so you don't have to worry about it.

SQL server 2008 : SQLXML XPATH LIMITATIONS

SQLXML supports a subset of XPath queries. Following is a list of limitations imposed on the SQLXML XPath implementation:

• The only axis specifiers supported are child, parent, attribute, and self.
• Only element and attribute node types are supported.
• Only predicates that return a boolean result are supported. Numeric predicates like [1] are not supported.
• Only the three XPath data types are supported: string, number, and boolean.
• SQLXML 4 does not support the root query (specified by a forward slash /), or descendant-or-self queries (specified by double slashes //). Every query must begin at a top-level schema element type.
• SQLXML does not support queries that generate a Cartesian product.
• The mod and union (|) operators, string functions, and numeric functions are not supported.

SQL server 2008 : GML

GML is the OGC standard for representation of geospatial data in XML format. SQL Server provides support for a subset of GML, allowing you to create geometry and geography data type instances from GML (or convert them to GML) using built-in data type methods. Y

SQL server 2008 :DTD, XDR, AND XSD

DTDs provide the most basic standard level of validation available to XML. DTDs provide simple structure and string-based content validation; however, they do not provide data typing functionality. DTDs also use a legacy non-XML format inherited from Standard Generalized Markup Language (SGML). DTDs have the advantage of having been part of the XML recommendation since the beginning, so nearly all XML parsers support them to some degree.

XDR schemas represent Microsoft's first attempt at implementing an early working draft of the W3C XML Schema recommendation. XDR functionality is Microsoft-specific, and you won't find it implemented widely on other platforms. XDR functionality for constraining XML structure and typing content has been superseded by the official W3C XML Schema recommendation, and support for XDR is provided for
backward-compatibility reasons. You normally won't use XDR schemas for new functionality, though you might run into them while supporting legacy applications.

SQL server 2008 : HTTP ENDPOINTS AND AD HOC QUERYING

The BATCHES option is a powerful option, but it should be used with care. Any time you allow ad hoc querying of your database, you should carefully consider the security ramifications. I would advise against allowing ad hoc querying over HTTP SOAP endpoints unless you have a compelling reason. And even then you should perform a very thorough security review to ensure that no unauthorized access is allowed to your database and to make sure that users cannot execute destructive ad hoc T-SQL code on your server.

SQL server 2008 : SECURE YOUR SQL SERVER ENDPOINTS

There is some concern from database administrators about exposing SQL Server directly to web traffic via the HTTP SOAP endpoints. This concern is not unreasonable, since you could potentially open up your server to unwanted traffic and attacks from the Internet. However, HTTP SOAP endpoints provide security that is very tightly integrated with SQL Server's built-in security model. If your SQL Server is secure, your exposure to attacks via endpoints is minimized. If your server is not properly secured, endpoints only exacerbate the problem. Of course, an unsecure SQL Server is probably more likely to be attacked using tried-and-true attacks, like SQL injection or password brute-force/dictionary attacks over the standard SQL Server TCP and user datagram protocol ports than via SOAP endpoints.

On the other hand, the vast majority of SQL Servers that are set up to expose web service methods via HTTP SOAP endpoints tend to be set up for internal use only, behind firewalls and with the additional network security provided by network administrators on a local area network or wide area network. If you set up any SQL Server for exposure over the Internet (endpoints enabled or not), make sure you do a thorough security analysis of your server and network to minimize the potential that your server, network, and data can become compromised. Though they are outside the scope of this book, the same type of precautions should be taken when exposing any computer to the Internet, including web servers and other networked computers.

SQL server 2008 : XSL:CHOOSE

The xsl:choose element is analogous to the SQL searched CASE expression. This element contains one or more xsl:when elements that are analogous to WHEN clauses in SQL searched CASE expressions. A SQL searched CASE expression is one where each WHEN clause is a predicate. Like the SQL searched CASE expression, each xsl:when element takes a test attribute that contains an expression. If the expression for an xsl:when element evaluates to true, the content of that element is used. The xsl:choose element can also contain an xsl:otherwise element which is equivalent to the CASE expression's ELSE clause. If all the xsl:when elements evaluate to false, the content of the xsl:otherwise element is used. XSLT does not require that your expression be a true Boolean expression. Any expression in XSLT can evaluate to an effective Boolean value. Chapter 6 has a discussion of effective Boolean value in XQuery.

SQL server 2008 : DHTML, CSS, AND XHTML

In 1999, the W3C approved the HTML 4.01 specification for web-based publishing (this recommendation is commonly known as HTML4). In 2000, the W3C quickly followed up with the XHTML (Extensible HTML) standard, which redefines HTML as an XML application. During this same time, vendors were just starting to get serious about implementing the 1996 W3C recommendation for CSS functionality in their browser products.

Historically speaking, attributes played a key role in HTML formatting. All the way up to HTML4, there is a heavy reliance on attributes to specify colors, borders, spacing, position, and just about every other formatting option supported by HTML. With the adoption of XHTML, most of these attributes were deprecated in favor of the more powerful and flexible CSS model. In an attempt to follow modern user interface coding standards, I've used CSS and generated properly formed HTML in the examples of this chapter. All HTML results have
been tested for standards conformance in both Internet Explorer 6 and Firefox 2.0.

SQL server 2008 : FULL-TEXT CONTAINS VS. XQUERY CONTAINS

The full-text search CONTAINS predicate is not the same as the XQuery contains predicate. The XQuery contains predicate performs a substring match similar to the T-SQL CHARINDEX function. The matches performed by the XQuery contains predicate are case sensitive.
The T-SQL CONTAINS predicate, on the other hand, includes all of the flexibility of the SQL Server full-text search functionality. This includes the ability to perform thesaurus lookups, word stemming, and proximity searches.

The downside to the T-SQL CONTAINS predicate is that you cannot specify node paths to narrow your search using them. The T-SQL full-text search is an all-or-nothing proposition—if you want to search for a word in your XML data using a full-text search, the word can appear anywhere in the XML content. This is why it makes sense to use the T-SQL CONTAINS predicate in conjunction with the XQuery contains predicate for maximum flexibility and performance.

SQL server 2008 : HTTP SOAP Endpoints

A powerful feature introduced in SQL Server 2005, SQL Server 2008 continues providing support for native HTTP SOAP endpoints, which use the XML-based SOAP protocol. HTTP SOAP endpoints provide an efficient, secure, easy-to-configure option for providing SQL Server–based
web service support. The built-in HTTP SOAP endpoint support makes it much easier to expose SQL Server functionality as web services than was previously possible via the Internet Information Server (IIS)–based web services available in SQL Server 2000.

SQL server 2008 : XQuery and XML DML Support

The new xml data type provides several methods to allow querying and modification of XML data. These new methods, including the query(), value(), exist(), nodes(), and modify() methods, support XQuery querying, XML shredding, and XML DML manipulation of your XML data. The SQL Server 2008 XQuery implementation is a powerful subset of the W3C XML Query Language specification, featuring support for path expressions, FLWOR (for-let-whereorder- by-return) expressions, standard functions and operators, and XML DML statements.

SQL server 2008 :FOR XML

SQL Server includes improvements to the legacy FOR XML clause. One improvement is tighter integration with the new xml data type, including options to generate native xml-typed results. FOR XML results can be assigned to variables of the xml data type, with additional support for nesting FOR XML queries, an improvement on the SQL Server 2000 FOR XML clauses, which were limited only to the top level of a SELECT statement. The FOR XML PATH mode, also carried over from SQL Server 2005, is an improvement over the legacy FOR XML EXPLICIT mode. With builtin support for XPath-style expressions, FOR XML PATH makes generating XML in explicit structures
much easier than was possible in SQL Server 2000.

The FOR XML RAW mode has also been improved with additional features, including the ability to rename the default row element name, the ability to explicitly specify the root node, and the ability to retrieve your data in an element-centric format. The FOR XML AUTO and FOR XML EXPLICIT modes have also been improved with additional options and settings.

While some options have been deprecated, several additional options have been added to the FOR XML clauses since the SQL Server 2000 version, including the ELEMENTS XSINIL option, which generates elements for NULLs in the result set, and XMLSCHEMA, which generates an inline XML Schema Definition (XSD) in your XML result. T

SQL server 2008 : XML Indexes

In the SQL Server XML model, whenever you query or manipulate XML data, the data is first converted to a relational format in a process known as shredding. This process can be time consuming when manipulating large XML documents or when querying large numbers of xml data type instances. SQL Server 2008 supports indexing of xml data type columns. Indexing xml columns helps the SQL optimizer significantly improve query performance on XML data stored in the database. The performance is improved by building an index of your XML data by converting it to a relational format, a process known as preshredding. The XML index preshredding process eliminates the shredding step during a query or XML data manipulation, resulting in much faster and less resource-intensive XML query operations. New DML statements have been added to T-SQL to make XML index management relatively easy.

SQL server 2008 xml Data Type - New feature

Prior to SQL Server 2005, SQL Server provided extremely limited support for storing, managing, and manipulating XML data. SQL Server 2000 implemented its XML capabilities through implementation of the FOR XML clause and kludgy LOB data type operations combined with
specialized system-stored procedures. SQL Server 2005 introduced the xml data type, promoting XML data storage and manipulations to first-class status in SQL Server.

The xml data type remains one of the most important XML-specific features in SQL Server 2008. The xml data type supports the storage of typed XML documents and fragments that have been validated against an XML schema collection and untyped XML data which has not. The
xml data type can be used to declare columns in a table, T-SQL variables, parameters, and as the return type of a function. Data can also be cast to and from the xml data type. In addition, the xml data type brings with it a set of methods useful for querying, shredding, and manipulating XML data.

What’s New in SQL Server 2008 XML

SQL Server 2008 provides several enhancements over SQL Server 2000 in terms of XML support and some enhancements over SQL Server 2005. While much of the backward-compatible XML-specific functionality from SQL Server 2000 is available in SQL Server 2008, most of it has been deprecated in favor of the new features and functionality. This section gives a broad  overview of the major enhancements to XML support, which include the following items:

• New xml data type
• XML schema collections
• XML indexes
• FOR XML enhancements, including XPath support in the FOR XML PATH clause
• XQuery and XML DML support
• SQLCLR xml data type support
• Improvements to legacy XML functionality, including improvements to the sp_xml_preparedocument procedure
• HTTP Simple Object Access Protocol (SOAP) endpoints

Oracle Admin : Creating Initial Control Files

The initial control files of an Oracle Database are created when you issue the CREATE DATABASE statement. The names of the control files are specified by the CONTROL_FILES parameter in the initialization parameter file used during database creation. The filenames specified in CONTROL_FILES should be fully specified and are operating system specific. The following is an example of a CONTROL_FILES initialization parameter:

CONTROL_FILES = (/u01/oracle/prod/control01.ctl,
                /u02/oracle/prod/control02.ctl,
                /u03/oracle/prod/control03.ctl)

If files with the specified names currently exist at the time of database creation, you must specify the CONTROLFILE REUSE clause in the CREATE DATABASE statement, or else an error occurs. Also, if the size of the old control file differs from the SIZE parameter of the new one, you cannot use the REUSE clause.

The size of the control file changes between some releases of Oracle Database, as well as when the number of files specified in the control file changes. Configuration parameters such as MAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, MAXDATAFILES, and MAXINSTANCES affect control file size.

You can subsequently change the value of the CONTROL_FILES initialization parameter to add more control files or to change the names or locations of existing control files.

Oracle : Application Developers Responsibility

Application developers design and implement database applications. Their responsibilities include the following tasks:

  • Designing and developing the database application

  • Designing the database structure for an application

  • Estimating storage requirements for an application

  • Specifying modifications of the database structure for an application

  • Relaying this information to a database administrator

  • Tuning the application during development

  • Establishing security measures for an application during development

Oracle Admin : Security Officers Responsibility

In some cases, a site assigns one or more security officers to a database. A security officer enrolls users, controls and monitors user access to the database, and maintains system security. As a DBA, you might not be responsible for these duties if your site has a separate security officer.

Oracle Admin : Database administrator's responsibilities

A database administrator's responsibilities can include the following tasks:
  • Installing and upgrading the Oracle Database server and application tools

  • Allocating system storage and planning future storage requirements for the database system

  • Creating primary database storage structures (tablespaces) after application developers have designed an application

  • Creating primary objects (tables, views, indexes) once application developers have designed an application

  • Modifying the database structure, as necessary, from information given by application developers

  • Enrolling users and maintaining system security

  • Ensuring compliance with Oracle license agreements

  • Controlling and monitoring user access to the database

  • Monitoring and optimizing the performance of the database

  • Planning for backup and recovery of database information

  • Maintaining archived data on tape

  • Backing up and restoring the database

  • Contacting Oracle for technical support


Oracle Admin : Types of Oracle Database Users

Following Different types of Oracle database Users

  • Database Administrators
  • Security Officers
  • Network Administrators
  • Application Developers
  • Application Administrators
  • Database Users

SQL server 2005 Question With Answer

Question

run a report weekly on Monday. There is a spreadsheet in which I change the Startdate and enddate only in the WeeklyMSfile.xls and worksheet is Weekly and column are A1 and A2. Suppose I am running report on Monday 07, 2008. I will put startdate as 06/30/2008 and Enddate will be 07/07/2008. After putting the date I run the executable file which is looking data from spreadsheet and I get the result in text format.

I just want to automate the spreadsheet to avoid weekly input data of startdate and enddate. My question is how can I create DTS-package so that when I run the DTS-package, automatically change the startdate and enddate and run the executable file.


Answer

Spreadsheet name is: WeeklyMSfile.xls

Executable file name is : WeeklyMS.exe

1. Import the Excel data into a #temptable

2. Change the columns names with sp_rename

3. Export the #temptable to Excel

SQL server 2005 Question With Answer

 Question :I tried to search if this had been asked before but didn't found anything so I hope It has not been 100 times before me.

Is it possible to check if a database allready exist in the SQL Server 2005? If for example I want to create a database called "Testing" I first want to check if the database exists before I create it.

Answer :
if not exists(select * from sys.databases where name = 'Testing')
    create database testing

SQL Query

Question : If a column as has been declared as a primary key with auto increment(IDENTITY(1,1) and it keeps on incrementing when a record is added what can can I do to reinitialise the seed to start at 1 again after deleting all the records in a table.

Answer  1:

You can use the DBCC function or Truncate the table.

 DBCC CHECKIDENT ( <table name>,RESEED,<new value>)

 Truncate Table <table name>

Answer  2:

Here is a simple sample for the question:

--Drop the foreign key

ALTER TABLE dbo.CategoryTable1Sub

DROP CONSTRAINT FK_CategoryID

GO

truncate table dbo.CategoryTable1

truncate table dbo.CategoryTable1Sub

GO

--Add Foreign key back

ALTER TABLE dbo.CategoryTable1Sub ADD CONSTRAINT

FK_CategoryID FOREIGN KEY

( CatID )REFERENCES dbo.CategoryTable1

( Category_ID )

GO


Answer  3:

f you are not able to TRUNCATE, and the issues of removing the CONSTRAINTS are burdensome, as Ken indicated, you may wish to try using the DBCC RESEED functionality.

 

Something like this:

 

DBCC CHECKIDENT ("YourTable", RESEED, 1);.

 

How many places to the right of the decimal can be stored in a CURRENCY data field?

The CURRENCY data type can store up to four places to the right of the decimal.

What is the highest value that can be stored in a BYTE data field?

The highest value that can be stored in a BYTE field is 255. or from
-128 to 127. Byte is a set of Bits that represent a single character.
Usually there are 8 Bits in a Byte, sometimes more, depending on
how the measurement is being made. Each Char requires one byte of
memory and can have a value from 0 to 255 (or 0 to 11111111 in
binary).

Write SQL query

Question : In the domain table we have status as a numeric value from 01 to 04 and we  have text definition of these values in the design document.
Write SQL query to see the result as a text definitions that is corresponded  to these values. (DB2)

Answer:  select TB1.member_id, TB1.bu_id, TB1.program,  TB2.num,
case TB1.status
when '01' then 'Auto renew'
when '02' then 'Expired'
when '03' then 'Sold'
when '04' then 'Terminated'

else TB_name.status
end
       from DB_name.TB_name1  TB1,
DB_name.TB_name2 TB2
       where
       TB1.program in ('com', 'org')
       and TB1.member_role  = '100'
       order by  TB1.member_id
       fetch first 30 rows only

What is transaction? In terms of Database

A. A transaction is a collection of applications code and database
manipulation code bound into an indivisible unit of execution.
it consists from:

BEGIN-TRANSACTION Name
Code
END TRANSACTION Name

What are the main components of Database management systems?

The database management system software includes components for
storage management, concurrency control, transaction
processing, database manipulation interface, database definition
interface, and database control interface.

What is query optimization?

Query optimization is the part of the query process in which the
database system compares different query strategies and chooses the
one with the least expected cost

What Oracle lock modes do you know?

Oracle has two lock modes: shared or exclusive.
Shared locks are set on database resources so that many transactions
can access the resource.
Exclusive locks are set on resources that ensure one transaction has
exclusive access to the database resource

What is Oracle locking?

Oracle uses locking mechanisms to protect data from being destroyed by
concurrent transactions.

Which of the following statements are Data Manipulation Language commands?

A. INSERT
B. UPDATE
C. GRANT
D. TRUNCATE
E. CREATE

How you will create a column alias? (Oracle 8i)

The AS keyword is optional when specifying a column alias. You must
enclose the column alias in double quotes when the alias
contains a space or lowercase letters. If you specify an alias in
lowercase letters without double quotes, the alias will appear in
uppercase.

Which operator do you use to return all of the rows from one query except rows are returned in a second query?

You use the MINUS operator to return all rows from one query except
where duplicate rows are found in a second query. The UNION operator
returns all rows from both queries minus duplicates. The UNION ALL
operator returns all rows from both queries including duplicates.
The INTERSECT operator returns only those rows that exist in both queries.

How Oracle executes a statement with nested subqueries?

When Oracle executes a statement with nested subqueries,it always executes the innermost query first. This query passes its results to the next query and so on until it reaches the outermost query.
It is the outermost query that returns a result set.

LINQ to SQL Statements Select with a Where Clause

public void SimpleQuery3()
{
DataClasses1DataContext dc = new DataClasses1DataContext();

var q =
from a in dc.GetTable<Order>()
where a.CustomerID == "VINET"
select a;

dataGridView1.DataSource = q;
}

simple LINQ to SQL statement

public void SimpleQuery()
{
DataClasses1DataContext dc = new DataClasses1DataContext();

var q =
from a in dc.GetTable<Order>()
select a;

dataGridView1.DataSource = q;
}

SQL Server Performance Tips and Guidelines

• As a common practice, every table should have a clustered index. Generally, but not always, the clustered index should be on a column that monotonically increases, such as an identity column or some other column where the value is unique. In many cases, the primary key is the ideal column for a clustered index.

• Indexes should be measured on all columns that are frequently used in WHERE, ORDER BY, GROUP BY, TOP and DISTINCT clauses.

• Do not automatically add indexes on a table because it seems like the right thing to do. Only add indexes if you know that they will be used by the queries run against the table.

• For historical (static) tables, create the indexes with a FILLFACTOR and a PAD_INDEX of 100 to ensure there is no wasted space. This reduces disk I/O, helping to boost overall performance.

• Queries that return a single row are just as fast using a non-clustered index as a clustered index.

• Queries that return a range of rows are just as fast using a clustered index as a non-clustered index.

• Do not add more indexes on your OLTP tables to minimize the overhead that occurs with indexes during data modifications.

• Do not add the same index more than once on a table with different names.

• Drop all those indexes that are not used by the Query Optimizer, generally. You probably won't want to add an index to a table under the following conditions:

If the index is not used by the query optimizer. Use the Query Analyzer's "Show Execution Plan" option to see if your queries against a particular table use an index or not.
If the table is small, most likely indexes will not be used.
If the column(s) to be indexed are very wide.
If the column(s) are defined as TEXT, NTEXT or IMAGE data types.
If the table is rarely queried but insertion, updating is frequent.

• To provide up-to-date statistics, the query optimizer needs to make smart query optimization decisions. You will generally want to leave the "Auto Update Statistics" database option on. This helps to ensure that the optimizer statistics are valid, ensuring that queries are properly optimized when they are run.

• Keep the "width" of your indexes as narrow as possible. This reduces the size of the index and reduces the number of disk I/O reads required to read the index.

• If possible, try to create indexes on columns that have integer values instead of characters. Integer values use less overhead than character values.

• If you have two or more tables that are frequently joined together, then the columns used for the joins should have an appropriate index. If the columns used for the joins are not naturally compact, then consider adding surrogate keys to the tables that are compact in order to reduce the size of the keys. This will decrease I/O during the join process, which increases overall performance.

• When creating indexes, try to make them unique indexes if at all possible. SQL Server can often search through a unique index faster than a non-unique index. This is because, in a unique index, each row is unique and once the needed record is found, SQL Server doesn't have to look any further.

• If a particular query against a table is run infrequently and the addition of an index greatly speeds the performance of the query, but the performance of INSERTS, UPDATES and DELETES is negatively affected by the addition of the index, consider creating the index for the table for the duration of when the query is run and then dropping the index. An example of this is when monthly reports are run at the end of the month on an OLTP application.

• Avoid using FLOAT or REAL data types as primary keys, as they add unnecessary overhead that can hurt performance.

• If you want to boost the performance of a query that includes an AND operator in the WHERE clause, consider the following:

Of the search criteria in the WHERE clause, at least one of them should be based on a highly selective column that has an index.
If at least one of the search criteria in the WHERE clause is not highly selective, consider adding indexes to all of the columns referenced in the WHERE clause.
If none of the columns in the WHERE clause are selective enough to use an index on their own, consider creating a covering index for this query.

• The Query Optimizer will always perform a table scan or a clustered index scan on a table if the WHERE clause in the query contains an OR operator and if any of the referenced columns in the OR clause are not indexed (or do not have a useful index). Because of this, if you use many queries with OR clauses, you will want to ensure that each referenced column in the WHERE clause has an index.

• If you have a query that uses ORs and it is not making the best use of indexes, consider rewriting it as a UNION and then testing performance. Only through testing can you be sure that one version of your query will be faster than another.

• If you use the SOUNDEX function against a table column in a WHERE clause, the Query Optimizer will ignore any available indexes and perform a table scan.

• Queries that include either the DISTINCT or the GROUP BY clauses can be optimized by including appropriate indexes. Any of the following indexing strategies can be used:

Include a covering, non-clustered index (covering the appropriate columns) of the DISTINCT or the GROUP BY clauses.
Include a clustered index on the columns in the GROUP BY clause.
Include a clustered index on the columns found in the SELECT clause.
Adding appropriate indexes to queries that include DISTINCT or GROUP BY is most important for those queries that run often.

• Avoid clustered indexes on columns that are already "covered" by non-clustered indexes. A clustered index on a column that is already "covered" is redundant. Use the clustered index for columns that can better make use of it.

• Ideally a clustered index should be based on a single column (not multiple columns) that are as narrow as possible. This not only reduces the clustered index's physical size, it also reduces the physical size of non-clustered indexes and boosts SQL Server's overall performance.

• When you create a clustered index, try to create it as a unique clustered index, not a non-unique clustered index.

• SET NOCOUNT ON at the beginning of each stored procedure you write. This statement should be included in every stored procedure, trigger, etc. that you write.

• Keep Transact-SQL transactions as short as possible within a stored procedure. This helps to reduce the number of locks, helping to speed up the overall performance of your SQL Server application.

• If you are creating a stored procedure to run in a database other than the Master database, don't use the prefix sp_ in its name. This special prefix is reserved for system stored procedures. Although using this prefix will not prevent a user defined stored procedure from working, what it can do is to slow down its execution ever so slightly.

• Before you are done with your stored procedure code, review it for any unused code, parameters or variables that you may have forgotten to remove while you were making changes and remove them. Unused code just adds unnecessary bloat to your stored procedures, although it will not necessarily negatively affect performance of the stored procedure.

• For best performance, all objects that are called within the same stored procedure should be owned by the same object owner or schema, preferably dbo, and should also be referred to in the format of object_owner.object_name or schema_owner.object_name.

• When you need to execute a string of Transact-SQL, you should use the sp_executesql stored procedure instead of the EXECUTE statement.

• If you use input parameters in your stored procedures, you should validate all of them at the beginning of your stored procedure. This way, if there is a validation problem and the client application needs to be notified of the problem, it happens before any stored procedure processing takes place, preventing wasted effort and boosting performance.

• When calling a stored procedure from your application, it is important that you call it using its qualified name, for example:

exec dbo.myProc

...instead of:

exec myProc

• If you think a stored procedure will return only a single value and not a record set, consider returning the single value as an output parameter.

• Use stored procedures instead of views. They offer better performance.

• Don't include code, variable or parameters that don't do anything.

• Don't be afraid to make broad-minded use of in-line and block comments in your Transact-SQL code. They will not affect the performance of your application and they will enhance your productivity when you have to come back to the code and try to modify it.

• If possible, avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performance and scalability of your applications.

• If you have the choice of using a join or a sub-query to perform the same task within a query, generally the join is faster. This is not always the case, however, and you may want to test the query using both methods to determine which is faster for your particular application.

• If your application requires you to create temporary tables for use on a global or per connection use, consider the possibility of creating indexes for these temporary tables. While most temporary tables probably won't need -- or even use -- an index, some larger temporary tables can benefit from them. A properly designed index on a temporary table can be as great a benefit as a properly designed index on a standard database table.

• Instead of using temporary tables, consider using a derived table instead. A derived table is the result of using a SELECT statement in the FROM clause of an existing SELECT statement. By using derived tables instead of temporary tables, you can reduce I/O and often boost your application's performance.

• For better performance, if you need a temporary table in your Transact-SQL code, consider using a table variable instead of creating a conventional temporary table.

• Don't repeatedly reuse the same function to calculate the same result over and over within your Transact-SQL code.

• If you use BULK INSERT to import data into SQL Server, then use the TABLOCK hint along with it. This will prevent SQL Server from running out of locks during very large imports and will also boost performance due to the reduction of lock contention.

• Always specify the narrowest columns you can. The narrower the column, the less amount of data SQL Server has to store and the faster SQL Server is able to read and write data. In addition, if any sorts need to be performed on the column, the narrower the column, the faster the sort will be.

• If you need to store large strings of data and they are less than 8000 characters, use a VARCHAR data type instead of a TEXT data type. TEXT data types have extra overhead that drag down performance.

• Don't use the NVARCHAR or NCHAR data types unless you need to store 16-bit character (Unicode) data. They take up twice as much space as VARCHAR or CHAR data types, increasing server I/O and wasting unnecessary space in your buffer cache.

• If the text data in a column varies greatly in length, use a VARCHAR data type instead of a CHAR data type. The amount of space saved by using VARCHAR over CHAR on variable length columns can greatly reduce the I/O reads that the cache memory uses to hold data, improving overall SQL Server performance.

• If a column's data does not vary widely in length, consider using a fixed-length CHAR field instead of a VARCHAR. While it may take up a little more space to store the data, processing fixed-length columns is faster in SQL Server than processing variable-length columns.

• If you have a column that is designed to hold only numbers, use a numeric data type such as INTEGER instead of a VARCHAR or CHAR data type. Numeric data types generally require less space to hold the same numeric value than does a character data type. This helps to reduce the size of the columns and can boost performance when the columns are searched (WHERE clause), joined to another column or sorted.

• If you use the CONVERT function to convert a value to a variable length data type such as VARCHAR, always specify the length of the variable data type. If you do not, SQL Server assumes a default length of 30. Ideally, you should specify the shortest length to accomplish the required task. This helps to reduce memory use and SQL Server resources.

• Avoid using the new BIGINT data type unless you really need its additional storage capacity. The BIGINT data type uses 8 bytes of memory, versus 4 bytes for the INT data type.

• Don't use the DATETIME data type as a primary key. From a performance perspective, it is more efficient to use a data type that uses less space. For example, the DATETIME data type uses 8 bytes of space, while the INT data type only takes up 4 bytes. The less space used, the smaller the table and index, and the less I/O overhead that is required to access the primary key.

• If you are creating a column that you know will be subject to many sorts, consider making the column integer-based and not character-based. This is because SQL Server can sort integer data much faster than character data.

• Carefully evaluate whether your SELECT query needs the DISTINCT clause or not. Some developers automatically add this clause to every one of their SELECT statements, even when it is not necessary. This is a bad habit that should be stopped.

• When you need to use SELECT INTO option, keep in mind that it can lock system tables, preventing other users from accessing the data they need while the data is being inserted. In order to prevent or minimize the problems caused by locked tables, try to schedule the use of SELECT INTO when your SQL Server is less busy. In addition, try to keep the amount of data inserted to a minimum. In some cases, it may be better to perform several smaller SELECT INTOs instead of performing one large SELECT INTO.

• If you need to verify the existence of a record in a table, don't use SELECT COUNT (*) in your Transact-SQL code to identify it. This is very inefficient and wastes server resources. Instead, use the Transact-SQL IF EXISTS to determine if the record in question exists, which is much more efficient.

• By default, some developers -- especially those who have not worked with SQL Server before -- routinely include code similar to this in their WHERE clauses when they make string comparisons:

SELECT column_name FROM table_name
WHERE LOWER (column_name) = 'name'

In other words, these developers are making the assumption that the data in SQL Server is case-sensitive, which it generally is not. If your SQL Server database is not configured to be case sensitive, you don't need to use LOWER or UPPER to force the case of text to be equal for a comparison to be performed. Just leave these functions out of your code. This will speed up the performance of your query, as any use of text functions in a WHERE clause hurts performance.

However, what if your database has been configured to be case-sensitive? Should you then use the LOWER and UPPER functions to ensure that comparisons are properly compared? No. The above example is still poor coding. If you have to deal with ensuring case is consistent for proper comparisons, use the technique described below, along with appropriate indexes on the column in question:

SELECT column_name FROM table_name
WHERE column_name = 'NAME' or column_name = 'name'

This code will run much faster than the first example.

• If you currently have a query that uses NOT IN, which offers poor performance because the SQL Server optimizer has to use a nested table scan to perform this activity, instead try to use one of the following options, all of which offer better performance:

Use EXISTS or NOT EXISTS
Use IN
Perform a LEFT OUTER JOIN and check for a NULL condition

• When you have a choice of using the IN or the EXISTS clause in your Transact-SQL, you will generally want to use the EXISTS clause, as it is usually more efficient and performs faster.

• If you find that SQL Server uses a TABLE SCAN instead of an INDEX SEEK when you use an IN/OR clause as part of your WHERE clause, even when those columns are covered by an index, consider using an index hint to force the Query Optimizer to use the index.

• If you use LIKE in your WHERE clause, try to use one or more leading characters in the clause, if possible. For example, use:

LIKE 'm%' instead of LIKE '%m'

• If your application needs to retrieve summary data often, but you don't want to have the overhead of calculating it on the fly every time it is needed, consider using a trigger that updates summary values after each transaction into a summary table.

• When you have a choice of using the IN or the BETWEEN clauses in your Transact-SQL, you will generally want to use the BETWEEN clause, as it is much more efficient. For example...

SELECT task_id, task_name
FROM tasks
WHERE task_id in (1000, 1001, 1002, 1003, 1004)

...is much less efficient than this:

SELECT task_id, task_name
FROM tasks
WHERE task_id BETWEEN 1000 and 1004

• If possible, try to avoid using the SUBSTRING function in your WHERE clauses. Depending on how it is constructed, using the SUBSTRING function can force a table scan instead of allowing the optimizer to use an index (assuming there is one). If the substring you are searching for does not include the first character of the column you are searching for, then a table scan is performed.

• If possible, you should avoid using the SUBSTRING function and use the LIKE condition instead for better performance. Instead of doing this:

WHERE SUBSTRING(task_name,1,1) = 'b'

Try using this instead:

WHERE task_name LIKE 'b%'

• Avoid using optimizer hints in your WHERE clauses. This is because it is generally very hard to out-guess the Query Optimizer. Optimizer hints are special keywords that you include with your query to force how the Query Optimizer runs. If you decide to include a hint in a query, this forces the Query Optimizer to become static, preventing the Query Optimizer from dynamically adapting to the current environment for the given query. More often than not, this hurts -- not helps -- performance.

• If you have a WHERE clause that includes expressions connected by two or more AND operators, SQL Server will evaluate them from left to right in the order they are written. This assumes that no parentheses have been used to change the order of execution. Because of this, you may want to consider one of the following when using AND:

Locate the least likely true AND expression first.
If both parts of an AND expression are equally likely of being false, put the least complex AND expression first.
You may want to consider using Query Analyzer or Management Studio to look at the execution plans of your queries to see which is best for your situation

• Don't use ORDER BY in your SELECT statements unless you really need to, as it adds a lot of extra overhead. For example, perhaps it may be more efficient to sort the data at the client than at the server.

• Whenever SQL Server has to perform a sorting operation, additional resources have to be used to perform this task. Sorting often occurs when any of the following Transact-SQL statements are executed:

ORDER BY
GROUP BY
SELECT DISTINCT
UNION

• If you have to sort by a particular column often, consider making that column a clustered index. This is because the data is already presorted for you and SQL Server is smart enough not to resort the data.

• If your WHERE clause includes an IN operator along with a list of values to be tested in the query, order the list of values so that the most frequently found ones are placed at the start of the list and the less frequently found ones are placed at the end of the list. This can speed up performance because the IN option returns true as soon as any of the values in the list produce a match. The sooner the match is made, the faster the query completes.

• If your application performs many wildcard (LIKE %) text searches on CHAR or VARCHAR columns, consider using SQL Server's full-text search option. The Search Service can significantly speed up wildcard searches of text stored in a database.

• The GROUP BY clause can be used with or without an aggregate function. However, if you want optimum performance, don't use the GROUP BY clause without an aggregate function. This is because you can accomplish the same end result by using the DISTINCT option instead, and it is faster. For example, you could write your query two different ways:

SELECT task_id
FROM tasks
WHERE task_id BETWEEN 10 AND 20
GROUP BY OrderID

...or:

SELECT DISTINCT task_id
FROM tasks
WHERE task_id BETWEEN 10 AND 20

• It is important to design applications that keep transactions as short as possible. This reduces locking and increases application concurrently, which helps to boost performance.

• In order to reduce network traffic between the client or middle-tier and SQL Server -- and also to boost your SQL Server-based application's performance -- only the data needed by the client or middle-tier should be returned by SQL Server. In other words, don't return more data (both rows and columns) from SQL Server than you need to the client or middle-tier and then further reduce the data to the data you really need at the client or middle-tier. This wastes SQL Server resources and network bandwidth.

• To make complex queries easier to analyze, consider breaking them down into their smaller constituent parts. One way to do this is to simply create lists of the key components of the query, such as:

List all of the columns that are to be returned
List all of the columns that are used in the WHERE clause
List all of the columns used in the JOINs (if applicable)
List all the tables used in JOINs (if applicable)
Once you have the above information organized into this easy-to-comprehend form, it is much easier to identify those columns that could potentially make use of indexes when executed.

What is SQL Server Monitoring?

Server monitoring is a challenge for SQL Server administrators. On average, SQL Server DBAs are responsible for twice as many servers as their peers using other platforms. The DBA also has a number of tasks to accomplish. How do DBAs get everything done in a day? They use the scripting languages just mentioned to automate their processes.

In an ideal world, databases would be self-monitoring. The database itself would kill a hanging process automatically. The creation of a new database would cause the automatic creation of backup jobs. The database would do what's needed to keep query performance above a certain accepted level. Unfortunately, none of the database providers are even close to providing this functionality. That's why DBAs are still needed.

There are two kinds of monitoring scenarios:

  • Reactive monitoring deals more with the resolution of existing issues or those that crop up.

  • Proactive monitoring is the process of looking at a current server state and making estimates and plans for changes to the underlying objects. The objective is to prevent issues, increase scalability, and maintain availability.

Command for Start SQLCMD

To get started with SQLCMD, go to the command prompt and type SQLCMD. The basic switch for working with SQLCMD is -S, which identifies the server.

To provide an instance, the command would be:

sqlcmd -S ComputerName\InstanceName.

The authentication type has three switches:

-E is the default and uses the local user.

-U lets you specify a user, such as SA.

-P is the password. Passwords are case-sensitive. If the -P option is not used, and the SQLCMDPASSWORD environment variable has not been set, SQLCMD prompts the user for a password. If the -P option is used at the end of the command prompt without a password, SQLCMD uses the default password (NULL).

SQL Server 2005 Remote Management Features

One of the real challenges facing administrators is how to manage more and more servers. Operations such as manufacturing and customer support are done around the globe, with local copies of data being synchronized during smaller and smaller windows. Administrators need to be able to remotely install, monitor, troubleshoot, and maintain remote servers. The SQL Server tools team has delivered three categories of interfaces to manage remote environments:

  • SQLCMD is for folks who are comfortable with command prompt applications. For customers migrating or currently using the command prompt languages, OSQL and ISQL are deprecated and have been replaced with SQLCMD. SQLCMD is a command-line executable. You invoke it at the command prompt by typing SQLCMD.

  • SQL Server Management Objects (SMO) is for those who build user interface–oriented applications. DBAs who want to build custom management tools will find that SMO has replaced DMO. SMO is a new API architecture that overcomes the limitations of DMO. SMO is scalable, reliable, and flexible. SMO is significantly more robust than DMO, because it is used by SQL Server Management Studio to connect and work with SQL Server instances. Every function found in SQL Server Management Studio is made possible by SMO.

  • Windows Management Instrumentation (WMI) allows the use of Windows scripting languages, such as VBScript, and it's more complicated than SMO or SQLCMD. WMI is powerful and provides deep hooks into the operating system, which is beyond the reach of SQLCMD and SMO. In an extremely complex infrastructure, the WMI provider may prove to be the most complete solution.

Remote functionality is also enhanced with new capabilities for scripting and working with Replication and Analysis Services (via respective .NET libraries), Replication Management Objects, and Analysis Management Objects.

The Top 10 Good Leadership Qualities

1.Vision
=======
A leader with vision has a clear, vivid picture of where to go, as well as a firm grasp on what success looks like and how to achieve it. But it's not enough to have a vision; leaders must also share it and act upon it. Jack Welch, former chairman and CEO of General Electric Co., said, "Good business leaders create a vision, articulate the vision, passionately own the vision and relentlessly drive it to completion."

A leader must be able to communicate his or her vision in terms that cause followers to buy into it. He or she must communicate clearly and passionately, as passion is contagious.

A good leader must have the discipline to work toward his or her vision single-mindedly, as well as to direct his or her actions and those of the team toward the goal. Action is the mark of a leader. A leader does not suffer "analysis paralysis" but is always doing something in pursuit of the vision, inspiring others to do the same.

2.Integrity
=========
Integrity is the integration of outward actions and inner values. A person of integrity is the same on the outside and on the inside. Such an individual can be trusted because he or she never veers from inner values, even when it might be expeditious to do so. A leader must have the trust of followers and therefore must display integrity.

Honest dealings, predictable reactions, well-controlled emotions, and an absence of tantrums and harsh outbursts are all signs of integrity. A leader who is centered in integrity will be more approachable by followers.

3. Dedication
============
Dedication means spending whatever time or energy is necessary to accomplish the task at hand. A leader inspires dedication by example, doing whatever it takes to complete the next step toward the vision. By setting an excellent example, leaders can show followers that there are no nine-to-five jobs on the team, only opportunities to achieve something great.

4.Magnanimity
============
Magnanimity means giving credit where it is due. A magnanimous leader ensures that credit for successes is spread as widely as possible throughout the company. Conversely, a good leader takes personal responsibility for failures. This sort of reverse magnanimity helps other people feel good about themselves and draws the team closer together. To spread the fame and take the blame is a hallmark of effective leadership.

5.humility
==========
Leaders with humility recognize that they are no better or worse than other members of the team. A humble leader is not self-effacing but rather tries to elevate everyone. Leaders with humility also understand that their status does not make them a god. Mahatma Gandhi is a role model for Indian leaders, and he pursued a "follower-centric" leadership role.

6.Openness
==========
Openness means being able to listen to new ideas, even if they do not conform to the usual way of thinking. Good leaders are able to suspend judgment while listening to others' ideas, as well as accept new ways of doing things that someone else thought of. Openness builds mutual respect and trust between leaders and followers, and it also keeps the team well supplied with new ideas that can further its vision.

7.Creativity
===========
Creativity is the ability to think differently, to get outside of the box that constrains solutions. Creativity gives leaders the ability to see things that others have not seen and thus lead followers in new directions. The most important question that a leader can ask is, "What if … ?" Possibly the worst thing a leader can say is, "I know this is a dumb question ... "

8.Fairness
==========
Fairness means dealing with others consistently and justly. A leader must check all the facts and hear everyone out before passing judgment. He or she must avoid leaping to conclusions based on incomplete evidence. When people feel they that are being treated fairly, they reward a leader with loyalty and dedication.

9.Assertiveness
==============
Assertiveness is not the same as aggressiveness. Rather, it is the ability to clearly state what one expects so that there will be no misunderstandings. A leader must be assertive to get the desired results. Along with assertiveness comes the responsibility to clearly understand what followers expect from their leader.

Many leaders have difficulty striking the right amount of assertiveness, according to a study in the February 2007 issue of the Journal of Personality and Social Psychology, published by the APA (American Psychological Association). It seems that being underassertive or overassertive may be the most common weakness among aspiring leaders.

10.Sense of humor
===============
A sense of humor is vital to relieve tension and boredom, as well as to defuse hostility. Effective leaders know how to use humor to energize followers. Humor is a form of power that provides some control over the work environment. And simply put, humor fosters good camaraderie.

Intrinsic traits such as intelligence, good looks, height and so on are not necessary to become a leader. Anyone can cultivate the proper leadership traits.

What is SOAP?

The basic Web services platform is XML plus HTTP.

  • SOAP stands for Simple Object Access Protocol
  • SOAP is a communication protocol
  • SOAP is for communication between applications
  • SOAP is a format for sending messages
  • SOAP is designed to communicate via Internet
  • SOAP is platform independent
  • SOAP is language independent
  • SOAP is based on XML
  • SOAP is simple and extensible
  • SOAP allows you to get around firewalls
  • SOAP will be developed as a W3C standard

Why Web Services?

Interoperability has highest priority.

When all major platforms could access the Web using Web browsers, different platforms could interact. For these platforms to work together, Web applications were developed.

Web applications are simple applications run on the web. These are built around the Web browser standards and can mostly be used by any browser on any platform.


Web services take Web applications to the next level.


Using Web services your application can publish its function or message to the rest of the world.

Web services uses XML to code and decode your data and SOAP to transport it using open protocols.

With Web services your accounting departments Win 2k servers billing system can connect with your IT suppliers UNIX server.


Web services have two types of uses.


Reusable application components


There are things different applications need very often. So why make these over and over again?

Web services can offer application components like currency conversion, weather reports or even language translation as services.

Ideally, there will only be one type of each application component, and anyone can use it in their application.

Connect existing software


Web services help solve the interoperability problem by giving different applications a way to link their data.

Using Web services you can exchange data between different applications and different platforms.

What is a Web service?

A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

Database naming convention

This article references Microsoft SQL Server databases in some examples, but can be used generically with other RDBMSs like Oracle, Sybase etc. too. So, here's preferred naming convention for:

  • Tables
  • Views
  • Stored procedures
  • User defined functions
  • Triggers
  • Indexes
  • Columns
  • User defined data types
  • Primary keys
  • Foreign keys
  • Default and Check constraints
  • Variables
Tables:

Tables represent the instances of an entity. For example, you store all your customer information in a table. Here, 'customer' is an entity and all the rows in the customers table represent the instances of the entity 'customer'. So, why not name your table using the entity it represents, 'Customer'. Since the table is storing 'multiple instances' of customers, make your table name a plural word.

So, name your customer table as '
Customers'.
Name your order storage table as '
Orders'.
Name your error messages table as '
ErrorMessages'.

This is a more natural way of naming tables, when compared to approaches which name tables as tblCustomers, tbl_Orders. Further, when you look at your queries it's very obvious that a particular name refers to a table, as table names are always preceded by FROM clause of the SELECT statement.

If your database deals with different logical functions and you want to group your tables according to the logical group they belong to, it won't hurt prefixing your table name with a two or three character prefix that can identify the group.

For example, your database has tables which store information about Sales and Human resource departments, you could name all your tables related to Sales department as shown below:

SL_NewLeads
SL_Territories
SL_TerritoriesManagers


You could name all your tables related to Human resources department as shown below:

HR_Candidates
HR_PremierInstitutes
HR_InterviewSchedules


This kind of naming convention makes sure, all the related tables are grouped together when you list all your tables in alphabetical order. However, if your database deals with only one logical group of tables, you need not use this naming convention.

Note that, sometimes you end up vertically partitioning tables into two or more tables, though these partitions effectively represent the same entity. In this case, append a word that best identifies the partition, to the entity name.

Views:

A view is nothing but a table,  for any application that is accessing it. So, the same naming convention defined above for tables, applies to views as well, but not always. Here are some exceptions:

1) Views not always represent a single entity. A view can be a combination of two tables based on a join condition, thus, effectively representing two entities. In this case, consider combining the names of both the base tables. Here's an example:

If there is a view combining two tables '
Customers' and 'Addresses', name the view as 'CustomersAddresses'. Same naming convention can be used with junction tables that are used to link two many-to-many related base tables. Most popular example is the 'TitleAuthor' table from 'Pubs' database of SQL Server.

2) Views can summarize data from existing base tables in the form of reports. You can see this type of views in the '
Northwind' database that ships with SQL Server 7.0 and above. Here's the convention that database follows. (I prefer this):

'
Product Sales for 1997'
'
Summary of Sales by Quarter'
'
Summary of Sales by Year'

However, try to stay away from spaces within object names.

Stored procedures:

Stored procedures always do some work for you, they are action oriented. So, let their name describe the work they do. So, use a verb to describe the work.

This is how I would name a stored procedure that fetches me the customer details given the customer identification number:
'
GetCustomerDetails'. Similarly, you could name a procedure that inserts a new customer information as 'InsertCustomerInfo'. Here are some more names based on the same convention: 'WriteAuditRecord', 'ArchiveTransactions', 'AuthorizeUser' etc.

As explained above in the case of tables, you could use a prefix, to group stored procedures also, depending upon the logical group they belong to. For example, all stored procedures that deal with 'Order processing' could be prefixed with ORD_ as shown below:

ORD_InsertOrder
ORD_InsertOrderDetails
ORD_ValidateOrder


If you are using Microsoft SQL Server, never prefix your stored procedures with '
sp_', unless you are storing the procedure in the master database. If you call a stored procedure prefixed with sp_, SQL Server always looks for this procedure in the master database. Only after checking in the master database (if not found) it searches the current database.

I do not agree with the approach of prefixing stored procedures with prefixes like 'sproc_' just to make it obvious that the object is a stored procedure. Any database developer/DBA can identify stored procedures as the procedures are always preceded by
EXEC or EXECUTE keyword.

User defined functions:

In Microsoft SQL Server 2000, User Defined Functions (UDFs) are almost similar to stored procedures, except for the fact that UDFs can be used in SELECT statements. Otherwise, both stored procedures and UDFs are similar. So, the naming conventions discussed above for stored procedures, apply to UDFs as well. You could even use a prefix to logically group your UDFs. For example, you could name all your string manipulation UDFs as shown below:

str_MakeProperCase
str_ParseString

Triggers:

Though triggers are a special kind of stored procedures, it won't make sense to follow the same naming convention as we do for stored procedures.

While naming triggers we have to extend the stored procedure naming convention in two ways:

  • Triggers always depend on a base table and can't exist on their own. So, it's better to link the base table's name with the trigger name
  • Triggers are associated with one or more of the following operations: Insert, Update, Delete. So, the name of the trigger should reflect it's nature

So, here's how I would name the insert, update and delete trigger on titles table:

titles_instrg
titles_updtrg
titles_deltrg

Microsoft SQL Server 7.0 started allowing more than one trigger per action per table. So, you could have 2 insert triggers, 3 update triggers and 4 delete triggers, if you want to! In SQL Server 7.0 you can't control the order of firing of these triggers, however you have some control over the order of firing in SQL Server 2000. Coming back to the point, if you have 2 insert triggers on titles table, use the following naming convention to distinguish the triggers:

titles_ValidateData_instrg
titles_MakeAuditEntries_instrg


Same naming convention could be used with update and delete triggers.

If you have a single trigger for more than one action (same trigger for insert and update or update and delete or any such combination), use the words 'ins', 'upd', 'del' together in the name of the trigger. Here's an example. If you have a single trigger for both insert and update on titles table, name the trigger as
titles_InsUpdtrg

Indexes:

Just like triggers, indexes also can't exist on their own and they are dependent on the underlying base tables. So, again it makes sense to include the 'name of the table' and 'column on which it's built' in the index name. Further, indexes can be of two types, clustered and nonclustered. These two types of indexes could be either unique or non-unique. So, the naming convention should take care of the index types too.

My index naming convention is:
Table name + Column name(s) + Unique/Non-uniqueness + Clustered/Non-clustered

For example, I would name the unique, clustered index on the TitleID column of Titles table as shown below:

Titles_TitleID_U_Cidx

I would name the unique, nonclustered index on the PubID column of Publishers table as shown below:

Publishers_PubID_U_Nidx

Here's how I would name a non-unique, non-clustered index on the OrdeID column of OrderDetails table:

OrderDetails_OrderID_NU_Nidx

Indexes can be composite too, meaning, an index can be built on more than one column. In this case, just concatenate the column names together, just the way we did with junction tables and views above. So, here's how I would name a composite, unique, clustered index on OrderID and OrderDetailID columns of OrderDetails table:

OrderDetails_OrderIDOrderDetailID_U_Cidx

Sure, these index names look long and ugly, but who is complaining? You'll never need to reference these index names in code, unless you are creating/dropping/rebuilding the indexes. So, it's not a pain, but it's a very useful naming convention.

Columns:

Columns are attributes of an entity, that is, columns describe the properties of an entity. So, let the column names be meaningful and natural.

Here's a simplest way of naming the columns of the Customers table:

CustomerID
CustomerFirstName
CustomerAddress


As shown above, it'll be a good idea to prefix the column names with the entity that they are representing.

Here's another idea. Decide on a standard two to four character code for each table in your database and make sure it's unique in the database. For example 'Cust' for Customers table, 'Ord' for Orders tables, 'OrdD' for OrderDetails table, 'Adt' for Audit tables etc. Use this table code to prefix all the column names in that table. Advantage of this convention is that in multi-table queries involving complex joins, you don't have to worry about ambiguous column names, and don't have to use table aliases to prefix the columns. It also makes your queries more readable.

If you have to name the columns in a junction/mapping table, concatenate the table codes of mapped tables, or come up with a new code for that combination of tables.

So, here's how the CustomerID column would appear in Customers table:

Cust_CustomerID

The same CustomerID column appears in the Orders table too, but in Orders table, here's how it's named:

Ord_CustomerID

Some naming conventions even go to the extent of prefixing the column name with it's data type. But I don't like this approach, as I feel, the DBA or the developer dealing with these columns should be familiar with the data types these columns belong to.

User defined data types:

User defined data types are just a wrapper around the base types provided by the database management system. They are used to maintain consistency of data types across different tables for the same attribute. For example, if the CustomerID column appears half a dozen tables, you must use the same data type for all the occurrences of the CustomerID column. This is where user defined data types come in handy. Just create a user defined data type for CustomerID and use it as the data type for all the occurrences of CustomerID column.

So, the simplest way of naming these user defined data types would be: Column_Name + '_type'. So, I would name the CustoerID type as:

CustomerID_type

Primary keys:

Primary key is the column(s) that can uniquely identify each row in a table. So, just use the column name prefixed with 'pk_' + 'Table name' for naming primary keys.

Here's how I would name the primary key on the CustomerID column of Customers table:

pk_Customers_CustomerID

Consider concatenating the column names in case of composite primary keys.

Foreign keys:

Foreign key are used to represent the relationships between tables which are related. So, a foreign key can be considered as a link between the 'column of a referencing table' and the 'primary key column of the referenced table'.

I prefer the following naming convention for foreign keys:

fk_referencing table + referencing column_referenced table + referenced column.

Based on the above convention, I would name the foreign key which references the CustomerID column of the Customers table from the Order's tables CustomerID column as:

fk_OrdersCustomerID_CustomersCustomerID

Foreign key can be composite too, in that case, consider concatenating the column names of referencing and referenced tables while naming the foreign key. This might make the name of the foreign key lengthy, but you shouldn't be worried about it, as you will never reference this name from your code, except while creating/dropping these constraints.

Default and Check constraints:

Use the column name to which these defaults/check constraints are bound to and prefix it with 'def' and 'chk' prefixes respectively for Default and Check constraints. 


I would name the default constraint for OrderDate Column as
def_OrderDate and the check constraint for OrderDate column as chk_OrderDate

Variables:
For variables that store the contents of columns, you could use the same naming convention that we use