SQL Server Tutorial
SQL Server Tutorial
SQL Server Management Studio (SSMS), is the client tool that can be
used to write and execute SQL queries. To connect to the SQL Server
Management Studio.
1. Click Start
2. Select All Programs
3. Select Microsoft SQL Server 2005, 2008, or 2008 R2 (Depending on the
version installed)
4. Select SQL Server Management Studio
You will now see, Connect to Server window.
1. Select Database Engine as the Server Type. The other options that you will see here are Analysis
Services(SSAS), Reporting Services (SSRS) and Integration Services(SSIS).
Server type = Database Engine
2. Next you need to specify the Server Name. Here we can specify the name or the server or IP Address.
If you have SQL Server installed on your local machine, you can specify, (local) or just . (Period) or
127.0.0.1
Server name = (local)
3. Now select Authentication. The options available here, depends on how you have installed SQL
Server. During installation, if you have chosen mixed mode authentication, you will have both Windows
Authentication and SQL Server Authentication. Otherwise, you will just be able to connect using
windows authentication.
4. If you have chosen Windows Authentication, you don’t have to enter user name and password,
otherwise enter the user name and password and click connect.
You should now be connected to SQL Server. Now, click on New Query, on the top left hand corner of
SSMS. This should open a new query editor window, where we can type SQL queries and execute.
SSMS is a client tool and not the Server by itself. Usually database server (SQL Server), will be on a
dedicated machine, and developers connect to the server using SSMS from their respective local
(development) computers.
Developer Machines 1,2,3 and 4 connects to the database server using SSMS.
2. Creating, altering and dropping a
database
In this part we will learn creating, altering and dropping a database.
Whether, you create a database graphically using the designer or, using a
query, the following 2 files gets generated.
You cannot drop a database, if it is currently in use. You get an error stating - Cannot
drop database "NewDatabaseName" because it is currently in use. So, if other users
are connected, you need to put the database in single user mode and then drop the
database.
Alter Database DatabaseName Set SINGLE_USER With Rollback Immediate
With Rollback Immediate option, will rollback all incomplete transactions and closes
the connection to the database.
3. Creating and Working with tables
The aim of this article is to create tblPerson and tblGender tables and
establish primary key and foreign key constraints. In SQL Server, tables can be
created graphically using SQL Server Management Studio (SSMS) or using a
query.
To create tblPerson table, graphically, using SQL Server Management Studio
The following statement creates tblGender table, with ID and Gender columns. The
following statement creates tblGender table, with ID and Gender columns. ID column,
is the primary key column. The primary key is used to uniquely identify each row in a
table. Primary key does not allow nulls.
Create Table tblGender
(ID int Not Null Primary Key,
Gender nvarchar(50))
Foreign keys are used to enforce database integrity. In layman's terms, A foreign key in one table
points to a primary key in another table. The foreign key constraint prevents invalid data form
being inserted into the foreign key column. The values that you enter into the foreign key column,
has to be one of the values contained in the table it points to.
4. Default constraint in SQL server
The insert statement below does not provide a value for GenderId column, so the default of 1 will
be inserted for this record.
Insert into tblPerson(ID, Name, Email) values(5,'Sam','s@s.com')
On the other hand, the following insert statement will insert NULL, instead of using the default.
Insert into tblPerson(ID, Name, Email, GenderId) values (6,'Dan','d@d.com',NULL)
To drop a constraint
ALTER TABLE { TABLE_NAME }
DROP CONSTRAINT { CONSTRAINT_NAME }
5. Cascading referential integrity
constraint
Cascading referential integrity constraint allows to define the actions Microsoft SQL
Server should take when a user attempts to delete or update a key to which an
existing foreign keys points.
For example, consider the 2 tables shown below. If you delete row with ID =
1 from tblGender table, then row with ID = 3 from tblPerson table becomes an orphan
record. You will not be able to tell the Gender for this row. So, Cascading referential
integrity constraint can be used to define actions Microsoft SQL Server should take
when this happens. By default, we get an error and the DELETE or UPDATE statement
is rolled back.
However, you have the following options when setting up Cascading
referential integrity constraint
CHECK constraint is used to limit the range of the values, that can be entered
for a column.
Let's say, we have an integer AGE column, in a table. The AGE in general
cannot be less than ZERO and at the same time cannot be greater than 150.
But, since AGE is an integer column it can accept negative values and values
much greater than 150.
So, to limit the values, that can be added, we can use CHECK constraint. In
SQL Server, CHECK constraint can be created graphically, or using a query.
The following check constraint, limits the age between ZERO and 150.
If a column is marked as an identity column, then the values for this column
are automatically generated, when you insert a new row into the table. The
following, create table statement marks PersonId as an identity column with
seed = 1 and Identity Increment = 1. Seed and Increment values are optional.
If you don't specify the identity and seed they both default to 1.
Create Table tblPerson
(
PersonId int Identity(1,1) Primary Key,
Name nvarchar(20)
)
In the following 2 insert statements, we only supply values for Name column and not
for PersonId column.
Insert into tblPerson values ('Sam')
Insert into tblPerson values ('Sara')
If you select all the rows from tblPerson table, you will see that, 'Sam' and 'Sara' rows
have got 1 and 2 as PersonId.
Now, if I try to execute the following query, I get an error stating - An explicit value for
the identity column in table 'tblPerson' can only be specified when a column list is
used and IDENTITY_INSERT is ON.
Select SCOPE_IDENTITY()
Select @@IDENTITY
Select IDENT_CURRENT('tblPerson')
SCOPE_IDENTITY() returns the last identity value that is created in the same session (Connection)
and in the same scope (in the same Stored procedure, function, trigger). Let's say, I have 2 tables
tblPerson1 and tblPerson2, and I have a trigger on tblPerson1 table, which will insert a record
into tblPerson2 table. Now, when you insert a record into tblPerson1 table, SCOPE_IDENTITY()
returns the identity value that is generated in tblPerson1 table, where as @@IDENTITY returns,
the value that is generated in tblPerson2 table. So, @@IDENTITY returns the last identity
value that is created in the same session without any consideration to the scope.
IDENT_CURRENT('tblPerson') returns the last identity value created for a specific table across any
session and any scope.
In brief:
SCOPE_IDENTITY() - returns the last identity value that is created in the same session and in the
same scope.
@@IDENTITY - returns the last identity value that is created in the same session and across any
scope.
IDENT_CURRENT('TableName') - returns the last identity value that is created for a specific table
across any session and any scope.
9. Unique key constraint
1. A table can have only one primary key, but more than one unique key
2. Primary key does not allow nulls, where as unique key allows one null
To drop the constraint
1. Right click the constraint and delete.
Or
2. Using a query
If you want to select all the columns, you can also use *. For better
performance use the column list, instead of using *.
SELECT *
FROM Table_Name
To Select distinct rows use DISTINCT keyword
SELECT Column_List
FROM Table_Name
WHERE Filter_Condition
Example: Select Name, Email from tblPerson where City = 'London'
Note: Text values, should be present in single quotes, but not required for
numeric values.
Different operators that can be used in a where clause
http://csharp-video-tutorials.blogspot.com/p/free-sql-server-video-tutorials-
for.html