Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
50 views

Connecting To SQL Server Using SSMS

SSMS is a client tool used to connect to SQL Server and execute SQL queries. To connect using SSMS, select it from the Start menu programs. In the connection window, select Database Engine as the server type, specify the server name (such as local), and select Windows or SQL authentication depending on the installation. Once connected, a new query window opens to allow writing and running SQL statements against the database.

Uploaded by

Aravind
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Connecting To SQL Server Using SSMS

SSMS is a client tool used to connect to SQL Server and execute SQL queries. To connect using SSMS, select it from the Start menu programs. In the connection window, select Database Engine as the server type, specify the server name (such as local), and select Windows or SQL authentication depending on the installation. Once connected, a new query window opens to allow writing and running SQL statements against the database.

Uploaded by

Aravind
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Connecting to SQL Server using SSMS - Part 1

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 dont 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.
Creating, altering and dropping a database - Part 2
In Part 1 of SQL Server, we have seen, using SSMS to connect to SQL Server. 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 DatabaseName

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.
Note: System databases cannot be dropped.
Creating and Working with tables - Part 3
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 tblGender table.
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 constraint ForeignKeyTable_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.
Default constraint in sql server - Part 4
In Part 3 of this video series, we have seen how to create tables (tblPerson and tblGender) and
enforce primary and foreign key constraints. Please watch Part 3, before continuing with this
session.

In this video, 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 }
Cascading referential integrity constraint - Part 5
In Part 3 of this video series, we have seen how to create tables (tblPerson and tblGender) and
enforce primary and foreign key constraints. In Part 4, we have learnt adding a default
constraint. Please watch Parts 3 and 4, before continuing with this session.

In this video, we will learn about 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 behaviour. 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.
Check constraint in SQL Server - Part 6

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
Identity column in SQL Server - Part 7
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 dont 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)
How to get the last generated identity column value in SQL Server - Part
8
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('TableName') 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 idetentity 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.
Unique key constraint - Part 9
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
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
Select statement - Part 10
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


Group By - Part 11
In SQL Server we have got lot of aggregate functions. Examples
1. Count()
2. Sum()
3. avg()
4. Min()
5. Max()

Group by clause is used to group a selected set of rows into a set of summary rows by the
values of one or more columns or expressions. It is always used in conjunction with one or more
aggregate functions.

I want an sql query, which gives total salaries paid by City. The output should be as shown
below.

Query for retrieving total salaries by city:


We are applying SUM() aggregate function on Salary column, and grouping by city column. This
effectively adds, all salaries of employees with in the same city.
Select City, SUM(Salary) as TotalSalary
from tblEmployee
Group by City

Note: If you omit, the group by clause and try to execute the query, you get an error - Column
'tblEmployee.City' is invalid in the select list because it is not contained in either an aggregate
function or the GROUP BY clause.

Now, I want an sql query, which gives total salaries by City, by gender. The output should be as
shown below.

Query for retrieving total salaries by city and by gender: It's possible to group by multiple
columns. In this query, we are grouping first by city and then by gender.
Select City, Gender, SUM(Salary) as TotalSalary
from tblEmployee
group by City, Gender

Now, I want an sql query, which gives total salaries and total number of employees by City, and
by gender. The output should be as shown below.

Query for retrieving total salaries and total number of employees by City, and by gender:
The only difference here is that, we are using Count() aggregate function.
Select City, Gender, SUM(Salary) as TotalSalary,
COUNT(ID) as TotalEmployees
from tblEmployee
group by City, Gender

Filtering Groups:
WHERE clause is used to filter rows before aggregation, where as HAVING clause is used to
filter groups after aggregations. The following 2 queries produce the same result.

Filtering rows using WHERE clause, before aggrgations take place:


Select City, SUM(Salary) as TotalSalary
from tblEmployee
Where City = 'London'
group by City

Filtering groups using HAVING clause, after all aggrgations take place:
Select City, SUM(Salary) as TotalSalary
from tblEmployee
group by City
Having City = 'London'

From a performance standpoint, you cannot say that one method is less efficient than the other.
Sql server optimizer analyzes each statement and selects an efficient way of executing it. As a
best practice, use the syntax that clearly describes the desired result. Try to eliminate rows that
you wouldn't need, as early as possible.

It is also possible to combine WHERE and HAVING


Select City, SUM(Salary) as TotalSalary
from tblEmployee
Where Gender = 'Male'
group by City
Having City = 'London'

Difference between WHERE and HAVING clause:


1. WHERE clause can be used with - Select, Insert, and Update statements, where as HAVING
clause can only be used with the Select statement.
2. WHERE filters rows before aggregation (GROUPING), where as, HAVING filters groups, after
the aggregations are performed.

You might also like