SQL SERVER – Reason for SQL Server Agent Starting Before SQL Server Engine Service

Nakul, a dedicated member of the Gandhinagar SQL Server User Group, recently emailed me with a very interesting, but quick question. He asked me why the SQL Server Agent starts before SQL Server Engine does? He made the very valid point that as the SQL Server Engine is the core service, it should start first, and there is little point to running the SQL Server Agent without it.

Off the top of my head, I can offer the following quick reasons for this sequence:

  • The SQL Server Engine does not only run jobs for SQL Server Engine itself. It also runs jobs for other core services like the SQL Server Analysis Service, Integration Service, Reporting Service etc.;
  • The SQL Server Agent can run almost any kind of task that an Operating system can run. For example invoking any program or running shell scripts;
  • The SQL Server Agent also starts jobs which are scheduled to run the second the SQL Server Engine starts, and for this reason it is needed; and
  • Replication, mirroring and a few other tasks also depend on Agent Jobs.

These are the reasons that I have come up with so far. Can you think of any more? Let us have your views.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

SQL SERVER – Forgot the Password of Username SA

I just received a call from an old friend with whom I used to work in Las Vegas. He told me about a password-related issue he faced in his organization. They had changed the password of username SA and now they are not able to recall the new password. I am sure that he is not the first person who has faced this issue. There may be many more similar situations where employees who have sysamin password leaves the job or a hacker disables the SA account.

Resetting the password of SA is a breeze!

Option 1 :

If there is any other SQL Server Login that is a member of sysadmin role, you can log in using that account and reset the password of SQL Server. Change the password of SA account as described here :  SQL SERVER – Change Password of SA Login Using Management Studio.

Option 2 :

If there is any other Windows Login that is a member of Windows Admin Group, log in using that account. Start SQL Server in Single User Mode as described here :  SQL SERVER – Start SQL Server Instance in Single User Mode.
Create a new login and give it sysadmin permission.

Note : If you have SQL Server Agent enabled, it starts before SQL Server service. If you have enabled SQL Server in a single user mode, it will connect it first, so it is recommended to turn that off before attempting any of the above options.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

SQL SERVER – 2008 – Policy-Based Management – Create, Evaluate and Fix Policies

This article will cover the most spectacular feature of SQL 2008 – Policy-based management and how the configuration of SQL Server with policy-based management architecture can make a powerful difference. Policy based management is loaded with several advantages. It can help you implement various policies for reliable configuration of the system. It also provides additional administration assistance to DBAs and helps them effortlessly manage various tasks of SQL Server across the enterprise.

1 Introduction
2 Basics of Policy Management
3 Policy Management Terms
4 Practical Example of Policy Management
4.1 Exploring of Facets
4.2 Create a Condition
4.3 Create a Policy
4.4 Evaluate a Policy
4.5 Fix Non-complying Policy
5 Summary

Read complete article here.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

SQLAuthority News – Using SQL Server 2008 Extended Events – White paper By Jonathan Kehayias

Strange it may sound but being a SQL Server pro has its downside too. Common information on SQL does not interest me, while a good document is hard to find. So the reader in me is mostly discontented and constantly keeps looking for interesting documents.  Recently, I chanced upon a really good white paper by Jonathan Keyhayias on SQL Serve r2008 extended events. I have known Jonathan through forums but have not met him in person yet. But I hope to meet him soon.

The white paper starts with introduction to the extended event and then elaborates on its architecture, system objects, confusing target data and other important aspects of the extended events. This white paper ends with life of an event, and I would recommend that you read this portion at least if you do not have sufficient time to read the whole white paper.

Let us go through the first paragraph taken from the white paper which lucidly defines extended events.

What is extended events?
As SQL Server matures with time, the diagnostics tools available to administrators to troubleshoot problems when they arise have also matured. SQL Server 2000 had very limited diagnostic tools when compared with SQL Server 2005. SQL Trace and SQL Server Profiler were often the tools of choice for administrators to identify problems with performance, along with DBCC and individual trace flags like 1205 for deadlocks, and 3605 to log results to the SQL Server error log. With SQL Server 2005, the diagnostic tools expanded to include the dynamic management views, which provide a deep view into the internal workings of SQL Server, additional trace events for SQL Trace and SQL Server Profiler including the deadlock graph and Showplan XML events, the ability to import performance counter logs in SQL Server Profiler to view trace events along with their impact on the system, and WMI events which use Service Broker endpoints for event notifications. SQL Server 2008 continues to build upon the diagnostic tools with a new feature called Extended Events.

You can continue reading the white paper Using SQL Server 2008 Extended Events here.

Let me have your views about this white paper.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

SQL SERVER – Find Hostname and Current Logged In User Name

I work in an environment wherein I connect to multiple servers across the world. Time and again, my SSMS is connected to a myriad of servers that kindles a lot of confusion. I frequently use the following trick to separate different connections, which I mentioned in my blog sometime back SQL SERVER – 2008 – Change Color of Status Bar of SSMS Query Editor. However, this trick does not help when a huge number of different connections are open. In such a case, I use the following handy script. Do not go by the length of the script; it might be very short but always works great!

Now, let’s take a look at the execution of this script in two different scenarios.

1) Logged in using SQL Authentication

SELECT HOST_NAME() AS HostName, SUSER_NAME() LoggedInUser

2) Logged in using Windows Authentication

SELECT HOST_NAME() AS HostName, SUSER_NAME() LoggedInUser

It is quite evident from both the above cases that we get correct logged-in username and hostname. Let me know if this script is helpful to you when you face a similar situation.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

SQL SERVER – FIX : ERROR : is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)

Just a day ago, one of my friend sent me email requesting help with following error:

is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)

In fact this is not SQL Server error but it is of .NET application. The solution of this error is just changing configuration of IIS7.

Fix/Solution/Workaround:

Go to IIS.
Click on Application Pool.
Look for your web application in application pool.
Go to Advanced Settings by right clicking on previously selected application pool.
Enable 32-Bit Applications by checking it.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

SQL SERVER – Introduction to SQL Server Encryption and Symmetric Key Encryption Tutorial with Script

SQL Server 2005 and SQL Server 2008 provide encryption as a new feature to protect data against hackers’ attacks. Hackers might be able to penetrate the database or tables, but owing to encryption they would not be able to understand the data or make use of it. Nowadays, it has become imperative to encrypt crucial security-related data while storing in the database as well as during transmission across a network between the client and the server.

Encryption hierarchy is marked by three-level security. These three levels provide different mechanisms for securing data across networks and local servers. Different levels of hierarchies allow multiple instances of services (e.g., SQL Server Services) to run on one physical server.

  • Windows Level – Highest Level – Uses Windows DP API for encryption
  • SQL Server Level - Moderate Level – Uses Services Master Key for encryption
  • Database Level – Lower Level – Uses Database Master Key for encryption

There are two  kinds of keys used in encryption:

  • Symmetric Key – In Symmetric cryptography system, the sender and the receiver of a message share a single, common key that is used to encrypt and decrypt the message. This is relatively easy to implement, and both the sender and the receiver can encrypt or decrypt the messages.
  • Asymmetric Key – Asymmetric cryptography, also known as Public-key cryptography, is a system in which the sender and the receiver of a message have a pair of cryptographic keys – a public key and a private key – to encrypt and decrypt the message. This is a relatively complex system where the sender can use his key to encrypt the message but he cannot decrypt it. The receiver, on the other hand, can use his key to decrypt the message but he cannot encrypt it. This intricacy has turned it into a resource-intensive process.

Yet another way to encrypt data is through certificates. A public key certificate is a digitally signed statement that binds the value of a public key to the identity of the person, device, or service that holds the corresponding private key. A Certification Authority (CA) issues and signs certifications. Download complete script here.

Please create a sample database that we will be use for testing Encryption. There are two different kinds of encryptions available in SQL Server:

  • Database Level – This level secures all the data in a database. However, every time data is written or read from database, the whole database needs to be decrypted. This is a very resource-intensive process and not a practical solution.
  • Column (or Row) Level – This level of encryption is the most preferred method. Here, only columns containing important data should be encrypted; this will result in lower CPU load compared with the whole database level encryption. If a column is used as a primary key or used in comparison clauses (WHERE clauses, JOIN conditions) the database will have to decrypt the whole column to perform operations involving those columns.

Let’s go over a simple instance that demonstrates the encryption and the decryption process executed with Symmetric Key and Triple DES encryption algorithm.

/* Create Database  */
USE master
GO
CREATE DATABASE EncryptTest
ON PRIMARY ( NAME = N'EncryptTest', FILENAME = N'C:\EncryptTest.mdf')
LOG ON ( NAME = N'EncryptTest_log', FILENAME = N'C:\EncryptTest_log.ldf')
GO

First, let’s create a sample table and then populate it with sample data. We will now encrypt one of the two columns of the table.

/* Create table and insert data in the table */
USE EncryptTest
GO
CREATE TABLE TestTable (FirstCol INT, SecondCol VARCHAR(50))
GO
INSERT INTO TestTable (FirstCol, SecondCol)
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
UNION ALL
SELECT 3,'Third'
UNION ALL
SELECT 4,'Fourth'
UNION ALL
SELECT 5,'Fifth'
GO
/* Check the content of the TestTable */
USE EncryptTest
GO
SELECT *
FROM TestTable
GO

The preceding code will return the result depicted in the subsequent figure.

Result of the SQL query

Every database can have one master key. Database master key is a symmetric key used to protect the private keys of certificates and asymmetric keys present in the database. It uses Triple DES algorithm together with user-provided password to encrypt the keys.

/* Create Database Master Key */
USE EncryptTest
GO
CREATE MASTER KEY ENCRYPTION
BY PASSWORD = 'SQLAuthority'
GO

Certificates are used to safeguard encryption keys, which are used to encrypt data in the database. SQL Server 2005 has the capability to generate self-signed X.509 certificates.

/* Create Encryption Certificate */
USE EncryptTest
GO
CREATE CERTIFICATE EncryptTestCert
WITH SUBJECT = 'SQLAuthority'
GO

The symmetric key can be encrypted by using various options such as certificate, password, symmetric key, and asymmetric key. A number of different algorithms can be employed for encrypting key. The supported algorithms are DES, TRIPLE_DES, RC2, RC4, RC4_128, DESX, AES_128, AES_192, and AES_256.

/* Create Symmetric Key */
USE EncryptTest
GO
CREATE SYMMETRIC KEY TestTableKey
WITH ALGORITHM = TRIPLE_DES ENCRYPTION
BY CERTIFICATE EncryptTestCert
GO

Now add a column of type varbinary to the original table, which will store the encrypted value for the SecondCol.

/*  Encrypt Data using Key and Certificate
Add Columns which will hold the encrypted data in binary */
USE EncryptTest
GO
ALTER TABLE TestTable
ADD EncryptSecondCol VARBINARY(256)
GO

Before the key is used, it needs to be decrypted using the same method that was used for encrypting it. In our example, we have used a certificate for encrypting the key. Because of the same reason, we are using the same certificate for opening the key and making it available for use. Subsequent to opening it and making it available for use, we can use the encryptkey function and store the encrypted values in the database, in the EncryptSecondCol column.

/* Update binary column with encrypted data created by certificate and key */
USE EncryptTest
GO
OPEN SYMMETRIC KEY TestTableKey DECRYPTION
BY CERTIFICATE EncryptTestCert
UPDATE TestTable
SET EncryptSecondCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),SecondCol)
GO

We can drop the original SecondCol column, which we have now encrypted in the EncryptSecondCol column. If you do not want to drop the column, you can keep it for future comparison of the data when we decrypt the column.

/* DROP original column which was encrypted for protect the data */
USE EncryptTest
GO
ALTER TABLE TestTable
DROP COLUMN SecondCol
GO

We can run a SELECT query on our database and verify if our data in the table is well protected and hackers will not be able to make use of it even if they somehow manage to reach the data.

/* Check the content of the TestTable */
USE EncryptTest
GO
SELECT *
FROM TestTable
GO

Result of the previous SQL query

Authorized user can use the decryptbykey function to retrieve the original data from the encrypted column. If Symmetric key is not open for decryption, it has to be decrypted using the same certificate that was used to encrypt it. An important point to bear in mind here is that the original column and the decrypted column should have the same data types. If their data types differ, incorrect values could be reproduced. In our case, we have used a VARCHAR data type for SecondCol and EncryptSecondCol.

/* Decrypt the data of the SecondCol  */
USE EncryptTest
GO
OPEN SYMMETRIC KEY TestTableKey DECRYPTION
BY CERTIFICATE EncryptTestCert
SELECT CONVERT(VARCHAR(50),DECRYPTBYKEY(EncryptSecondCol)) AS DecryptSecondCol
FROM TestTable
GO

If you drop the database after the entire processing is complete, you do not have to worry about cleaning up the database. However, in real world on production servers, the database is not dropped. It is a good practice for developers to close the key after using it. If keys and certificates are used only once or their use is over, they can be dropped as well. Dropping a database will drop everything it contains – table, keys, certificates, all the data, to name a few.

/* Clean up database  */
USE EncryptTest
GO
CLOSE SYMMETRIC KEY TestTableKey
GO
DROP SYMMETRIC KEY TestTableKey
GO
DROP CERTIFICATE EncryptTestCert
GO
DROP MASTER KEY
GO
USE [master]
GO
DROP DATABASE [EncryptTest]
GO

Summary

Encryption is a very important security feature of SQL Server 2005. Long keys and asymmetric keys create unassailable, stronger encryption and stronger encryption uses lots of CPU to encrypt data. Stronger encryption is slower to process. When there is a huge amount of data to encrypt, it is suggested to encrypt it using a symmetric key. The same symmetric key can be encrypted further with an asymmetric key for additional protection, thereby adding the advantage of a stronger encryption. It is also recommended to compress data before encryption, as encrypted data cannot be compressed.

Click to Download Scripts

Reference : Pinal Dave (http://blog.SQLAuthority.com)