Monday, March 21, 2011

Using the NOLOCK Table Hint

Each time you write and execute a T-SQL Query in SQL Server, the Database Engine selects the most optimized query plan for executing the query.

The SQL Server Database Engine component that undertakes this task is the Query Optimizer. Given the T-SQL query itself as well as the underlying database(s) design, the Query Optimizer selects the best execution plan for the query and then it executes the query.

Now, in SQL Server you can make use of several query hints, such as locking hints. Though, as SQL Server Query Optimizer typically selects the best execution plan for a query, it is not recommended for inexperienced developers and administrators to make use of them.

Nevertheless, today I will talk about a special table hint, that is the NOLOCK hint. This hint is equivalent to the READUNCOMMITTED hint.

A typical example of using the NOLOCK hint is the following:

SELECT *
FROM TABLE_NAME WITH (NOLOCK)
GO

Similar examples:

SELECT *
FROM TABLE_NAME A WITH (NOLOCK)
GO

SELECT *
FROM TABLE_NAME (NOLOCK)
GO

SELECT *
FROM TABLE_NAME A (NOLOCK)
GO

For environments where many concurrent queries are executed against the same database objects (i.e. Web Applications), the NOLOCK hint can become quite handy. By using this hint, the transaction isolation level for the SELECT statement is READ UNCOMMITTED. Of course, this means that the query may see inconsistent data, that is data not yet committed, etc. So, if this is not a problem for you, it might solve many concurrency issues.

Though note that in general is not a good idea to apply the above practice as a rule.

I hope you found this post useful!

Until next time!
Read more on this article...

Sunday, March 20, 2011

Database [Database_Name] cannot be upgraded because it is read-only or has read-only files

A few days ago I was trying to attach some databases on a SQL Server 2005 instance. The database files were copied over the network and located on a drive on the DBMS server.

Though, while I was trying to attach the databases I was getting an error message of the following type:

Msg 3415, Level 16, State 3, Line 1
Database [database_name] cannot be upgraded because it is read-only or has read-only files. Make the database or files writeable, and rerun recovery.
Msg 1813, Level 16, State 2, Line 1
Could not open new database [database_name]. CREATE DATABASE is aborted.

As the error message was saying, I checked the permissions of the database files and ensured that they were not read-only. Also, the service user account running the SQL Server instance had full access on the files.

As I did not have much time for fully troubleshooting the issue, I provided full access to "Everyone" on all the database files I wanted to attach, and tried again.

Guess what? It worked :)

After the databases were successfully attached, I removed the full access from the "Everyone" entity and so everything was back to normal!
Read more on this article...