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

DatabaeLab 2 6

The document discusses creating and altering tables in SQL Server. It explains different data constraints that can be applied on tables like primary key, foreign key, not null, unique, check, default and identity. Specific examples are given for creating tables with these constraints using SQL commands and SQL Server Management Studio. Instructions are provided about how to set primary keys, foreign keys and other constraints using the designer tools in SQL Server.

Uploaded by

abdul.rafae221
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

DatabaeLab 2 6

The document discusses creating and altering tables in SQL Server. It explains different data constraints that can be applied on tables like primary key, foreign key, not null, unique, check, default and identity. Specific examples are given for creating tables with these constraints using SQL commands and SQL Server Management Studio. Instructions are provided about how to set primary keys, foreign keys and other constraints using the designer tools in SQL Server.

Uploaded by

abdul.rafae221
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Air University, Islamabad

Department of Computer Science


Database Management System
Lab 2 Tasks
Data Definition Language (DDL)
In this lab, you will learn how to create a new database and tables in SQL
Server using commands or SQL Server Management Studio.
DATABASE LAB MANUAL

Creating a new database using the CREATE


DATABASE statement

Once the statement executes successfully, you can view the newly created database in
the Object Explorer. If the new database does not appear, you can click
the Refresh button or press F5 keyboard to update the object list.

To show all databases list in the SQL Server

Or you can execute the stored procedure sp_databases

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Creating a new database using SQL Server


Management Studio
First, right-click the Database and choose New Database… menu item.

Second, enter the name of the database e.g., SampleDb and click
the OK button.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Third, view the newly created database from the Object Explorer:

In this tutorial, you have learned how to create a new database using SQL
Server CREATE DATABASE statement and SQL Server Management Studio.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

SQL Server DROP DATABASE

Using the SQL Server DROP DATABASE statement to delete a


database
To remove an existing database from a SQL Server instance, you use
the DROP DATABASE statement.

The DROP DATABASE statement allows you to delete one or more databases

The IF EXISTS option is available from SQL Server 2016 (13.x). It allows you to
conditionally delete a database only if the database already exists. If you attempt to
delete a nonexisting database without specifying the IF EXISTS option, SQL Server will
issue an error.

Before deleting a database, you must ensure the following important


points:

 First, the DROP DATABASE statement deletes the database and also the
physical disk files used by the database. Therefore, you should have a backup of
the database in case you want to restore it in the future.
 Second, you cannot drop the database that is currently being used.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Using the SQL Server Management Studio to drop a


database
You can follow these steps to delete the SampleDb database:
First, right-click on the database name that you want to delete and choose Delete menu
item:

Second, uncheck the Delete backup and restore history information for
databases check box, check the Close existing connections check box, and click
the OK button to delete the database.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Third, verify that the database has been dropped from the Object Explorer.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

SQL Server CREATE TABLE


Introduction to the SQL Server CREATE TABLE statement
To create a new table, you use the CREATE TABLE statement as follows:

The visits table contains five columns:

 The visit_id column is the primary key column of the table.


The IDENTITY(1,1) instructs SQL Server to automatically generate integer
numbers for the column starting from one and increasing by one for each new row.
 The first_name and last_name columns are character string columns
with VARCHAR type. These columns can store up to 50 characters.
 The visited_at is a DATETIME column that records the date and time at which the
customer visits the store.
 The phone column is a varying character string column which accepts NULL.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Task
1. The following illustrates the BikeStores database diagram:
2. Create database BikeStores
3. Create Tables as given below in diagram.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Air University, Islamabad


Department of Computer Science
Database Management System

Lab 3 Tasks
Data Definition Language (DDL)
In this lab, you will learn how to create and alter a new tables and how to
apply constraints on the table in SQL Server using commands or SQL Server
Management Studio.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

SQL Constraints
Constraints are used to limit the type of data that can go into a table.

Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the
table is created (with the ALTER TABLE statement).

Here are the most important constraints:

 PRIMARY KEY
 NOT NULL
 UNIQUE
 FOREIGN KEY
 CHECK
 DEFAULT
 IDENTITY

1. PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values. It is normal to just use running numbers, like 1, 2, 3, 4, 5, … as
values in Primary Key column.

It is a good idea to let the system handle this for you by specifying that the Primary Key should be set to
identity (1, 1). IDENTITY (1, 1) means the first value will be 1 and then it will increment by 1. Each table
should have a primary key, and each table can have only ONE primary key.

SCHOOL

Setting Primary Keys in the Designer Tools:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

If you use the Designer tools in SQL Server, you can easily set the primary Key in a table just by right-click
and select “Set primary Key”.

2. FOREIGN KEY
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

CLASS:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

The FOREIGN KEY constraint also prevents that invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.

Setting Foreign Keys in the Designer Tools:

If you want to use the designer, right-click on the column that you want to be the Foreign Key and
select “Relationships…”

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

The following window pops up (Foreign Key Relationships):

Click on the “Add” button and then click on the small “…” button. Then the following window pops up
(Tables and Columns):

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Here you specify the primary Key Column in the Primary Key table and the Foreign Key Column in the
Foreign Key table.

3. NOT NULL / Required Columns


The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint
enforces a field to always contain a value. This means that you cannot insert a new record, or update a
record without adding a value to this field.

4. UNIQUE
The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY
KEY constraints both provide a guarantee for uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it

Note! You can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per
table.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Setting UNIQUE in the Designer Tools:

If you want to use the designer, right-click on the column that you want to be UNIQUE and select
“Indexes/Keys…”

Then click “Add” and then set the “Is Unique” property to “Yes”:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

5. CHECK
The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a single column it allows only certain values for this column.

If you define a CHECK constraint on a table it can limit the values in certain columns based on values in
other columns in the row.

In this case, when we try to insert a Customer Number less than zero we will get an error message.

Setting CHECK constraints in the Designer Tools

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

If you want to use the designer, right-click on the column where you want to set the constraints and
select “Check Constraints…”

Then click “Add” and then click “…” in order to open the Expression window:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

In the Expression window you can type in the expression you want to use:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

6. DEFAULT
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.

Setting DEFAULT values in the Designer Tools

Select the column and go into the “Column Properties”

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

7. AUTO INCREMENT or IDENTITY


Very often we would like the value of the primary key field to be created automatically every time a new
record is inserted.

Setting identity (1,1) in the Designer Tools:

We can use the designer tools to specify that a Primary Key should be an identity column that is
automatically generated by the system when we insert data in to the table.

Click on the column in the designer and go into the Column Properties window

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

ALTER TABLE
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

1. To add a column in a table, use the following syntax:

2. To delete a column in a table, use the following syntax

(Notice that some database systems don't allow deleting a column)

3. To change the data type of a column in a table, use the following syntax:

If we use CREATE TABLE and the table already exists in the table we will get an error message,

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

So if we combine CREATE TABLE and ALTER TABLE we can create robust database scripts that gives no
errors, as the example shown below:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

INSERT INTO
The INSERT INTO statement is used to insert a new row in a table.

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their values:

Insert Data Only in Specified Columns:

It is also possible to only add data in specific columns.

Note! You need at least to include all columns that cannot be NULL.

Insert Data in the Designer Tools:

When you have created the tables, you can easily insert data into them using the designer tools. Right-
click on the specific table and select “Edit Top 200 Rows”:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

UPDATE
The UPDATE statement is used to update existing records in a table.

The syntax is as follows:

Note! Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

DELETE
The DELETE statement is used to delete rows in a table.

Note! Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!

Delete All Rows:


It is possible to delete all rows in a table without deleting the table.

This means that the table structure, attributes, and indexes will be intact (not damaged or impaired in any way)

Note! Make sure to do this only when you really mean it! You cannot UNDO this statement!

Delete Data in the Designer Tools:

You delete data in the designer by right-click on the row and select “Delete”

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

SELECT
The SELECT statement is probably the most used SQL command. The SELECT statement is used for
retrieving rows from the database and enables the selection of one or many rows or columns from one
or many tables in the database.

We will use the CUSTOMER table as an example.

To be continued…….

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Air University, Islamabad


Department of Computer Science

Database Management System

Lab 4 Tasks
In this lab, you will learn Select statement with different operators on the table
in SQL Server using commands or SQL Server Management Studio.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

SELECT
The SELECT statement is probably the most used SQL command. The SELECT statement is used for
retrieving rows from the database and enables the selection of one or many rows or columns from one
or many tables in the database.

The full syntax of the SELECT statement is complex, but the main clauses can be summarized.

Example:

This simple example gets all the data in the table CUSTOMER. The symbol “*” is used when you want
to get all the columns in the table.

If you only want a few columns, you may specify the names of the columns you want to retrieve,
example:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Note! SQL is not case sensitive. SELECT is the same as select

Select Data in the Designer Tools:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

The following will appear:

The ORDER BY Keyword


If you want the data to appear in a specific order you need to use the “order by” keyword.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

If you use the “order by” keyword, the default order is ascending (“asc”). If you want the order to be
opposite, i.e., descending, then you need to use the “desc” keyword.

SELECT DISTINCT
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table.

The DISTINCT keyword can be used to return only distinct (different) values.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

The WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified criterion.

Note! SQL uses single quotes around text values, as shown in the example above.

Operators
With the WHERE clause, the following operators can be used:

Examples:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.

Note! The "%" sign can be used to define wildcards (missing letters in the pattern) both before and
after the pattern.

You may also combine with the NOT keyword, example:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or
dates.

Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.

With SQL, the following wildcards can be used:

Note! SQL wildcards must be used with the SQL LIKE operator.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

AND & OR Operators


The AND operator displays a record if both the first condition and the second condition is true.

The OR operator displays a record if either the first condition or the second condition is true.

Combining AND & OR:


You can also combine AND and OR (use parenthesis to form complex expressions).

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

ELECT TOP Clause


The TOP clause is used to specify the number of records to return.

The TOP clause can be very useful on large tables with thousands of records. Returning a large number
of records can impact on performance.

You can also specify in percent:

This is very useful for large tables with thousands of records

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Alias
You can give a table or a column another name by using an alias. This can be a good thing to do if you
have very long or complex table names or column names.

An alias name could be anything, but usually it is short

Joins
SQL joins are used to query data from two or more tables, based on a relationship between certain
columns in these tables.

To be continued…….

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Air University, Islamabad


Department of Computer Science

Database Management System

Lab 5 Tasks
In this Lab, you will learn about various kinds of SQL Server joins that allow you to
combine data from two tables.

In a relational database, data is distributed in multiple logical tables. To get a complete


meaningful set of data, you need to query data from these tables by using joins. SQL
Server supports many kinds of joins including inner join, left join, right join, full outer join,
self join and cross join. Each join type specifies how SQL Server uses data from one table
to select rows in another table.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Joins
SQL joins are used to query data from two or more tables, based on a relationship between
certain columns in these tables.

Different SQL JOINs


Before we continue with examples, we will list the types of JOIN you can use, and the differences
between them.
 JOIN: Return rows when there is at least one match in both tables
 LEFT JOIN: Return all rows from the left table, even if there are no matches in the right
table
 RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left
table
 FULL JOIN: Return rows when there is a match in one of the tables

Select all records from Select all records from Select all records from Select all records from
Table A and Table B, Table A, along with Table B, along with Table A and Table B,
where the join condition records from Table B for records from Table A for regardless of whether the
is met. which the join condition is which the join condition is join condition is met or
met (if at all). met (if at all). not.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Inner Join

Left Join

Note that since there were no matching records for Alina Majid in our orders table,
the order_amount is NULL, which simply means there is no data for these fields.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Right Join
Right join is a mirror version of the left join and allows to get a list of all orders, appended with customer
information.

Note that since there were no matching customer records for orders amount in 100.2 and 102,
the CustomerId ,FirstName and LastName fields are NULL in the resulting set.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Full Join
Finally, for a list of all records from both tables, we can use a full join.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Task
Write SQL queries to find:
1. FistName and LastName of Customers who have booked at least one table

2. FistName and LastName of Customers who have booked TableNumber=2

3. Number of times a table has been booked along with it's Details

4. Number of times a table has been booked by a Customer belonging to a particular

Profession

5. FirstName and LastName of Customer(s) who booked the maximum tables

6. All the information about Customers along with their BOOKING details

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Air University, Islamabad


Department of Computer Science

Database Management System

Lab 6 Tasks
In this Lab, you will learn SQL Server Scripting

SQL Scripts
A SQL script is a collection of SQL statements that you can execute in one operation. You can use
any kind of SQL commands, such as insert, select, delete, update, etc. In addition you can define
and use variables, and you may also use program flow like If-Else, etc. You may also add
comments to make the script easier to read and understand.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Using Comments
Using comments in you SQL script is important to make the script easier to read and understand.
In SQL we can use 2 different kinds of comments:
 Single-line comment
 Multiple-line comment

Single-line comment

We can comment one line at the time using “--” before the text you want to comment out.

Syntax:

Multiple-line comment
We can comment several line using “/*” in the start of the comment and “*/” in the end
of the comment.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Variables
MS SQL has two types of variables:

1. Local variable
2. Global variable.

However, the user can only create a local variable.

Local variable:
 A user declares the local variable.
 By default, a local variable starts with @.
 Every local variable scope has the restriction to the current batch or
procedure within any given session.

Global variable:
 The system maintains the global variable. A user cannot declare them.
 The global variable starts with @@
 It stores session related information.

The ability to using variables in SQL is a powerful feature. You need to use the keyword
DECLARE when you want to define the variables. Local variables must have the symbol

“@” as a prefix. You also need to specify a data type for your variable (int, varchar(x), etc.).
declare @local_variable data_type
If you have more than one variable you want to declare:

declare
@myvariable1 data_type,
@myvariable2 data_type,

........
When you want to assign values to the variable, you must use either a SET or a SELECT
statement.
Asim Ali Fayyaz (Research Associate)
[email protected]
DATABASE LAB MANUAL

If you want to see the value for a variable, you can e.g., use the PRINT command like this:

Assigning variables with a value from a SELECT statement is very useful.


We use the CUSTOMER table as an example:

You can assign a value to the variable from a select statement like this:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

You can also use a variable in the WHERE clause LIKE, e.g., this.

Assigning a value to a variable with a Scalar Subquery using SET


Note:

 Enclose the query in parenthesis.


 The query should be a scalar query. A scalar query is a query with results as just one row
and one column. Otherwise, the query will throw an error.
 If the query returns zero rows, then the variable is set to EMPTY, i.e., NULL.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Global Variables
Global variable names begin with a @@ prefix. You do not need to declare them, since the server
constantly maintains them. They are system-defined functions and you cannot declare them.

1. @@CONNECTIONS
2. @@MAX_CONNECTIONS
3. @@CPU_BUSY
4. @@ERROR
5. @@IDENTITY
6. @@IDLE
7. @@IO_BUSY
8. @@LANGID
9. @@LANGUAGE
10. @@MAXCHARLEN
11. @@PACK_RECEIVED
12. @@PACK_SENT
13. @@PACKET_ERRORS
14. @@ROWCOUNT
15. @@SERVERNAME
16. @@SPID
17. @@TEXTSIZE
18. @@TIMETICKS
19. @@TOTAL_ERRORS
20. @@TOTAL_READ / @@TOTAL_WRITE
21. @@TRANCOUNT
22. @@VERSION

Global variable names begin with a @@ prefix. You do not need to declare them, since the server constantly
maintains them. They are system-defined functions and you cannot declare them.

@@CONNECTIONS

The number of logins or attempted logins since SQL Server was last started.

Return type: int

@@MAX_CONNECTIONS

The maximum number of simultaneous connections that can be made with SQL Server in this
computer environment. The user can configure SQL Server for any number of connections less than
or equal to the value of @@max_connections with sp_configure ''number of user
connections''.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Return type: int

@@CPU_BUSY

The amount of time, in ticks, that the CPU has spent doing SQL Server work since the last time SQL
Server was started.

Return type: int

@@ERROR

Commonly used to check the error status (succeeded or failed) of the most recently executed
statement. It contains 0 if the previous transaction succeeded; otherwise, it contains the last error
number generated by the system. A statement such as:

Return type: int

IF @@ERROR <> 0
PRINT 'Your error message';
IF @@ERROR != 0 return causes an exit if an error occurs.
Every Transact-SQL statement resets @@error, including print statements or if tests, so the
status check must immediately follow the statement whose success is in question.

@@IDENTITY

The last value inserted into an IDENTITY column by an insert or select into
statement. @@identity is reset each time a row is inserted into a table. If a statement inserts
multiple rows, @@identity reflects the IDENTITY value for the last row inserted. If the affected
table does not contain an IDENTITY column, @@identity is set to 0.

The value of @@identity is not affected by the failure of an insert or select into statement,
or the rollback of the transaction that contained it. @@identity retains the last value inserted into
an IDENTITY column, even if the statement that inserted it fails to commit.

Return type: numeric(38,0)

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Example

@@IDLE

The amount of time, in ticks, that SQL Server has been idle since it was last started.

Return type: int

Example
SELECT @@IDLE * CAST(@@TIMETICKS AS float) AS 'Idle microseconds',
GETDATE() AS 'as of'

Output
Hide Copy Code

Idle microseconds as of
---------------------- -----------------------
11340000000 2009-08-19 22:07:19.903

@@IO_BUSY

The amount of time, in ticks, that SQL Server has spent doing input and output operations since it
was last started.

Return type: int

Example
SELECT @@IO_BUSY*@@TIMETICKS AS 'IO microseconds',
GETDATE() AS 'as of'

Output
IO microseconds as of
--------------- -----------------------
5906250 2009-08-19 22:09:44.013

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

@@LANGID

The local language id of the language currently in use (specified in syslanguages.langid).

Return type: smallint

Example
SET LANGUAGE 'Italian'
SELECT @@LANGID AS 'Language ID'
SET LANGUAGE 'us_english'
SELECT @@LANGID AS 'Language ID'

Output
@@LANGUAGE

The name of the language currently in use (specified in syslanguages.name).

Return type: nvarchar

Example
SELECT @@LANGUAGE AS 'Language Name';

@@MAXCHARLEN

The maximum length, in bytes, of a character in SQL Server's default character set.

Return type: tinyint

Example
SELECT @@MAX_PRECISION AS 'Max Precision'

Output
-------------
38

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

@@PACK_RECEIVED

The number of input packets read by SQL Server since it was last started.

Return type: int

Example
SELECT @@PACK_RECEIVED AS 'Packets Received'

Output
Packets Received
----------------
8998

@@PACK_SENT

The number of output packets written by SQL Server since it was last started.

Return type: int

Example
SELECT @@PACK_SENT AS 'Pack Sent'

Output
Pack Sent
-----------
9413

@@PACKET_ERRORS

The number of errors that have occurred while SQL Server was sending and receiving packets.

Return type: int

Example
SELECT @@PACKET_ERRORS AS 'Packet Errors'

Output
Packet Errors
-------------
0

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

@@ROWCOUNT

The number of rows affected by the last command. @@rowcount is set to 0 by any command
which does not return rows, such as an if statement. With cursors, @@rowcount represents the
cumulative number of rows returned from the cursor result set to the client, up to the last fetch
request.

Return type: int

Example
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';

Output
'Warning: No rows were updated'

@@SERVERNAME

The name of the local SQL Server. You must define a server name with sp_addserver, and then
restart SQL Server.

Return type: varchar

Example
SELECT @@SERVERNAME AS 'Server Name'

Output
MY_SERVER_WINDOWS_2003

@@SPID

The server process ID number of the current process.

Return type: smallint

Example
SELECT @@SPID AS 'ID', SYSTEM_USER AS 'Login Name', USER AS 'User Name'

Output
ID Login Name User Name
------ ----------------------------------------------------
55 MY_SERVER_WINDOWS_2003\Administrator dbo

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

@@TEXTSIZE

The current value of the set textsize option, which specifies the maximum length, in bytes, of text or
image data to be returned with a select statement. Defaults to 32K.

Return type: smallint

Example
SET TEXTSIZE 2048
SELECT @@TEXTSIZE AS 'Text Size'

Output
Text Size
-----------
2048

@@TIMETICKS

The number of microseconds per tick. The amount of time per tick is machine dependent.

Return type: int

Example
SELECT @@TIMETICKS AS 'Time Ticks';

Output
Time Ticks
-----------
31250

@@TOTAL_ERRORS

The number of errors that have occurred while SQL Server was reading or writing.

Return type: int

Example
SELECT @@TOTAL_ERRORS AS 'Errors', GETDATE() AS 'As of'

Output
Errors As of
----------- -----------------------
0 2009-08-19 22:47:51.937

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

@@TOTAL_READ / @@TOTAL_WRITE

The number of disk reads by SQL Server since it was last started.

Return type: int

Example
SELECT @@TOTAL_READ AS 'Reads', @@TOTAL_WRITE AS 'Writes', GETDATE() AS 'As of'

Output
Reads Writes As of
----------- ----------- -----------------------
861 91 2009-08-19 23:36:26.763

@@TRANCOUNT

The nesting level of transactions. Each begin transaction in a batch increments the transaction count.
When you query @@trancount in chained transaction mode, its value is never zero since the query
automatically initiates a transaction.

Return type: int

@@VERSION

The date of the current version of SQL Server.

Return type: nvarchar

Example
SELECT @@VERSION AS 'SQL Server Version'

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Flow Control
As with other programming languages you can use different kind of flow control, such as IFELSE,
WHILE, etc, which is very useful.

IF – ELSE

BEGIN…END
If more than one line of code is to be executed within an IF sentence you need to use

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

WHILE
We can also use WHILE, which is known from other programming languages.
Example:
We are using the CUSTOMER table:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

As you can see the code inside the WHILE loop is executed as long as “AreaCode” for
CustomerId=1 is less than 54. For each iteration is the “AreaCode” for that customer
incremented with 1.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

CURSOR
In advances scripts, CURSORs may be very useful. A CURSOR works like an advanced WHILE
loop which we use to iterate through the records in one or more tables.

CURSORS are used mainly in stored procedures, triggers, and SQL scripts.

Example:
We use the CUSTOMER table as an example:

We will create a CURSOR that iterate through all the records in the CUSTOMER table and check
if the Phone number consists of 11 digits, if not the script will replace the invalid Phone number
with the text “Phone number is not valid”.

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

The CUSTOMER table becomes:

Asim Ali Fayyaz (Research Associate)


[email protected]
DATABASE LAB MANUAL

Creating and using a CURSOR includes these steps:

 Declare SQL variables to contain the data returned by the cursor. Declare one variable
for each result set column.
 Associate a SQL cursor with a SELECT statement using the DECLARE CURSOR statement.
The DECLARE CURSOR statement also defines the characteristics of the cursor, such as
the cursor name and whether the cursor is read-only or forward-only.
 Use the OPEN statement to execute the SELECT statement and populate the cursor.
 Use the FETCH INTO statement to fetch individual rows and have the data for each
column moved into a specified variable. Other SQL statements can then reference those
variables to access the fetched data values.
 When you are finished with the cursor, use the CLOSE statement. Closing a cursor frees
some resources, such as the cursor's result set and its locks on the current row.
 The DEALLOCATE statement completely frees all resources allocated to the cursor,
including the cursor name.

Asim Ali Fayyaz (Research Associate)


[email protected]

You might also like