You are on page 1of 10

Department of Computer Science &

Information Technology

Superior University
Gujranwala Campus

Group Members:

Faizan Khan (052)


Hamza Farooq (028)
AbdulQadir Butt (061)

Professor Name: Naveed Ahmad

Final Project Data ware House

© Department of Computer Science & Information Technology.


1
Computed Column

Introduction:

Computed columns are type of columns in which the values are derived based on
one or more other columns. Hence the data type on the computed column depends
on the result of the derived column values.

Computed columns is a feature which has been there in SQL Server since version
2000. But in my experience, I feel that it has been a feature which has been used
less compared to many other features available, and during discussions and
interviews, this is something which most developers slip or fail to answer.

First, we will consider a case where we need to store details on a table without
the usage of computed columns.

Consider we have a table which contains employee details. We have two columns
to store employee’s first and last names. But we also required to have a column
which we need to store their full name as well by concatenating the first and last
names. So the correct way is to have the third column which contains the full
name and the data needs to be inserted while the employee record is created and
it should be maintained in the case where the details are updated as well.
Otherwise, the data integrity will be lost. (One might debate that the full name
can be built from the business logic code using the first and last names. But for
illustration purposes, we would consider that we are maintaining it using SQL
Server.)
CREATE TABLE dbo.Employee (
Id INT
,FirstName VARCHAR(30)
,LastName VARCHAR(30)
,FullName VARCHAR(61)
)

Let’s insert few records to the table which we created now:

INSERT INTO dbo.Employee(Id, FirstName, LastName)


VALUES (1,’John’,’Doe'),(2,’Jane’,’Doe')

© Department of Computer Science & Information Technology.


2
PERSISTED, DETERMINISTIC or NON-DETERMINISTIC?

The values reflected on computed column can be either deterministic or persisted.


When the values are deterministic or non-deterministic, the value in the column
will not be saved on to the table physically. Instead, it is always calculated during
the query execution. Hence the value could differ based on the functions you use
in the formula. E.g.: If you use GETDATE() in the calculated column, it will
always return a different value during each execution.

CREATE TABLE dbo.Employee2(


Id INT
,FirstName VARCHAR(30)
,LastName VARCHAR(30)
,CreatedDate AS GETDATE()
)

INSERT INTO dbo.Employee2(Id, FirstName, LastName)


VALUES (1,'John','Doe')

And when queried, the calculated column returns different values as shown
below:

Note: The above mentioned can be achieved using a default constraint as well. I
have used that example on strictly illustration basis.
You can further read on deterministic and non-deterministic function on the
following Microsoft documentation:
Deterministic and Nondeterministic Functions
Computed column values can be persisted by adding the
keyword PERSISTED when the column is created using T-SQL or by the table
designer in SSMS. We will drop ‘FullName’ column and recreate the column.

ALTER TABLE dbo.Employee DROP COLUMN FullName;


ALTER TABLE dbo.Employee
ADD FullName AS CONCAT(FirstName,' ',LastName) PERSISTED;

© Department of Computer Science & Information Technology.


3
Note: If you try to drop the ‘CreatedDate’ column on Employee2 and try to create
it as PERSISTED, it will throw an error. Because computed columns can only be
persisted when it’s deterministic.

PERSISTED

Specifies that the Database Engine will physically store the computed values in
the table, and update the values when any other columns on which the computed
column depends are updated. Marking a computed column as PERSISTED
allows an index to be created on a computed column that is deterministic, but not
precise. For more information, see Indexes on Computed Columns. Any
computed columns used as partitioning columns of a partitioned table must be
explicitly marked PERSISTED. Computed column expression must be
deterministic when PERSISTED is specified.

Pretty much every computed column related performance problem I have


encountered over the years has had one (or more) of the following root causes:

 Implementation limitations
 Lack of cost model support in the query optimizer
 Computed column definition expansion before optimization starts
An example of an implementation limitation is not being able to create a filtered
index on a computed column (even when persisted). There is not much we can
do about this problem category; we have to use workarounds while we wait for
product improvements to arrive.
The lack of optimizer cost model support means SQL Server assigns a small
fixed cost to scalar computations, regardless of complexity or implementation.
As a consequence, the server often decides to recompute a stored computed
column value instead of reading the persisted or indexed value directly. This is
particularly painful when the computed expression is expensive, for example
when it involves calling a scalar user-defined function.
The problems around definition expansion are a bit more involved, and have
wide-ranging effects.

SQL Server normally expands computed columns into their underlying


definitions during the binding phase of query normalization. This is a very early
phase in the query compilation process, well before any plan selection decisions
are made (including trivial plan). In theory, performing early expansion might
enable optimizations that would otherwise be missed. For example, the optimizer
might be able to apply simplifications given other information in the query and
metadata (e.g. constraints). This is the same sort of reasoning that leads to view
definitions being expanded (unless a NOEXPAND hint is used).

© Department of Computer Science & Information Technology.


4
Calculate Age From Date OF Birth:

Dates and times can be the most frustrating data types to work with in SQL
Server. Learn everything you need to know about the way dates work with this
handy blog series and enjoy happier times!

1. Dates and Times in SQL


2. Date and Time Data Types in SQL Server
3. Dates and Times in Criteria
4. Formatting Dates and Times in SQL Server
5. Calculations with Dates in SQL Server
6. How to Calculate Age in SQL Server (this blog)

This blog is part of a larger tutorial on SQL Server, which you can
read here. Wise Owl also run SQL courses, as well as training
in SSRS, SSAS and SSIS.

How to Calculate Age in SQL Server


A common requirement in SQL Server databases is to calculate the age of
something in years. There are several techniques for doing this depending on
how accurate you want the final result to be. This blog considers three
techniques, saving the most complex, but most accurate, for last.
Using DATEDIFF to Calculate Age
Apparently, the quickest and easiest way to calculate the age of someone or
something in years is to simply use the DATEDIFF function.

© Department of Computer Science & Information Technology.


5
At first glance the DATEDIFF function seems to successfully calculate ages
quickly and easily, but closer inspection reveals that it's not quite as accurate as
we'd like (and certainly not as accurate as Keanu Reeves would like!). In fact, in
the above list, only the last record is calculated correctly - the other three are being
reported as one year older than they actually are.
The problem is that when the DATEDIFF function is told to look at years it
ignores every other part of the dates involved, essentially performing the
calculation shown below:

This is what DATEDIFF is really doing when you ask it to give you the difference
between two dates in years.
Clearly, using DATEDIFF to calculate the difference between dates in years isn't
accurate enough for something as potentially sensitive as age. In that case we
need a different approach.
Calculating Age in Days and Dividing the Result
A more accurate, but not perfect, way to calculate age in years is to first work out
the difference in days between two dates and then divide the result by the number
of days in a year. The method is shown in the example below:

© Department of Computer Science & Information Technology.


6
The last step in this type of calculation is to remove the decimal places to give
the age in whole years. To do this we can convert the answer to the INT data
type.

Using DATEDIFF and Correcting the Result

This is the most accurate way to calculate an age in years, but it's also the most
complex expression to write. The starting point is to use the first calculation we
demonstrated at the top of the page to calculate the difference in years between
two dates:

Error Handling In Sql Server:

© Department of Computer Science & Information Technology.


7
Versions of SQL Server previous to SQL Server 2005 required error handling
code after every Transact-SQL statement that might produce an error. (You can
handle errors using the @@error global variable.) Starting with SQL Server 2005,
you can capture and handle exceptions using two statements, TRY and CATCH.
This section first explains what “exception” means and then discusses how these
two statements work.

An exception is a problem (usually an error) that prevents the continuation of a


program. With such a problem, you cannot continue processing because there is
not enough information needed to handle the problem. For this reason, the
existing problem will be relegated to another part of the program, which will
handle the exception.

The role of the TRY statement is to capture the exception. (Because this process
usually comprises several statements, the term “TRY block” typically is used
instead of “TRY statement.”) If an exception occurs within the TRY block, the
part of the system called the exception handler delivers the exception to the other
part of the program, which will handle the exception. This program part is
denoted by the keyword CATCH and is therefore called the CATCH block.

Exception handling using the TRY and CATCH statements is the common way
that modern programming languages like C# and Java treat errors.

Exception handling with the TRY and CATCH blocks gives a programmer a lot
of benefits, such as:

 Exceptions provide a clean way to check for errors without cluttering code
 Exceptions provide a mechanism to signal errors directly rather than using
some side effects
 Exceptions can be seen by the programmer and checked during the
compilation process

SQL Server 2012 introduces the third statement in relation to handling errors:
THROW. This statement allows you to throw an exception caught in the
exception handling block. Simply stated, the THROW statement is another return
mechanism, which behaves similarly to the already described RAISEERROR
statement.

Example 1 shows how exception handling with the TRY/CATCH/THROW


works. It shows how you can use exception handling to insert all statements in a
batch or to roll back the entire statement group if an error occurs. The example is
based on the referential integrity between the department and employee tables.

© Department of Computer Science & Information Technology.


8
For this reason, you have to create both tables using the PRIMARY KEY and
FOREIGN KEY constraints.

After the execution of the batch in Example 1, all three statements in the batch
won’t be executed at all, and the output of this example is:

The execution of Example 1 works as follows. The first INSERT statement is


executed successfully. Then, the second statement causes the referential integrity
error. Because all three statements are written inside the TRY block, the exception
is “thrown” and the exception handler starts the CATCH block. CATCH rolls
back all statements and prints the corresponding message. After that the THROW
statement returns the execution of the batch to the caller. For this reason, the
content of the employee table won’t change.

The statements BEGIN TRANSACTION, COMMIT TRANSACTION, and


ROLLBACK are Transact-SQL statements concerning transactions. These
statements start, commit, and roll back transactions, respectively. See Chapter
13 for the discussion of these statements and transactions generally.

Example 2 shows the batch that supports server-side paging.

© Department of Computer Science & Information Technology.


9
The batch in Example 2 uses the AdventureWorks database and
its Employee table to show how generic server-side paging can be implemented.
The @Pagesize variable is used with the FETCH NEXT statement to specify the
number of rows per page (20, in this case). The other variable, @CurrentPage,
specifies which particular page should be displayed. In this example, the content
of the third page will be displayed.

Error handling in SQL Server give us control over Transact-SQL code. For
example when things go wrong we get a chance to do something about it and
possibly make it right again. SQL Server error handling can be as simple as just
logging that something happened or it could be us trying to fix an error. It can
even be translating the error in SQL language because we all know how technical
SQL Server error messages could get making no sense and hard to understand.
Luckily we have a chance to translate those messages into something more
meaningful to pass on to the users, developers, etc.

In this article, we’ll take a closer look at the TRY…CATCH statement: the
syntax, how it looks, how it works and what can be done when an error occurs.
Furthermore, the method will be explained in a SQL Server case using a group of
T-SQL statements/blocks which is basically SQL Server way of handling errors.
This is a very simple, yet structured way of doing it and once you get the hang of
it, can be quite helpful in many cases.

On top of that, there is a RAISERROR function that can be used to generate our
own custom error messages which is a great way to translate confusing error
messages into something a little bit more meaningful that people would
understand.

© Department of Computer Science & Information Technology.


10

You might also like