0% found this document useful (0 votes)
154 views

SQL Server Tutorial

This document provides instructions on connecting to SQL Server using SQL Server Management Studio (SSMS) and performing basic database and table operations such as creating, altering, dropping, and adding constraints. The key steps outlined are: 1. Connecting to SSMS by specifying the server type, name, and authentication method. 2. Creating, altering, and dropping databases either graphically or using queries. 3. Creating tables with columns, primary keys, and foreign key constraints between tables. 4. Adding default, cascading referential integrity, and check constraints to columns to enforce valid data values.

Uploaded by

Dhiren Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views

SQL Server Tutorial

This document provides instructions on connecting to SQL Server using SQL Server Management Studio (SSMS) and performing basic database and table operations such as creating, altering, dropping, and adding constraints. The key steps outlined are: 1. Connecting to SSMS by specifying the server type, name, and authentication method. 2. Creating, altering, and dropping databases either graphically or using queries. 3. Creating tables with columns, primary keys, and foreign key constraints between tables. 4. Adding default, cascading referential integrity, and check constraints to columns to enforce valid data values.

Uploaded by

Dhiren Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

SQL SERVER TUTORIAL

1. Connecting to SQL Server using SSMS

• Connecting to SQL Server using SSMS


• What is SQL Server Management Studio

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.

A SQL Server database can be created, altered and dropped

1. Graphically using SQL Server Management Studio (SSMS) or


2. Using a Query
To create the database graphically

1. Right Click on Databases folder in the Object explorer


2. Select New Database
3. In the New Database dialog box, enter the Database name and click OK.

To Create the database using a query


Create database (Database Name)

Whether, you create a database graphically using the designer or, using a
query, the following 2 files gets generated.

.MDF file - Data File (Contains actual data)


.LDF file - Transaction Log file (Used to recover the database)
To alter a database, once it's created
Alter database DatabaseName Modify Name = NewDatabaseName

Alternatively, you can also use system stored procedure


Execute sp_renameDB 'OldDatabaseName‘, 'NewDatabaseName'

To Delete or Drop a database


Drop Database DatabaseThatYouWantToDrop

Dropping a database, deletes the LDF and MDF files.

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

1. Right click on Tables folder in Object explorer window


2. Select New Table
3. Fill Column Name, Data Type and Allow Nulls, as shown below and save the
table as tblPerson.

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

In tblPerson table, GenderID is the foreign key referencing ID column


in tblGendertable. Foreign key references can be added graphically using SSMS or
using a query.
To graphically add a foreign key reference

1. Right click tblPerson table and select Design


2. In the table design window, right click on GenderId column and select Relationships
3. In the Foreign Key Relationships window, click Add button
4. Now expand, in Tables and Column Specification row, by clicking the, + sign
5. Click on the elipses button, that is present in Tables and Column Specification row
6. From the Primary Key Table, dropdownlist, select tblGender
7. Click on the row below, and select ID column
8. From the column on the right hand side, select GenderId
9. Click OK and then click close.
10. Finally save the table.

To add a foreign key reference using a query


Alter table tblPerson
add constraint tblPerson_GenderId_FK FOREIGN KEY (GenderId) references tblGender(ID)

The general formula is here


Alter table ForeignKeyTable add constraintForeignKeyTable_ForiegnKeyColumn_FK
FOREIGN KEY (ForiegnKeyColumn) references PrimaryKeyTable (PrimaryKeyColumn)

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

we will learn adding a Default Constraint. A column default can be specified


using Default constraint. The default constraint is used to insert a default
value into a column. The default value will be added to all new records, if no
other value is specified, including NULL.
Altering an existing column to add a default constraint:
ALTER TABLE { TABLE_NAME }
ADD CONSTRAINT { CONSTRAINT_NAME }
DEFAULT { DEFAULT_VALUE } FOR { EXISTING_COLUMN_NAME }

Adding a new column, with default value, to an existing table:


ALTER TABLE { TABLE_NAME }
ADD { COLUMN_NAME } { DATA_TYPE } { NULL | NOT NULL }
CONSTRAINT { CONSTRAINT_NAME } DEFAULT { DEFAULT_VALUE }

The following command will add a default constraint, DF_tblPerson_GenderId.


ALTER TABLE tblPerson
ADD CONSTRAINT DF_tblPerson_GenderId
DEFAULT 1 FOR GenderId

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

1. No Action: This is the default behavior. No Action specifies that if an


attempt is made to delete or update a row with a key referenced by foreign
keys in existing rows in other tables, an error is raised and the DELETE or
UPDATE is rolled back.

2. Cascade: Specifies that if an attempt is made to delete or update a row


with a key referenced by foreign keys in existing rows in other tables, all rows
containing those foreign keys are also deleted or updated.

3. Set NULL: Specifies that if an attempt is made to delete or update a row


with a key referenced by foreign keys in existing rows in other tables, all rows
containing those foreign keys are set to NULL.

4. Set Default: Specifies that if an attempt is made to delete or update a row


with a key referenced by foreign keys in existing rows in other tables, all rows
containing those foreign keys are set to default values.
6. Check constraint in SQL Server

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.

ALTER TABLE tblPerson


ADD CONSTRAINT CK_tblPerson_Age CHECK (Age > 0 AND Age < 150)

The general formula for adding check constraint in SQL Server:

ALTER TABLE { TABLE_NAME }


ADD CONSTRAINT { CONSTRAINT_NAME } CHECK ( BOOLEAN_EXPRESSION )

If the BOOLEAN_EXPRESSION returns true, then the CHECK constraint allows


the value, otherwise it doesn't. Since, AGE is a nullable column, it's possible
to pass null for this column, when inserting a row. When you pass NULL for
the AGE column, the boolean expression evaluates to UNKNOWN, and allows
the value.
To drop the CHECK constraint:

ALTER TABLE tblPerson


DROP CONSTRAINT CK_tblPerson_Age
7. Identity column in SQL Server

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.

Insert into tblPerson values (1,'Todd')


So if you mark a column as an Identity column, you don’t have to explicitly supply a
value for that column when you insert a new row. The value is automatically
calculated and provided by SQL server. So, to insert a row into tblPerson table, just
provide value for Name column.

Insert into tblPerson values ('Todd')


Delete the row, that you have just inserted and insert another row. You see that the
value for PersonId is 2. Now if you insert another row, PersonId is 3. A record with
PersonId = 1, does not exist, and I want to fill this gap. To do this, we should be able to
explicitly supply the value for identity column. To explicitly supply a value for identity
column

1. First turn on identity insert - SET Identity_Insert tblPerson ON


2. In the insert query specify the column list
Insert into tblPerson(PersonId, Name) values(2, 'John')
As long as the Identity_Insert is turned on for a table, you need to explicitly provide
the value for that column. If you don't provide the value, you get an error - Explicit
value must be specified for identity column in table 'tblPerson1' either when
IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR
REPLICATION identity column.
After, you have the gaps in the identity column filled, and if you wish SQL server to
calculate the value, turn off Identity_Insert.
SET Identity_Insert tblPerson OFF
If you have deleted all the rows in a table, and you want to reset the identity column
value, use DBCC CHECKIDENT command. This command will reset PersonId identity
column.
DBCC CHECKIDENT(tblPerson, RESEED, 0)
8. How to get the last generated identity
column value in SQL Server
From the previous session, we understood that identity column values are
auto generated. There are several ways in sql server, to retrieve the
last identity value that is generated. The most common way is to use
SCOPE_IDENTITY() built in function.

Apart, from using SCOPE_IDENTITY(), you also have @@IDENTITY and


IDENT_CURRENT('Table Name') function.
Example queries for getting the last generated identity value

Select SCOPE_IDENTITY()
Select @@IDENTITY
Select IDENT_CURRENT('tblPerson')

Let's now understand the difference between, these 3 approaches.

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

We use UNIQUE constraint to enforce uniqueness of a column i.e the column


shouldn't allow any duplicate values. We can add a Unique constraint thru the
designer or using a query.

To add a unique constraint using SQL server management studio designer:

1. Right-click on the table and select Design


2. Right-click on the column, and select Indexes/Keys...
3. Click Add
4. For Columns, select the column name you want to be unique.
5. For Type, choose Unique Key.
6. Click Close, Save the table.
To create the unique key using a query:

Alter Table Table_Name


Add Constraint Constraint_Name Unique(Column_Name)
Both primary key and unique key are used to enforce, the uniqueness of a column.
So, when do you choose one over the other?
A table can have, only one primary key. If you want to enforce uniqueness on 2 or
more columns, then we use unique key constraint.
What is the difference between Primary key constraint and Unique key constraint?
This question is asked very frequently in interviews.

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

Alter Table tblPerson


Drop Constraint UQ_tblPerson_Email
10. Select statement

Basic select statement syntax


SELECT Column_List
FROM Table_Name

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 DISTINCT Column_List


FROM Table_Name
Example: Select distinct city from tblPerson
Filtering rows with WHERE clause

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

You might also like