Sunday, October 26, 2014

Case Sensitive Search in SQL Server

We all know that SQL is a case insensitive language. Yes, it is true. But we think that even in searching the data in database is also case insensitive. But that's not true. There lies a feature called COLLATION which contradicts our assumption.

Collation comes into action when we use ORDER BY clause. There are several collations which define language and sorting according to the alphabet of that language. The default collation we see in the English version of SQL Server on the English version of Microsoft Windows is Latin collation. As English is derived from Latin, the sorting of the English records in the database is performed according to the English alphabet. This Latin collation of two types, case sensitive and case insensitive. The default collation taken by SQL Server during its installation is Case Insensitive Latin collation. If case sensitive Latin collation is selected then that doesn't allow case insensitive searching of the records.

Let's see it practically...

USE AdventureWorks2012
GO
CREATE TABLE SENSITIVE_SEARCH (NAME VARCHAR(100))
GO
INSERT INTO SENSITIVE_SEARCH VALUES ('YASHWANTH'),('yashwanth'),('Yashwanth'),('yasHwanth')
GO
SELECT * FROM SENSITIVE_SEARCH

Now, I've created a table and inserted the same name in different styles.


Now let's do a search with a predicate,

SELECT * FROM SENSITIVE_SEARCH WHERE NAME = 'YASHWANTH'


See the result. It's same as above. Though you change the style of the predicate column value the result lies same.

To achieve case sensitive search, you need to change the collation. Collation can be changed at instance level, database level and column level. In this case, only for this table we need to achieve case sensitive search. So, changing the column's collation is enough.

Before changing the collation, let's know how to know collation at different levels...

1) To know the collation of the server through Object Explorer, right click on the instance name and select Properties.

Through T-SQL, collation can be known as,

SELECT SERVERPROPERTY('collation')

2) To know the collation of the database through Object Explorer, right click on the database and select Properties. Under Maintenance section, collation appears.

Through T-SQL, it can be known as,

SELECT DATABASEPROPERTYEX('AdventureWorks2012','collation')

or connect to the database and run this command

SELECT collation_name FROM sys.databases WHERE name = 'AdventureWorks2012'

3) To know the table collation through Object Explorer, right click on the Table and select Properties. Under Extended Properties, collation appears.

4) Collation of a column can be known through Object Explorer by right clicking on the column and selecting Properties.

Through T-SQL, it can be known as,

SELECT collation_name FROM sys.columns WHERE object_id = OBJECT_ID('SENSITIVE_SEARCH') AND name = 'NAME'

Now we need to change the collation of the column NAME in the table SENSITIVE_SEARCH. To facilitate case sensitive search, we need to choose a suitable collation. To know the available collations supported by SQL Server, run the following query.

SELECT * FROM sys.fn_helpcollations() WHERE name LIKE 'SQL%'

There are some characteristics to be noted while selecting a collation,

_CS - Case Sensitive
_CI - Case Insensitive
_AS - Accent Sensitive
_AI - Accent Insensitive
_KS - Kana Sensitive
_WS - Width Sensitive

In our present case, we require the following collation,

SQL_Latin1_General_CP1_CS_AS

To change the collation of our table's column to the above collation run the following command,

ALTER TABLE SENSITIVE_SEARCH ALTER COLUMN NAME VARCHAR(100) COLLATE SQL_Latin1_General_CP1_CS_AS

Now case sensitive search is enabled for the column NAME.

SELECT * FROM SENSITIVE_SEARCH WHERE NAME = 'YASHWANTH'
GO
SELECT * FROM SENSITIVE_SEARCH WHERE NAME = 'Yashwanth'



To know more about collations in SQL Server, follow the official documentation of Microsoft.

Tuesday, August 19, 2014

Database Mirroring in SQL Server - Post Mirroring Configuration, Monitoring & Troubleshooting

This post is the sequel of my post Database Mirroring in SQL Server - Configuration. In this post, we'll see about what to do after Database Mirroring is configured, how to monitor a mirroring session and troubleshooting the mirroring configuration.

Post Mirroring Configuration


After Database Mirroring is configured, the following steps have to be taken to ensure a correct service to clients,
  • The logins, jobs, SSIS packages etc that are created in Principal Instance must be created in Mirror Instance manually as they are not automatically replicated when mirroring is configured.
  • Any new changes made on Principal such as adding new logins, mapping new users to databases should be reflected manually in the Mirror instance too.


Monitoring the Mirroring Session


After mirroring is configured, it can be checked using the following query,

SELECT * FROM sys.database_mirroring

Run the above query in Principal and Mirror to know the status of instance, role etc. The first column of this view is database_id. For first records the values of this view is NULL because database_ids 1,2,3 and 4 are of system databases Master, Model, Msdb and Tempdb respectively. System databases cannot be mirrored, so they have NULL values.

For more information about this view, go here,


Database Mirroring Session can be monitored by using a built-in tool named Database Mirroring Monitor. 

Go to Object Explorer, right click the Principal or Mirror Database. Select Tasks and then click Launch Database Mirroring Monitor.

The databases that are configured for Mirroring are registered automatically with this tool. If not, they can be registered manually by clicking Register Mirrored Database on Home screen. From there, Principal and Mirror can be connected and registered. After registering, Database Mirroring Monitor shows the status of Principal and Mirror and their connection status with Witness. It is refreshed automatically for every 30 seconds and shows any unsent log including its size, estimated time to send it from Principal to Mirror etc. There lies a button History on clicking which the synchronization history appears. The history results can be filtered according to the given options.

In the Warnings tab, warnings can be configured by setting desired threshold values for different kinds of warnings. When a configured threshold is exceeded, an event is logged to the Application Even Log. This can be configured as an email alert.

Removing Database Mirroring


Configuring something may be difficult sometimes but removing something is very easy. So is the case with Mirroring. Mirroring can be removed with just one mouse click.

In Object Explorer, right click on the Principal database and click Properties. Under Mirroring tab, click on Remove Mirroring button. You will be asked for a confirmation. Confirm if mirroring has to be removed and it will be removed. Now you've removed Mirroring but you're not done with it completely. In the same Database Properties window, you can still see a Server Network Address for your principal instance. This is because there are endpoints configured and they have to be removed. For this, connect to Principal, Mirror and Witness (if any) and run the following SQL statement.

DROP ENDPOINT <Endpoint-Name>;

With this command, mirroring is removed completely including its endpoints. The Mirror database remains in a RESTORING state as it was created WITH NO RECOVERY option. To bring it into normal state, restore its backup WITH RECOVERY option or just run the following command,

RESTORE DATABASE <Database_Name> WITH RECOVERY

Troubleshooting Database Mirroring Configuration


While configuring Database Mirroring on a single computer with three instances, an error rises with Error Message 1418. This message indicates that the server network address cannot be reached or does not exist. It asks you to verify the server network address and re-issue the command.

For this, there is a simple solution. Go to SQL Server Configuration Manager and right click on SQL Server service and click on Properties. Under Log On tab, select This Account. In the Account Name field, provide your local system Account Name or click on Browse and search your account name by using Check Name button. Provide and confirm your account password and click Apply. It asks for restarting the service, click Yes and the service will be restarted. Do the same procedure for Principal, Mirror and Witness instances.


Now go to Database Properties window and click on Start Mirroring button which starts your mirroring session.

Sunday, August 17, 2014

Database Mirroring in SQL Server - Configuration

Configuring Database Mirroring becomes easier when one understands completely about what is mirroring. Please read my previous posts about introduction of Database Mirroring here,

Database Mirroring in SQL Server - Introduction (Part - 1)

Database Mirroring in SQL Server - Introduction (Part - 2)

Mirroring can be configured by using SQL Server Management Studio or Transact - SQL statements. Before configuring mirroring session, ensure the following conditions are met,
  • The recovery model of Principal database is FULL.
  • Create a mirror database on Mirror server by restoring the latest full backup of Principal Database WITH NO RECOVERY which allows inserting log records into it.
  • Take a log backup of Principal database and restore it on Mirror database WITH NO RECOVERY option.
  • To setup Database Mirroring, the used login should be of sysadmin fixed role.
The communication between instances that are participated in Mirroring is performed over TCP endpoints. Each instance should have its own Endpoint that listens over a unique TCP/IP port.

Configuring Database Mirroring using SQL Server Management Studio


In the Object Explorer, right click on the Principal Database and select Properties.

Go to Mirroring Page and click the Configure Security button which launches Configure Database Mirroring Wizard. Click Next.

Then comes Include Witness Server page which asks whether you need a Witness instance to be configured. If you want you Mirroring Session, select NO otherwise YES. Right now, I'm selecting YES.


Click Next which takes you to Choose Servers to Configure. Ensure that Witness Server Instance is checked to configure Witness.


Click Next to go to Principal Server Instance configuration. There the Principal Server Instance is already selected. As said earlier in this post, communication is done over TCP Endpoints. Each endpoint has its own TCP/IP port. By default there is a port 5022. If you're setting up Mirroring in your production environment, use another port for security reasons. The name of endpoint is Mirroring by default. You can rename it. There is also one more option for encrypting data that is sent through that endpoint, checked by default. If you want your data not to be encrypted, uncheck that check box.


Click Next to configure Mirror Server Instance. Select an instance that has to be used as Mirror and connect to it. The above specified things imply here also. Make sure that the listener port of Mirror should not be same if both Principal and Mirror are two separate instances on a single machine.


Click Next to configure Witness Server Instance. Even here, the above specified conditions imply.


Click Next to go to Service Accounts page. If the three instances belong to same domain account then no need to specify service accounts, leave the text boxes empty. If not, specify service accounts. This creates logins for each account and grants CONNECT permission on the endpoints. If the three instances are in a Workgroup then also no need to specify any Service Account.

Click Next which takes you to Complete the Wizard page. Verify all the options selected till now and click Finish if everything is OK. Now the endpoints are created for each instance.


Click Close button which takes you to Database Properties dialog box. In this dialog box, the properties of Principal, Mirror and Witness are displayed. SQL Server asks whether to start mirroring or not. If you want it to start mirroring right now, click on Start Mirroring. To start the session later, select Do Not Start Mirroring.

If you click Start Mirroring, it takes a few seconds to start the session and gives you the following screen.


At the bottom of above screen, you can see the current status of your Mirroring Session. You have options to Pause or Remove Mirroring and Failover (this is for Manual Failover).

You can also see your databases in Object Explorer by connecting to your Principal and Mirror Instances.


Now Principal and Mirror are synchronized with each other. The Mirror database will be in Restoring state as it was created WITH NO RECOVERY option. It cannot be connected now. Only Principal can be connected.

To test synchronizing, do some transactions on Principal and refresh the Object Explorer. You can see Principal and Mirror getting synchronized.

To test Automatic Failover, go to SQL Server Configuration Manager and shutdown Principal instance. Refresh the object explorer and you can find Mirror has become Principal. This is done by Witness.