Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Q1:

Ans 1 : TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released
back to the server. 
DELETE is a DML command and can be rolled back. 
 
Both commands accomplish identical tasks (removing all data from a table), but TRUNCATE is much
faster.

Ans 2 :

The DELETE command is used to remove rows from a table. A WHERE clause can be used to
only remove some rows. If no WHERE condition is specified, all rows will be removed. After
performing a DELETE operation you need to
COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.

TRUNCATE removes all rows from a table. The operation cannot be rolled back. As such,
TRUCATE is faster and doesn't use as much undo space as a DELETE.

The DROP command removes a table from the database. All the tables' rows,
indexes and privileges will also be removed. The operation cannot be rolled back.

DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore
DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations
cannot be rolled back.

From Oracle 10g a table can be "undropped". Example:

SQL> FLASHBACK TABLE emp TO BEFORE DROP;

Flashback complete.

In case of TRUNCATE ,Trigger doesn't get fired.But in DML commands like DELETE .Trigger get fired.
An Introduction to Clustered and Non-
Clustered Index Data Structures
By : G. Vijayakumar
Dec 15, 2004

When I first started using SQL Server as a novice, I was initially confused as to the differences
between clustered and non-clustered indexes. As a developer, and new DBA, I took it upon
myself to learn everything I could about these index types, and when they should be used. This
article is a result of my learning and experience, and explains the differences between clustered
and non-clustered index data structures for the DBA or developer new to SQL Server. If you are
new to SQL Server, I hope you find this article useful.

As you read this article, if you choose, you can cut and paste the code I have provided in order to
more fully understand and appreciate the differences between clustered and non-clustered
indexes.

Part I: Non-Clustered Index

Creating a Table

To better explain SQL Server non-clustered indexes; let’s start by creating a new table and
populating it with some sample data using the following scripts. I assume you have a database
you can use for this. If not, you will want to create one for these examples.

Create Table DummyTable1


(
EmpId Int,
EmpName Varchar(8000)
)

When you first create a new table, there is no index created by default. In technical terms, a table
without an index is called a “heap”. We can confirm the fact that this new table doesn’t have an
index by taking a look at the sysindexes system table, which contains one for this table with an
of indid = 0. The sysindexes table, which exists in every database, tracks table and index
information. “Indid” refers to Index ID, and is used to identify indexes. An indid of 0 means that
a table does not have an index, and is stored by SQL Server as a heap.

Now let’s add a few records in this table using this script:
Insert Into DummyTable1 Values (4, Replicate ('d',2000))
GO

Insert Into DummyTable1 Values (6, Replicate ('f',2000))


GO

Insert Into DummyTable1 Values (1, Replicate ('a',2000))


GO

Insert Into DummyTable1 Values (3, Replicate ('c',2000))


GO

Now, let’s view the contests of the table by executing the following command in Query Analyzer
for our new table.

Select EmpID From DummyTable1


GO

Empid
4
6
1
3

As you would expect, the data we inserted earlier has been displayed. Note that the order of the
results is in the same order that I inserted them in, which is in no order at all.

Now, let’s execute the following commands to display the actual page information for the table
we created and is now stored in SQL Server.

dbcc ind(dbid, tabid, -1) – This is an undocumented command.

DBCC TRACEON (3604)


GO

Declare @DBID Int, @TableID Int


Select @DBID = db_id(), @TableID = object_id('DummyTable1')

DBCC ind(@DBID, @TableID, -1)


GO

This script will display many columns, but we are only interested in three of them, as shown
below.

PagePID IndexID PageType


26408 0 10
26255 0 1
26409 0 1

Here’s what the information displayed means:

PagePID is the physical page numbers used to store the table. In this case, three pages are
currently used to store the data.

IndexID is the type of index,

Where:

0 – Datapage

1 – Clustered Index

2 – Greater and equal to 2 is an Index page (Non-Clustered Index and ordinary index),

PageType tells you what kind of data is stored in each database,

Where:

10 – IAM (Index Allocation MAP)

1 – Datapage

2 – Index page

Now, let us execute DBCC PAGE command. This is an undocumented command.

DBCC page(dbid, fileno, pageno, option)

Where:

dbid = database id.

Fileno = fileno of the page.  Usually it will be 1, unless we use more than one file for a database.

Pageno = we can take the output of the dbcc ind page no.

Option = it can be 0, 1, 2, 3. I use 3 to get a display of the data.  You can try yourself for the
other options.

Run this script to execute the command:


DBCC TRACEON (3604)
GO

DBCC page(@DBID, 1, 26408, 3)


GO

The output will be page allocation details.

DBCC TRACEON (3604)


GO

dbcc page(@DBID, 1, 26255, 3)


GO

Definition
An identity column has a name, initial seed and step.  When a row is inserted into a table the
column will take the value of the curent seed incremented by the step.

Note: An identity column is not guaranteed to be unique nor consecutive. You should always
place a unique index on an identity column if your system requires uniqueness.

Creating And Using Identity Columns

We create an example table

CREATE TABLE #a(i INT IDENTITY(1,1), j INT)

This is the usual way you will see an identity used and is the default.  It gives the same result
as ...

CREATE TABLE #a(i INT IDENTITY, j INT)

Inserting rows ...

INSERT #a SELECT 1
SELECT * FROM #a
i j
----------- -----------
1 1

... will work but is a bit confusing and may be version dependent. It is a good idea to always
name the columns inserted and leave the others to default.

INSERT #a (j) SELECT 1


SELECT * FROM #a
i j
----------- -----------
1 1
2 1

Note one use of an identity. We have inserted duplicate rows but can separate them by the
identity column value. The identity also shows the order in which the rows were inserted.

We can find the current identity seed by using DBCC checkident ...

DBCC checkident (#a)

Checking identity information: current identity value '2', current column


value '2'.

So the current seed is 2 - remember the next value will be the current seed plus the step.

Failed Inserts
BEGIN TRAN
INSERT #a (j) SELECT 1
ROLLBACK TRAN
SELECT * FROM #a

i j
----------- -----------
1 1
2 1

DBCC checkident (#a)


Checking identity information: current identity value '3', current column
value '3'.

The table has not changed but we can see from the checkident that the current seed has been
changed and we know that this is used to generate the next value.

Note: The next value is the step added to the current seed; not one more than the max value in
the table, or even the step from the last or maximum value.

INSERT #a (j) SELECT 1


SELECT * FROM #a
i j
----------- -----------
1 1
2 1
4 1

The situation above commonly happens when there is an index violation on j.

Values For Original Seed And Step

Note that the initial seed and step can be any integer value
CREATE TABLE #b (i INT IDENTITY(-7,5), j INT)
INSERT #b (j) SELECT 1
INSERT #b (j) SELECT 1
INSERT #b (j) SELECT 1
SELECT * FROM #b
i j
----------- -----------
-7 1
-2 1
3 1
CREATE TABLE #c (i INT IDENTITY(1,-3), j INT)
INSERT #c (j) SELECT 1
INSERT #c (j) SELECT 1
INSERT #c (j) SELECT 1
SELECT * FROM #c
i j
----------- -----------
1 1
-2 1
-5 1

Inserting Specific Identity Values

We can insert a specific identity value to override the generated value.  To do this execute a SET
IDENTITY_INSERT #a ON and specify the column list explicitly.

SET IDENTITY_INSERT #a ON
INSERT #a (i,j) SELECT 2,2
SET IDENTITY_INSERT #a OFF
SELECT * FROM #a

i j
----------- -----------
1 1
2 1
4 1
2 2

Remember that the identity doesn't guarantee uniqueness? We now have 2 rows with the identity
value 2.

What has happened to the seed?

DBCC checkident (#a)


Checking identity information: current identity value '4', current column
value '4'.

Note that it is not affected by the previous insert. Let's insert a higher value ...

SET IDENTITY_INSERT #a ON
INSERT #a (i,j) SELECT 10,3
SET IDENTITY_INSERT #a OFF
SELECT * FROM #a
i j
----------- -----------
1 1
2 1
4 1
2 2
10 3

DBCC checkident (#a)

Checking identity information: current identity value '10', current column


value '10'.

This time the seed is updated - that is because the value we inserted was higher than the current
seed. It will increase but not decrease.

But what happens if the step is negative?

SELECT * FROM #c

i j
----------- -----------
1 1
-2 1
-5 1

DBCC checkident (#c)


Checking identity information: current identity value '-5', current column
value '-5'.
note: step is -3
SET IDENTITY_INSERT #c ON
INSERT #c (i,j) SELECT -8,2
SET IDENTITY_INSERT #c OFF

SELECT * FROM #c
i j
----------- -----------
1 1
-2 1
-5 1
-8 2

DBCC checkident (#c)


Checking identity information: current identity value '-8', current column
value '-8'.
SET IDENTITY_INSERT #c ON
INSERT #c (i,j) SELECT 10,2
SET IDENTITY_INSERT #c OFF
SELECT * FROM #c

i j
----------- -----------
1 1
-2 1
-5 1
-8 2
10 2

DBCC checkident (#c)

So the update of the seed takes into account the sign of the step.

Changing The Current Seed

We have seen that the current seed can be changed by an insert - but only in the direction of the
step. A better way is to use DBCC checkident. This will take a reseed keyword and value to set
the seed.

CREATE TABLE #d (i INT IDENTITY (5,2), j INT)


INSERT #d (j) SELECT 1
INSERT #d (j) SELECT 1
SELECT * FROM #d
i j
----------- -----------
5 1
7 1

DBCC checkident(#d)
Checking identity information: current identity value '7', current column
value '7'.
DBCC checkident(#d, reseed, 2)

Checking identity information: current identity value '7', current column


value '2'.

Note this is the first time that the current seed has been different from the last allocated value.

INSERT #d (j) SELECT 2


SELECT * FROM #d
i j
----------- -----------
5 1
7 1
4 2

We can also reset the current seed to it's original value via a truncate table.

Note - a delete does not do this.

TRUNCATE TABLE #d
DBCC checkident(#d)
Checking identity information: current identity value 'NULL', current column
value 'NULL'.

INSERT #d (j) SELECT 1


SELECT * FROM #d
i j
----------- -----------
5 1

DBCC checkident(#d)
Checking identity information: current identity value '5', current column
value '5'.

Finding The Identity Value

A common requirement is to find the identity value for an inserted row. There are several
statements associated with this

 scope_identity
 ident_current
 @@identity

scope_identity()

returns the last identity inserted in the current scope and session. This is usualy the only one of
these functions that is useful. It is not affected by other connections or tables nor by triggers.

@@identity

will return the last identity value inserted in any scope. This means that if a trigger inserts into a
table with an identity then that is the value returned. This means that adding replication or
auditing triggers to a database can alter the value of @@identity. In earlier versions of sql server
this was the only means of returning the identity value and care had to be taken.

ident_current('table')

returns the last value inserted into that table on any connection. Remember to put the table
name in quotes

As stated earlier scope_identity() is probably the only one of these functions that you will need
to use.

Using Scope_Identity()

As stated earlier scope_identity() returns the last identity value inserted.

CREATE TABLE #t1 (i INT IDENTITY(5,1), j INT)


INSERT #t1 (j) SELECT 1
SELECT SCOPE_IDENTITY(), MAX(i) FROM #t1

--------------------------------------- -----------
5 5

scope_identity also returns the value after a rollback

BEGIN TRAN
INSERT #t1 (j) SELECT 1
ROLLBACK TRAN
SELECT SCOPE_IDENTITY(), MAX(i) FROM #t1

--------------------------------------- -----------
6 5

but the value is not updated for a failure due to an index violation although the value is allocated

CREATE UNIQUE INDEX ix ON #t1 (j)


INSERT #t1 (j) SELECT 1
SELECT SCOPE_IDENTITY(), MAX(i) FROM #t1

--------------------------------------- -----------
6 5
INSERT #t1 (j) SELECT 2
SELECT SCOPE_IDENTITY(), MAX(i) FROM #t1

--------------------------------------- -----------
8 8

Adding An Identity Column To A Table.

An identity column can be added to a table via an alter table statement. Values will be allocated
to the column according to the seed and step.

In this case SCOPE_IDENTITY() will not return an allocated value.

CREATE TABLE #t2 (j INT)


INSERT #t2 (j) SELECT 1
INSERT #t2 (j) SELECT 1
INSERT #t2 (j) SELECT 1
INSERT #t2 (j) SELECT 1
SELECT * FROM #t2

j
-----------
1
1
1
1
ALTER TABLE #t2 ADD i INT IDENTITY (5,2)
SELECT * FROM #t2

j i
----------- -----------
1 5
1 7
1 9
1 11

This can be useful for dealing with tables with duplicate rows.

Note - an existing column cannot be made into an identity. In this case you must drop the
existing column and add a new one.

In this instance the existing values cannot be retained. To retain existing values create a new
table and insert using identity_insert.  Also as this will update all rows in a table it can take a
very long time on large tables and increase the log size.

Select Into

An identity column can be included in a table created using a select into statement via the
identity function

SELECT *, IDENTITY(INT,1,1) AS id INTO #tbl FROM sysobjects

This is useful for creating a table from existing structures

Identity Datatypes

The identity must only contain integer values but the column can be of any numeric datatype
(bigint, int, tinyint, numeric, decimal). This can be useful when values greater than be contained
in a bigint are required.

Detecting Identity Columns And Their Properties

The existance of an identity column on a table can be checked via

SELECT OBJECTPROPERTY(OBJECT_ID('<tablename>'),'TableHasIdentity')

Which will return 1 if an identity exists on the table.

Similarly ...

SELECT COLUMNPROPERTY(OBJECT_ID('<tablename>'),'<columnname>','IsIdentity')

... Will show if a column has the identity property.

A more useful way of obtaining this information is by using the catalog view
sys.identity_columns which returns a row for each column in the database with an identity
property.
SELECT TableName = OBJECT_NAME(OBJECT_ID) ,
       ColumnName = name ,
       OriginalSeed = seed_value ,
       Step = increment_value ,
       LastValue = last_value ,
       IsNotForReplication = is_not_for_replication
FROM sys.identity_columns

Character Values In An Identity Column

A common request is to hold a composite value and to allocate sequential values depending on
the character part
eg.

a1
a2
a3
b1
b2

This is not possible and probably not even desirable. Notice that this column actually contains
two values - what would be it's purpose?

Perhaps it is trying to allocate a sequence to the character part. That definition highlights the
mistake - the sequence value is separate to the character part and should be a separate column.

Now we can use an identity for the numeric value and easily calculate a consecutive value for the
character value from this when accessing the table or in a view.

If it is required to keep the sequence value in the table - maybe for performance reasons then this
could be maintained via a trigger.

Bulk Insert

If the table has an identity column then a bulk insert will often fail if the identity values are not
held in the text file. The easiest way around this is to create a view on the tabke excluding the
identity column and bulk insert into the view. Another option is to create a format file to use with
the bulk insert. I would avoid this option if possible as it adds an external object and is more
difficult to maintain.

It is tempting to assume that the identity values will be allocated in the order of rows in the text
file but this is not the case.  This is often an issue with unstructured data like XML. In this case
an XML block cannot be parsed using the identity values. It often will work but cannot be
guaranteed - especially if multiple threads are spawned - better not to rely on it.

To deal with such data import into text column (or varchar(max) in v2005+) then parse the data.
This might be quite slow. You will not be able to define a column or row terminator and there is
an interesting "feature" to be aware of in some versions of sql server:  If the text file length is
divisble by 4 the bulk insert would fail without giving an error. Test your version to see if it has
this problem and if so you can check the file length and and a dummy character if it's divisible by
4.

To Use An Identity Or Not

It is a question that often raises passions of almost religious fervour and a search will find many
threads on the subject.

I have heard people say that every table in a database should have an identity column and that
only those should be used in joins. Other people say that they have no place in a relational
database and should never be used. I would not subscribe to either of these opinions but would
use an identity where it seems sensible. When importing data into staging tables an identity can
be useful to identify the rows which may otherwise contain duplicates. In the same situation it
can be useful for batching rows to fit in with the memory available for processing.  A lookup
table needs an ID - why not make it an identity if it is not allocated from a script. It can be useful
for allocating IDs - e.g. a customer ID but be careful about different systems allocating the same
ID.

Disaster Recovery

There can be an issue with disaster recovery and standby systems. If the identity values are used
in another database then the databases may get out of step. When the standby system is brought
on-line there needs to be some means of checking that the values are consistent across the
databases

Summary Of Points Covered

 An identity column has a name, initial seed and step.


 An identity column is not guaranteed to be unique nor consecutive
 We can find the current identity seed and change it by using dbcc checkident
 The next value allocated is the step added to the current seed.
 An insert failure can change the current seed value.
 An explicit value may be inserted via set identity_insert on and including the column list.
 A value explicitly inserted that is more than the current seed in the direction of the step will
update the current seed.
 A truncate table (but not delete) will update the current seed to the original seed value.
 Scope_identity() can be used to find the last identity value allocated.
 An identity column can be added to a table but the identity property of an existing column
cannot be changed.
 The identity function may be used to create an identity column on a table created using select
into.
 Identity columns and their properties can be found via sys.identity_columns.
 Bulk insert cannot be guaranteed to allocate the identity values in the order of rows in a text
file.
 It is sometimes easier to use a view to bulk insert into a table with an identity column.
Introduction

Protecting database information from threats and vulnerabilities is very important for any
organization; security should be a critical feature of any database engine. The new security
features in Microsoft SQL server 2008 are designed to make the database more secure. This
article discusses the top 10 new security features introduced in SQL server 2008.

Feature -1 Policy-Based Management Configuration

SQL server 2008 introduces policy-based management, which helps DBAs to define
standard rules or policies and enforce these rules for configuring and managing SQL Server
databases throughout the enterprise. By using the new surface area facet to control active
services and features, policy-based management reduces database exposure to security
threats. You can apply policy-based management on servers, databases, and database
objects (tables, indexes, etc.) across the enterprise. DBAs can define policy-based
management configuration using SQL Server Management Studio Environment. The policy
management node is available under the management node in Object Explorer (a dockable
window present in SQL Server Management Studio); where you will also see policies,
conditions, and facets sub nodes. To define a new policy from SQL Server Management
Studio you need to set following:

1. Target entity - Database or database object on which you would like to enforce your
policy.
2. Facet - SQL server 2008 already has a predefined set of rules under the facets sub
node. You just need to select the appropriate facet while creating a condition. Each
facet contains a list of properties. For example, the auto shrink database option is a
property.
3. Condition - An expression that will return either true or false value. Your policy-
based management will test whether a condition has returned true or false.
4. Policy - You can create a new policy by right clicking on the policies node and
selecting new option. While creating a new policy you need to select a predefined
condition and execution mode. You can schedule a policy using SQL agent (by
creating a Job). For on demand execution, select the policy from Object Explorer and
select evaluate.

Feature -2 Transparent Data Encryption (TDE)

Transparent data encryption (TDE) enables application developers to encrypt an existing


SQL server database without changing the application tires. In SQL Server 2000, developers
need to write an extended stored procedure to implement encryption on data but not on the
full database; or they need to use third party tools like DbEncrypt. To implement encryption
in SQL Server 2005, all table column data types must be varbinary. Microsoft has overcome
these issues by introducing TDE a full database level encryption with SQL Server 2008. TDE
is designed to provide protection for the entire database without affecting existing
applications. (See "Transparent Data Encryption (TDE) in SQL Server 2008").
Feature -3 Extensible Key Management (EKM)

It's always recommended to store database encryption keys and passwords separately from
the data. The Extensible Key Management (EKM) feature of SQL server 2008 enables you to
manage encrypted keys and passwords to external hardware devices like smart cards, USB
devices or a hardware security module (HSM). EKM uses the Microsoft Cryptographic API
(MSCAPI) provider for encryption and key generation. Third party vendors also provide
enterprise key management by using HSM. These HSM devices store encryption keys on
hardware or software modules that makes a database more secure because the encryption
keys do not reside with encryption data. Before implementing EKM, you need to explicitly
execute the sp_configure command to enable this feature.

sp_configure 'show advanced', 1


GO
RECONFIGURE
GO
sp_configure 'EKM provider enabled', 1
GO
RECONFIGURE
GO

Feature -4 Authentication improvements and enforce password


policies

There are significant improvements in SQL Server 2008 authentication rules. Now it
supports encryption of the channel by default through the use of SQL-generated certificates.
In addition, the database engine uses Windows group policy for password complexity,
password expiration, and account lockout.

SQL server 2008 password policy is also different from previous versions of SQL Server.
New password policy is built using NetValidatePasswordPolicy () API, which is part of the
NetAPI32 library on Windows Server 2003 (enforce minimum password length, proper
character combinations, and regularly-changing passwords).You can't create simple
passwords like 'sa' in SQL server 2008 only complex passwords are recommended in
production environments. To modify existing SQL Server 2008's password policy, you must
change the authentication mode to mixed and execute the following SQL command:

ALTER LOGIN sa WITH PASSWORD = 'sa' UNLOCK, CHECK_POLICY = OFF,


CHECK_EXPIRATION = OFF

Feature -5 Protecting Metadata

SQL Server 2008 protects metadata at the granular level. In SQL Server 2000, any user
having database access could view metadata information. However, SQL Server 2008
protects metadata by providing permissions to the owner who has access on metadata
objects. In addition, there is a view definition available for granting permission to users for
accessing metadata. SQL Server 2008 also shows an error message if a user with no
permissions wants to drop an object from the database. The following example shows an
error message.
Cannot drop the table 'tbluser', because it does not exist or you do not have
permission.

Feature -6 Use the built-in cryptography hierarchy in SQL


Server 2008

SQL Server 2008 supports different types of data encryption using symmetric and
asymmetric keys, and digital certificates. On the server level, there is a service master key
and within the scope of a database, there is database master key. The scope of the
database master key is on the entire database objects, certificates, and data in the
database. Each database can have a single master key. You can create a database master
key with the CREATE MASTER KEY T-SQL statement.

USE master;
GO
CREATE MASTER KEY
ENCRYPTION BY PASSWORD = '23987hVJ#Kh95234nl0zBe';
GO

After creating the database master key, a developer can create asymmetric keys,
symmetric keys or certificates depending on the type of encryption policy they want to
apply on the database.

Feature -7 Sign code modules

SQL Server 2008 provides the flexibility to sign your stored procedures, functions, triggers,
and event notifications digitally with certificates. Using  a code module you can restrict
database objects to be available through certificates only. This provides more granular level
control over access to database objects. Sign code modules also provide you the additional
benefit of protecting your database code against unauthorized changes.

The following code snipped shows the steps sign code module creation for providing access
to TestUser on TestSchema.GetUserAccess procedure.

CREATE CERTIFICATE TestCodeSigningCert


ENCRYPTION BY PASSWORD = 'tJI%@V4!axnlXflC'
WITH SUBJECT = 'Test Code signing certificate'
GO
-- Sign the stored procedure
ADD SIGNATURE TO TestSchema.GetUserAccess BY CERTIFICATE TestCodeSigningCert
WITH PASSWORD = ' tJI%@V4!axnlXflC '
GO
-- Map a user to the certificate
CREATE USER TestUser FOR CERTIFICATE TestCodeSigningCert
GO
--Assign SELECT permissions to new TestUser
GRANT SELECT ON SocialSecurity TO TestUser
GO
-- Grant execute permission to the user who will run the code
GRANT EXECUTE ON TestSchema.GetUserAccess TO ProcedureUser
GO
Feature -8 Auditing in SQL Server 2008

SQL Server 2008 introduces a number of new auditing features. With the newly included
audit object, you can log audit information in a file, Windows application log and Windows
security log. You can create an audit object using the CREATE SERVER AUDIT statement.
The following T-SQL code creates two audit objects; the first one logs activity to a file, and
the other to log activity to the windows application log.

CREATE SERVER AUDIT TEST_File_Audit1


TO FILE ( FILEPATH='\SQLSERVPROD_1Audit_LogTest' );
CREATE SERVER AUDIT TEST_File_Audit2
TO APPLICATION_LOG
WITH ( QUEUE_DELAY = 500, ON_FAILURE = SHUTDOWN);

Feature -9 Enhance security features with execution context

SQL Server 2008 identifies modules (SQL statements in stored procedures, functions) with
an execution context so that T-SQL statements within the module execute under a
particular user instead of the calling user. When creating user defined functions, stored
procedures and triggers you can use the EXECUTE AS clause to specify which user's
permissions SQL Server uses to validate access to objects. In the following example,
TestProc will execute under TestUser1 user.

CREATE PROCEDURE TestProc(@TestParam varchar(50))


WITH EXECUTE AS 'TestUser1'

Feature -10 Use Windows Update to automatically apply SQL


Server 2008 patches

To avoid security threats and vulnerabilities you need to periodically update SQL server
patches provided by Microsoft. You can now use Windows update to automatically download
SQL Server 2008 patches and install throughout the enterprise to reduce threats caused by
known software vulnerabilities.

Conclusion

SQL Server 2008 enhanced the security features to protect the database and other
resources. SQL Server 2008 provides many tools to configure the database server and more
specifically, the configuration of server surface area. New authentication and password
policies provide granular level security. Metadata is also more secure now as only
authenticated and permitted users can access that. Full database encryption can be
provided now using TDE.
An Introduction to Stored Procedures

There are mainly two ways by which you can store a batch of statements in SQL
Server, Procedures and functions. Both are almost similar in structure, with few differences. In
this section, I am mainly concentrating on Stored procedures.

So, what is a Stored Procedure ? It's nothing but a batch of  stored SQL Statements, which can
accepts and returns values if needed.

Syntax

1: CREATE PROC[EDURE] urProcedureName


2: [<@InputParameter> Datatype default] [, 1..n] ]
3: [<@OutputParameter> Datatype OUT[PUT]][, 1..n] ]
4: [WITH { RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ]
5: AS
6: [BEGIN ]
7: [SqlStatements;][1..n]
8: [END]
9: GO

font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Parameter description

urProcedureName : this is the desired name of the new stored procedure, it can be upto 116
characters. Because of some performance problems, it is not recommended to prefix "sp_" in
user defined procedures.
parameters  : these holds the value, you passed to the procedure. During the execution, we need
to provide the value of each input parameters, unless it has been defined with some default
value.A stored procedure can have a maximum of 2,100 parameters. By default, parameters can
take the place only of constant expressions; they cannot be used instead of table names, column
names, or the names of other database objects.

The maximum size of a stored procedure is 128 MB.

At this moment, I think this is sufficient for you to start with SQL Server stored procedures. for
detailed information on the other parameters check books online.

My first stored procedure

Once you have knows the sql syntax, it is pretty easy to create stored procedures. As a simple
example here we are going to create a stored procedure that just returns a string.

1: CREATE PROCEDURE MyfirstStoredProc


2: AS
3: SELECT 'Welcome to the world of Sql Server'
4: GO
5:  

Type the above code in "Query analyzer" if you are using sql server 2000, or in "SQL Server
Management studio" if you are using sql server 2005.In order to compile it, press "F5", if you
wont get any error messages, then your statements will get stored in the database, and inorder to
further modify it, you can either DROP the procedure and recreate it, or you can replace 
"CREATE"  with "ALTER".

The above example creates a procedure with name "MyFirstStoredproc"  which shows the
message we mentioned in line # 3.  The "GO" statement on line#4, indicates the end of the batch
(and thus the end of the procedure).

In order to execute the procedure, you need to use "EXEC " followed by the procedure name.

EXEC MyfirstStoredProc

Stored Procedure with input parameters

Now we are going to write a stored procedure to do some addition operation, this stored
procedure accepts two numbers and shows the result.

1: CREATE PROCEDURE retSum


2: @Num1 INT,
3: @num2 INT
4: AS
5: SELECT (@Num1 + @Num2) AS Total
6: GO

the above stored procedure has two input parameters, @num1 and @num2, declared as integer.

You can execute the parameterized procedures in 2 ways, the first one is the based on 'Relative
location' ( values get substituted implicitly based one position) and the second one is the
'Explicit' substitution.

EXEC retSum 10, 20 -- implicit substitution


EXEC retSum @num2 = 20,
@Num1 = 10 -- Explicit substitution

For explicit substitution, you must know the parameters of the sp. for example, if you accidenlty
types @num4 for an existing parameter, then the sp call will throw an error like

Server: Msg 8145, Level 16, State 2, Procedure retSum, Line 0


@num4 is not a parameter for procedure retSum.

So you must be very careful, while using the explicit call.

Stored Procedure with Output parameter

You can return values from a stored procedure in three different ways.

1. Using SELECT statement 
2. Using RETURN statement
3. Using OUTPUT parameters

The above examples uses the 'SELECT' statement to return a the value. In this section, we are
going to look at the other two.
 

CREATE PROCEDURE retSumAsOutput


@Num1 INT,
@num2 INT,
@Sum INT OUT
AS
SELECT @sum = @Num1 + @Num2
GO

Executing this sort of stored procedure is somewhat tricky, you need to declare the variables to
hold the values returned by the stored procedure.For example, above procedure can be executed
as follows

DECLARE @Res INT


EXEC retSumAsOutput 1,2, @Res OUT
SELECT @Res

Returning a value from SQL Server Stored procedure using Return Statement

Return statement can return only an integer value. Also you should note that, the execution quits
unconditionally once it processes the 'Return' statement, so the statements after the 'Return' wont
get executed.
CREATE PROCEDURE retTest
@i int
as
RETURN @i*@i
GO

DECLARE @retValFromSP int


EXEC @retValFromSP = retTest 10
SELECT @retValFromSP

I hope, all of you got some basic idea on writing the stored procedures. Now, let me explain what
are the advantages of Stored procedures over the usual sql query.

The main advantage is the performance. Whenever you submits a query to SQL, it has to go
several processes before execution( Parsing -> optimization ->Compilation -> execution), and
for the Stored procedures this is an one time process and the  SQL stores the execution plan in
the cache , and the subsequent calls to this stored procedure will make of this saved plan, thus
saving a lot of time.

Using SQL server stored procedures, you can avoid the network round trips. Consider the
situations where you are sending a long sql statement from the front end and imagine the same
page will get called from the application more that 100 times per hour.Now if you have a stored
procedure, which does the same stuff, can you say how much bandwidth we saved ?

Another advantage is that a procedure encapsulates the business logic. for example, if I run an
sql server stored procedure using 'exec tstSp' , then no one in this world can tell, what is
happening inside that procedure, without looking the script.

Security, the SQL server stored procedures provides security in two was; the first one is by using
'ENCRYPTION' option it can encrypts the contents of that stored procedure, this prevents the
users from directly viewing the contents of the sp and hides the business logic. We don't actually
need to give permissions to those tables used in that particular stored procedure, we just need to
provide the users to execute that stored procedure.
If you write the Queries at the front end itself, then future modifications, need a more time for
deployment.Now, if you implement the logic at the back end, its pretty easy to manage .So you
can save lot of time for deployment and compilation.

Reusability; if you encapsulate the sql server statement as a stored procedure, you just need to
call that stored proc, wherever you need to execute that statement.

you must be very careful, while using the explicit call.

Stored Procedure with Output parameter

You can return values from a stored procedure in three different ways.

1. Using SELECT statement 
2. Using RETURN statement
3. Using OUTPUT parameters

The above examples uses the 'SELECT' statement to return a the value. In this section, we are
going to look at the other two.

CREATE PROCEDURE retSumAsOutput


@Num1 INT,
@num2 INT,
@Sum INT OUT
AS
SELECT @sum = @Num1 + @Num2
GO

Executing this sort of stored procedure is somewhat tricky, you need to declare the variables to
hold the values returned by the stored procedure.For example, above procedure can be executed
as follows
DECLARE @Res INT
EXEC retSumAsOutput 1,2, @Res OUT
SELECT @Res

Returning a value from SQL Server Stored procedure using Return Statement

Return statement can return only an integer value. Also you should note that, the execution quits
unconditionally once it processes the 'Return' statement, so the statements after the 'Return' wont
get executed.

CREATE PROCEDURE retTest


@i int
as
RETURN @i*@i
GO

DECLARE @retValFromSP int


EXEC @retValFromSP = retTest 10
SELECT @retValFromSP

I hope, all of you got some basic idea on writing the stored procedures. Now, let me explain what
are the advantages of Stored procedures over the usual sql query.

The main advantage is the performance. Whenever you submits a query to SQL, it has to go
several processes before execution( Parsing -> optimization ->Compilation -> execution), and
for the Stored procedures this is an one time process and the  SQL stores the execution plan in
the cache , and the subsequent calls to this stored procedure will make of this saved plan, thus
saving a lot of time.
Using SQL server stored procedures, you can avoid the network round trips. Consider the
situations where you are sending a long sql statement from the front end and imagine the same
page will get called from the application more that 100 times per hour.Now if you have a stored
procedure, which does the same stuff, can you say how much bandwidth we saved ?

Another advantage is that a procedure encapsulates the business logic. for example, if I run an
sql server stored procedure using 'exec tstSp' , then no one in this world can tell, what is
happening inside that procedure, without looking the script.

Security, the SQL server stored procedures provides security in two was; the first one is by using
'ENCRYPTION' option it can encrypts the contents of that stored procedure, this prevents the
users from directly viewing the contents of the sp and hides the business logic. We don't actually
need to give permissions to those tables used in that particular stored procedure, we just need to
provide the users to execute that stored procedure.

If you write the Queries at the front end itself, then future modifications, need a more time for
deployment.Now, if you implement the logic at the back end, its pretty easy to manage .So you
can save lot of time for deployment and compilation.

Reusability; if you encapsulate the sql server statement as a stored procedure, you just need to
call that stored proc, wherever you need to execute that statement.

You might also like