Showing posts with label SQL Server Database Engine. Show all posts
Showing posts with label SQL Server Database Engine. Show all posts

Saturday, December 27, 2014

Could not find a log backup file that could be applied to secondary database

Error: Could not find a log backup file that could be applied to secondary database 'Database Name'.(Microsoft.SqlServer.Management.LogShipping) 
Error: The file 'F:\Database_Transaction_Log\Database_20130405231501.trn' is too recent to apply to the secondary database ‘Database Name'.(Microsoft.SqlServer.Management.LogShipping)
Error: The log in this backup set begins at LSN 2045263000000026000001, which is too recent to apply to the database. An earlier log backup that includes LSN 2045263000000023900001 can be restored. Searching for an older log backup file. Secondary Database: 'Database Name'

A few of my clients encountered this issue recently and needed help. Basically, they've setup Log Shipping on one of their production databases to copy transactions to a secondary server (for reporting purposes). The setup was working fine except for the fact that Log Sipping will break sporadically with the above error messages, and they had to ‘reset’ Log shipping to resolve the issue. Just by looking at the error message, I made a guess that this must be due to transaction log backups that are being performed “outside” of Log Shipping – in other words, I thought there must be a process separate from Log Shipping that is performing transaction log backups. The reason this is going to be an issue is because when applying/restoring transaction log backups on to the secondary server, Log Shipping is not going to be able find the log backup that was taken “outside” of Log Shipping – this means that there will be a ‘break’ in the chain/sequence of transaction log backups and hence a successful restore won't be possible. Below are three different scenarios I ran into with different clients.

Client/Scenario #1: This scenario was simple and it was easy to identify and resolve the issue: this client had a maintenance Job (outside of Log Shipping) that was backing up the transaction log on a regular basis. We simply disabled the maintenance job and the issue got resolved.

Client/Scenario #2: In this scenario, there was nothing within SQL Server and outside of Log Shipping that was backing up the transaction log. After a couple of discussions, I found out that they are using Avamar for backups and recovery purposes so I obviously wanted to know if they are using Avamar for transactions log backups. The answer was “No, We just do full backups”. But I wanted to confirm so we took a closer look at some of the settings in Avamar and found one that says “Force incremental backup after full backup” under the “Options” tab in the “Edit Dataset” window (shown in screenshot below). It sounded like this option does transactions log backups but to be 100% sure, we reached out to Avamar technical support and they confirmed that the setting below DOES transactions log backups. The support also said that if you include a database in Avamar’s backup plan, by default, it will perform transaction log backups as well (if the database is in FULL recovery model). 


Long story short, we deselected the option "Force incremental backup after full backup" so Avamar stopped performing  transaction log backups and Log Shipping continued to work without any issues.

Client/Scenario #3: This scenario is pretty much the same as that of Scenario #2, except that this client uses Veeam for backup and recovery. As in scenario #2, we explored some of the options in Veeam and found a similar setting (though not as obvious) called “Enable application-aware image processing” as shown in the screen shot below (the one on the left). Veeam technical support did confirm that this setting performs full as well as transaction log backups but if we just need to do full backups (without transactions log backups), we need to deselect the option “Backup logs periodically” under the advanced settings shown in the screen shot below on the right.


So we left the option “Enable application-aware image processing” selected but deselected “Backup logs periodically” and that took care of the issue with Log Shipping.

Even if you are not using Log Shipping, it is not a good idea to have two different process backup the transaction log of a given database as it can cause issues and confusion at the time restoring those backups. I hope this is helpful. If you've experienced this error and the reason/resolution was different than what I posted above, please leave a comment with your solution. Thanks.

Sunday, April 7, 2013

SQL Server restore error: Specified cast is not valid. (SqlManagerUI)

 I just encountered this error when restoring a SQL Server FULL backup file I got from one our clients - Specified cast is not valid. (SqlManagerUI)


This less-than-helpful error wasn't good enough for me to come to a conclusion so I decided to restore the database using a T-SQL command(Here is the command I used: RESTORE DATABASE CRM FROM DISK = 'E:\CRM.bak') and I got a different error which is shown below.

The media family on device 'E:\CRM.bak' is incorrectly formed. SQL Server cannot process this media family.  

The first thing that came to my mind after looking at the above error was that the backup file is corrupted. So I decided to verify using VERIFYONLY and HEADERONLY commands and below is the output.

  
The two observations above made me lean more towards believing that the backup file is corrupted or incomplete, BUT the issue turned out to be something else – The backup I got from our client was taken on  SQL Server 2012 instance and I was trying to restore it to SQL Server 2008R2. I had no idea about the version of SQL Server our client is using because they send us a backup file every quarter and we just restore it and generate audit reports for them.

I definitely think that the error message should have been more descriptive, but had it been so, I wouldn't have written this blog post. Hope this helps others.

Sunday, April 8, 2012

Start/Stop SQL Server from command line


You can using the following script to start/stop SQL Server services using command line:

SQL Server Database Engine(both SQL Server service and SQL Server Agent):
NET STOP SQLSERVERAGENT
NET STOP MSSQLSERVER
NET START MSSQLSERVER
NET START SQLSERVERAGENT

SQL Server Reporting Services:
NET STOP ReportServer
NET START ReportServer

SQL Server Analysis Services:
NET STOP MSSQLServerOLAPService
NET START MSSQLServerOLAPService

Friday, March 23, 2012

Integration Services and Analysis Services missing in Management Studio


If you don’t see Integration Services and Analysis Services  in SQL Server Management Studio in “connecting to server” dialog box, there could be one of the two reasons listed below: 

1. You are using SLQ Server  Management Studio Express(SSMSE). If so, please note that you can’t use SSMSE to manage SQL Server Analysis Services, Integration Services, Notification Services, Reporting Services, SQL Server Agent, or SQL Server 2005 Mobile Edition.
2. You only have “Management Tools - Basic” installed. To be able to connect to other services(Integration Services, Analysis Services  etc), you’ll need to have “Management Tools - Complete”. Just run the installation file again and select the option shown in the screen shot below to resolve this.


Sunday, February 26, 2012

How to enable xp_cmdshell?


The following script can be used to enable  xp_cmdshell 

EXECUTE SP_CONFIGURE 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO
EXECUTE SP_CONFIGURE 'xp_cmdshell', '1'
RECONFIGURE WITH OVERRIDE
GO
EXECUTE SP_CONFIGURE 'show advanced options', 0
RECONFIGURE WITH OVERRIDE
GO

Thursday, September 29, 2011

SQL Server Database Administration - FAQs


1. What does "breaking the continuity of transaction log" mean?
It basically means that you can't restore a sequence of log backups on top of restoring a full database backup, to recover a database to a point in time in the event of a disaster. The continuity of the transaction log will break when you clear the log without backing it up or when you switch from full recovery model to simple recovery model.
For example if you have a backup strategy where you do a full database backup every week (on Sunday night) and a transaction log backup every day . For some reason, you switched to simple recover model on Wednesday (around 10 am) and you changed the recovery model back to full after an hour. Unfortunately your server crashed on Friday. In this scenario, you will only be able to restore until Tuesday. Since the chain of transaction log backups was broken on Wednesday, all the log backups taken since then will be useless.
2. Does switching from full to Bulk recovery model break the continuity of the transaction log?
No it doesn't, but you need to backup the transaction log right before and right after you switch between full and bulk-logged recovery models.
3. Can I restore a SQL Server 2008 backup to a SQL Server 2005 server?
You can't restore a backup from a higher version of SQL Server on to a lower version of SQL Server. That being said, you can however, script the definition and data in SQL Server 2008(be sure to select the option Script for SQL Server 2005) and use the script to create your database back on SQL Server 2005.
4. What is tail of the log?
Transaction log backup taken after failure is called tail of the log. The tail of the log can be used to recover up to the point of failure.
5. Why is my transaction growing unexpectedly and how can I fix it?
This question is a little tough to answer without knowing more details, but one of the most common reasons for this unexpected growth is due to improper initialization of the transaction log file. Please read this excellent post by Kimberly Tripp for more details.
6. How is error handling done in SQL Server?
SQL Server provides the following functions/commands to help in troubleshooting Transact-SQL code:
  • @@ERROR function
  • @@ROWCOUNT function
  • RAISEERROR function
  • Try...Catch
For more details, refer the post Error Handling in SQL Server
7. Can I use bulk-logged model for a database that is setup for Database Mirroring?
Database Mirroring only supports full recovery model, so no.
8. What is the difference between Import Export Wizard and Copy Database Wizard?
The following post will help - Import Export vs Copy Database Wizard in SQL Server.
9. Can I use SQL Server Management Studio(SSMS) 2005 to connect to a SQL Server 2008 instance?
You'll need to install a Cumulative Update in order to connect to a 2008 instance using SQL Server 2005, without that, no.
10. What is the difference between a logical read and a physical read?
A logical read occurs when SQL Server finds the page it needs in the buffer cache. A physical read occurs when SQL Server doesn't find the page it needs in the buffer cache and so has to go to the disk to get it.
11. Will the database backup include all the transactions that occured during the backup process? If yes, how does SQL Server manage that?
Yes, a full database backup is an image of the entire database at the time at which the full backup completed. To accomplish this, SQL Server marks the log between the start of the backup and end of the backup and then applies those transactions to the backup.
12. What is Change Data Capture (CDC)?
Change Data Capture (CDC) tracks DML(Inserts, Updates, Deletes) and DDL(Create, Alter, Drop) activity on SQL Server tables. To store the information about the changes made to the tables being tracked, CDC creates change tables that have the same structure (columns) as that of the source tables plus a few more columns that are specific to CDC. CDC simply reads the transaction log to capture the changes made to the tables and then writes that information into the corresponding change tables. CDC is available on enterprise, developer and evaluation edition only. For more details, check this post - Change Data Capture in SQL Server 2008
13. To enable Change Data Capture (CDC), does the database need to be in full recovery model?
No, Change Data Capture (CDC) can work with any recovery model.
14. I have enabled Change Data Capture (CDC) on our database but nothing is being captured in the change tables. Is there anything that I need to check?
Change Data Capture (CDC) uses SQL Agent jobs to record and clean up data, check if SQL Agent is up and running.
15. Is point in time recovery possible with Bulk-logged recovery model?
With BULK_LOGGED recovery model, you won’t be able to do point in time recovery to any time within a transaction log backup containing at least one bulk-logged operation.
16. What is a covering index?
A covering index is one that has all the columns required to satisfy a query so that there is no need to perform a bookmark lookup (or key lookup) to find additional columns.
17. What is the difference between a clustered and a non-clustered Index?
The following post will help - Clustered Vs Nonclustered Index.
18. What is the use of Merge statement in SQL Server?
This is a new feature of SQL Server 2008 T-SQL language that lets you do INSERTs, UPDATEs, and DELETEs in a single SQL statement. For more details, refer the post Working with Merge in SQL Server 2008.
19. How can I upgrade an Evaluation Edition of SQL Server 2008 to any license edition?
The following post will help - SQL Server 2008 Evaluation Edition Upgrade.
20. How do you optimize a slow running query?
The following post will help - How to optimize a slow running query in SQL Server.
21. How often should I reboot my SQL Server? Should I schedule a reboot?
There is no need to reboot unless it’s really needed, example after Service Pack installations or when the Tempdb database is FULL.
22. How often should I rebuild my indexes?
As often as are required. The general rule of thumb is -
  • If the fragmentation level is over 30% - Rebuild the index.
  • If the fragmentation level is between 10% and 30% - Reorganize the index.
  • If the fragmentation level is below 10% - Don’t need to optimize do any index optimization.
To do this, you will have to automate index optimization. Here is one way to do it:
1. Create a loop to walk through all the tables.
2. Programmatically determine the level of fragmentation for each index.
3. Rebuild/Reorganize each index based on the level of fragmentation.
4. Wrap up all the above code in a Stored Procedure.
5. Create and schedule a job using the Stored Procedure created in step 4.
23. Is backup compression supported in SQL Server 2008 Standard Edition?
No, backup compression is only supported in Enterprise Edition. However every SQL Server 2008 Edition can restore a compressed backup.
23. What operations are minimally logged in Bulk-logged recovery model?
The following operations will be minimally logged:
  1. Bulk import operations (BCP, BULK INSERT,etc)
  2. SELECT INTO operations
  3. WRITETEXT and UPDATETEXT BLOB
  4. CREATE INDEX (this also includes indexed views)
  5. ALTER INDEX REBUILD or DBCC DBREINDEX
  6. DROP INDEX
To be continued...


SQL Server 2008 Upgrade - FAQs


1. Can I use Copy Database Wizard to upgrade my database from SQL server 2005 to SQL Server 2008?
Sure you can, in fact, this method is better than backup/restore as it allows you to copy related objects external to the database such as logins, sql agent jobs, stored procedures from master database etc.
2. Which is the best method to upgrade, an in-place upgrade or a side-by-side upgrade?
Please refer SQL Server in-place vs side-by-side upgrade for more details.
3. Can I do a cross-platform upgrade? I mean, can I upgrade from a 32 bit instance of SQL Server 2000/2005 to a 64 bit instance?
Yes you can, but only using a side-by-side upgrade. Upgrading from a 32 bit instance of SQL Server 2000/2005 to a 64 bit instance of SQL Server 2008 using in-place upgrade is not supported.
4. We are upgrading from SQL Server 2000/2005 to SQL Server 2008, can we upgrade to a different edition than the one we are currently on?
Yes you can, but only using a side-by-side upgrade. In-place upgrade does not support all the paths between editions, for example you can't upgrade from a standard edition of SQL server 2000/2005 to an enterprise edition of SQL server 2008.
5. Is there a way to find out what issues we are likely to encounter during upgrade?
Yes, use Upgrade Advisor to find out potential blocking issues that you might encounter during the upgrade process. You can download SQL Server 2008 Upgrade Advisor from here. Also, run the Best Practices Analyzer against your legacy instance of SQL Server to find out if there are any bad practices which you can address before the upgrade process. You can download the SQL Server 2005 Best Practices Analyzer here.
6. We are still on SQL Server 7.0. Can we upgrade directly to SQL Server 2008?
Yes you can, using a side-by-side upgrade. If you are doing an-inplace upgrade, you would have to first upgrade to SQL Server 2000 or SQL Server 2005, then upgrade to SQL Server 2008.
7. Can I restore a SQL Server 2008 backup to a SQL Server 2005 server?
You can't restore a backup from a higher version of SQL Server on to a lower version of SQL Server. That being said, you can however, script the definition and data in SQL Server 2008(be sure to select the option Script for SQL Server 2005) and use the script to create your database back on SQL Server 2005.
8. Can I use synchronize database wizard to upgrade an analysis services database from SSAS 2005 to 2008?
No, it is not possible to use the synchronize database wizard to synchronize data between SSAS 2005 and SSAS 2008. You can however, backup the analysis services 2005 database and restore it on SSAS 2008 to accomplish the same thing.
To be continued...

Policy-Based Management in SQL Server 2008


Policy-Based Management is one of the several nice features of SQL Server 2008. To explain how this feature is implemented, let me give you a real time scenario that I faced myself. The Manager I report to has been trying to implement naming standards across our firm. Two of his favorite naming standards are:
  • The names of all user stored procedure should begin with usp.
  • The names of all user created views should begin with Vwv.
Since a Manager doesn't have time to review all the code developed by every developer, it usually happens that Stored Procedures, Views, Functions etc written by developers get promoted to production even if the code is against the corporate naming standards. SQL Server 2008 makes it quite easy to handle such situations. You simply need to create policies with all your naming standards as conditions. That is it, its that simple. Let me walk you through the process of creating a policy. Lets create the first one - The names of all user stored procedure should begin with usp.
Connect to your SQL server 2008 instance, expand the Management folder, then expand the Policy Management folder, right-click the Policies folder and select New Policy as shown in the figure below.

The Create New Policy dialog box appears. Give an appropriate name for the policy and in the Check condition drop-down, select New Condition as shown in the figure below.

You can also select an existing condition that you have previously defined. (You can create a new condition by right-clicking the Conditions folder under Policy Management). Also, please note that you can only have one condition for a policy.
The Create New Condition dialog box appears as shown below. Type in an appropriate name for the condition, select Stored Procedure in the Facet drop-down and set the condition in the expression section as show in the figure below and click OK to return to the Create New Policy dialog box.

Your screen should look similar to the one shown in the figure below.

In the Against targets, you can either apply the condition to all the stored procedures or create a condition(by clicking the down arrow next to StoredProcedure) to apply it to only the required ones. The same applies to Database; you can apply the condition to stored procedures in all the database or create a condition to apply that to only the required ones.
In the Evaluation Mode drop-drown, you have 3 options to select:
  • on demand - Use this option to evaluate the policy as and when required by the user. To evaluate a policy, right-click the Policy folder and select Evaluate.
  • on schedule - Use this option to evaluate the policy automatically by creating a schedule using SQL Server Agent.
  • on change: log only - This option uses event notification to evaluate a policy whenever the policy is violated.
  • on change: prevent - This option automatically prevents the user from violating the policy. It uses DDL triggers behind the scenes.
In the Server restriction drop-down, you can select the servers that are appropriate for this policy by creating a condition or leave it as none to apply the policy to all servers.
Now lets try to create a stored procedure whose name doesn't begin with usp and see what happens.

As shown in the figure above, SQL Server prevented the creation of stored procedure since its violating the policy we just created.

Thursday, September 22, 2011

SQL Server 2008 Evaluation Edition Upgrade


Many folks think that it is not possible to upgrade from an Evaluation Edition of SQL Server 2008 to Enterprise/Standard/Developer Edition. They think that the only way is to uninstall the Evaluation Edition and then install the desired Edition of SQL Server. Well, that is simply not true. You can very well upgrade from Evaluation Edition to any licensed edition by running the setup file and selecting Edition Upgrade option underMaintenance. You might wonder, what if the evaluation period has expired? No problem, there is a work around: Just change the system date back to a date before the date of expiration of the software, and then do the upgrade. However, please note that SQL Server Management Studio and SQL Server Profiler tools will still complain with the following error message after the evaluation period of the original edition expires.
Evaluation period has expired. For information on how to upgrade your evaluation software please go to http://www.microsoft.com/sql/howtobuy (http://www.microsoft.com/sql/howtobuy)
There are two ways to fix the above error message:
1. Install Service Pack 1 before upgrading SQL Server 2008 evaluation edition to any licensed edition.

2. Modify Registry. Go to Start->Run->Regedit. In the Registry Editor, select the following keyHKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\100\ConfigurationState and change the value of the Common Files REG_DWORD to 3 as shown in the figure below.

After completing the registry changes, run the edition upgrade and you are done. For a list of supported version and Edition upgrades, check out the following:
http://msdn.microsoft.com/en-us/library/ms143393.aspx

BACKUP LOG WITH TRUNCATE_ONLY in SQL Server 2008

If you are using SQL Server 2008, you will notice that BACKUP LOG WITH TRUNCATE_ONLY has been thrown out. There are several reasons Microsoft decided to cut this command loose. First of all, BACKUP LOG WITH TRUNCATE_ONLY is a misnomer, it doesn't backup the log(as the name suggests), it clears the contents(inactive portion) of the transaction log without backing it up, breaking the chain of your log backups and the ability to do point in time recovery. So how do we truncate the log in SQL Server 2008 then? Simple, change the recovery model to simple, use DBCC SHRINKFILE to shrink the log file and switch the recovery model back to full. This solution is far better than what was offered in SQL Server 2005. Remember that the purpose of full recovery model is to let us perform point in time recovery, but by doing a TRUNCATE_ONLY, you loose that ability. So if your business doesn't care about point in time recovery, switch to simple recovery model. The fundamental point am trying to emphasize here is that full recovery model and BACKUP LOG WITH TRUNCATE_ONLY don't go together, which means executing TRUNCATE_ONLY command defeats the purpose of setting the database to full recovery model. Many Developers/DBAs (inadvertently) used this command only to know later that they broke the continuity of their transaction log backups. Hence you are required to switch the recovery model to simple so that you know what you are exactly doing.

Clustered Vs Nonclustered Index in SQL Server


Seeing this question asked so many times and at so many places, thought blogging about it would be a good idea.
The fundamental difference between a clustered index and a non-clustered index is in the structure. The leaf level of a cluster index is the base table data, sorted by the column on which the index is defined(known as cluster key). Think of clustered index as a phone book ordered by last name. Since the data in the table is sorted by the cluster key, there can only be ONE clustered index per table, though the index can include multiple columns(composite index).

On the other hand, the leaf level of a non-clustered index contains columns defined in the non-clustered key and a pointer back to the corresponding base table record. If the base table has a cluster index, then this pointer will be a cluster key of the base table record(logical RID). Also, in case the clustered index is non-unique, the non-clustered index will also include a column called uniquifier to locate a particular record if there are duplicate values. If the base table is a heap(no clustered index), then the pointer will be row ID of the corresponding base table record. Think of non-clustered index as the index at the back of a book. Unlike clustered indexes, you can have multiple non-clustered indexes(up to 249 in SQL Server 2005 and up to 999 in SQL server 2008) on a single table.

Wednesday, September 21, 2011

How to optimize a slow running query in SQL Server


As a database developer/administrator, you will often come across queries that take long time to execute. Here is what I would do when I am told to optimize a slow running query:
Analyze the query execution plan
First step in tuning the performance of a badly performing query is to take a look at the query execution plan. If an index is used to retrieve the result set, you will see Index Seek; if an index is not used, you will see Table Scan for a heap or a Clustered Index Scan in the case of an index-based table. Try adding appropriate indexes to the table being scanned, if you are not much familiar with the data model and the business needs, leverage Database Tuning adviser for appropriate index recommendations. However, if indexes already exist on the tables, try to find out why the indexes are not being used. If you see Clustered Index Scan, try to replace it with Index Seek by creating index on the most restrictive condition used in the query. Also, make sure that the indexes are not fragmented and the statistics on the tables are up to date. If the indexes are heavily fragmented or if statistics on the tables are not up to date, the optimizer will ignore the existing indexes and will likely generate a less efficient execution plan. You can find out index fragmentation using the
sys.dm_db_index_physical_stats Dynamic Management Function(DMF) and to analyze statistics on indexes, you can use DBCC SHOW_STATISTICS. If there are key lookup(also known as bookmark lookup) operations being performed, see if you can use a covering index to avoid key lookups. Key lookup requires access to both index pages and data pages and is a very expensive operation which might cause performance degradation, especially in the case of a large table.
Analyze and tune the query
Once you are done analyzing the query execution plan, the next step step will be to optimize the query itself. Try to rewrite the query in another way if you think it will help improve the performance. Here are some of the general guidelines that I follow:

  • 1. Operate on small result sets - Don't use "SELECT *", instead limit the number of columns by including only those columns that are required. Also, try to use a highly restrictive condition in the WHERE clause to only include the required data. In short, retrieve only the rows and columns that are needed.
  • 2. Avoid cursors - Avoid using cursors if you can, and try to use a Temp table with identity column to implement looping mechanism. I always create a temp table with an identity column and use a while loop to iterate over data sets.
  • 2. Avoid using arithmetic operators or functions on WHERE clause column - Using an arithmetic operator or functions on a WHERE clause column prevents the optimizer from choosing the index on the column. Also, try to avoid using exclusion conditions(example !=, NOT EXISTS, NOT IN, OR) in the WHERE clause. Exclusion conditions can force the optimizer to
    ignore indexes on the columns in the WHERE clause.
  • 4. Fully qualify Database objects - Always fully qualify database objects with the owner. This will reduce the overhead of name resolution and might also avoid execution plan recompiles.
  • 5. Avoid implicit datatype conversions in the query - Implicit conversions can prevent the indexes from being used by the optimizer and will also add overhead by costing extra CPU cycles for datatype conversions.
  • 6. Don't prefix stored procedure name with sp - Many Developers are used to prefixing stored procedure names with sp_. If a stored procedure having an sp_ prefix is executed, SQL Server always looks in the master database first to find the stored procedure. Also, let's say you have a stored procedure named sp_Test, if Microsoft decides to use this name, all the references to this stored procedure will break, so never begin the name of a SP with sp_.
  • 7. Use SET NOCOUNT - SQL Server sends messages(count of the number of rows affected) to the client after each T-SQL statement is executed. If you are using stored procedure, there is no need pass this information and using this option will turn off the messages that are sent back to the client. Though this is not a huge thing, it is definitely something to consider.

Error handling in SQL Server

SQL Server provides the following functions/commands to help in troubleshooting Transact-SQL code:
@@ERROR function
The @@ERROR function is  used to capture the number of an error generated by the previous Transact-SQL statement. A value of 0 indicates success. Though this function is quite handy, it is a little tricky because its value gets updated for every command. So you will have to save the value of this function to a variable to make use of it in the code.

@@ROWCOUNT function
The @@ROWCOUNT function returns the number of rows affected by the last Transact-SQL statement. Like the@@ERROR function, the value of @@ROWCOUNT gets updated for every command but can be captured in variable for use in the code.

RAISERROR function
This function can be used to return custom error messages when troubleshooting errors in Transact-SQL code. Here is the syntax:

RAISERROR (msg_ id or msg_str, severity, state, optional arguments) WITH option

  • msg_id - A user-defined error message number stored in the sys.messages .
  • message - A user-defined error message.
  • severity - The severity level associated with the message. The severity code used you’ll use most of the time will be 16 indicating critical error. Please note that 11 is the minimum severity that will cause a CATCH block to fire.
  • state - error state
  • Argument - Parameters used in the substitution for variables defined in msg_str  or the message corresponding to msg_id
  • WITH option - There are three values that can be used with this option:
  • LOG - Logs error in the error log and the application log
  • NOWAIT - Sends the message immediately to the client
  • SETERROR - Sets the @@ERROR value to msg_id or 50000
Example:

USE [TestDB]
CREATE PROCEDURE [dbo].[UpdateEmployees]
(
@DepartmentID INT,
@EmpID INT
)
AS
BEGIN
DECLARE @ErrorMsg INT
DECLARE @RecordCount INT
UPDATE dimEmployees SET DepartmentID = @DepartmentID WHERE EmpID = @EmpID
SELECT  @ErrorMsg = @@ERROR, @RecordCount = @@ROWCOUNT
IF (@ErrorMsg <> 0 OR @RecordCount = 0)
BEGIN
RAISERROR ('An error occured when updating the dimEmployees table',16,1)
END
END
Try...Catch:
Try Catch technique consists of a Try block which contains the code that might cause an exception and a Catch block where the control will be transferred if an error is encountered in the Try block. If there are statements in the TRY block that follow the  statement that caused the error, they will not be executed.


BEGIN TRY
{ SQL statements block }
END TRY
BEGIN CATCH
{ Error Handling Code }
END CATCH
Example:
BEGIN TRY
SELECT 1/0;
PRINT 'Statement after error'
END TRY
BEGIN CATCH
PRINT 'Divide by zero error'
END CATCH
And here is the output:
Divide by zero error

Isolation Levels in SQL Server


An Isolation Level controls how and when the changes made by one transaction are visible to other concurrent transactions. The following are the types of isolation levels in SQL Server.
Read Uncommitted - This isolation level ignores both read and write locks on resources when reading, but honors locks while modifying data to prevent other transactions from modifying the same data. This level is the least restrictive of all the isolation levels and allows dirty reads1, phantom reads2 and non-repeatable reads3.

Read Committed - Read Committed is the default isolation level in SQL Server. This isolation level places a shared lock on resources when reading and only reads committed data. Please note that locks are not held for the duration of the entire transaction and so there are chances that data can change before the end of the transaction. Though it prevents dirty reads, it allows phantom reads and non-repeatable reads.
Repeatable Read - This isolation level places a shared lock on resources (when reading) during the entire transaction thereby preventing other transactions from modifying the same data. This lock prevents non-repeatable reads but allows phantom reads. For example, let us say that a new record was inserted by another transaction after the current transaction has completed its first read. This new record could get included in later reads of the current transaction causing phantom reads.  Thought this isolation level prevents dirty reads and non-repeatable reads, it allows phantom reads.
Serializable - Serializable is similar to Repeatable Read, but it places a Key Range Lock preventing other transactions from modifying or inserting new rows until the transaction is committed or rolled back. This is the least concurrent of all the isolation levels and is the default isolation level in SQL Server Integration Services. This isolation doesn't prevents reads, phantom reads and non-repeatable reads.
Read Committed Snapshot (new since SQL Server 2005) - This is a variation of Read Committed isolation level which allows user to look at the data as it was during the beginning of the SELECT statement. To accomplish this, it implements row versioning by taking a copy of the row to be modified and storing it in tempdb. This means that shared locks are never placed on resource and read operations retrieve the recent committed copy of the data from version store (tempdb). In other words, readers do not block writers and writers do not block readers. This isolation doesn't allow dirty reads, phantom reads or non-repeatable reads.
Snapshot Isolation (new since SQL Server 2005) - Snapshot Isolation is similar to Read Committed Snapshot, but it is based at the transaction level unlike Read Committed Snapshot which is based at the statement level. Like Read Committed Snapshot, this isolation doesn't allow dirty reads, phantom reads or non-repeatable reads.
Please note that Isolation Levels only define how shared locks should behave, exclusive locks are not affected by changing isolation levels.
1. Dirty reads occur when a transaction reads data that is being modified by another transaction which is not yet committed. Since the changes have not been committed, there are chances that these changes might be rolled back and hence the reading operation is said to read "dirty" data.
2. Phantom reads occur when a transaction accesses a collection of rows more than once and another transaction inserts rows that happen to be in the range of rows retrieved by the first transaction causing first transaction to read more number of rows in future reads.
3. Non-repeatable reads occur when a transaction accesses a range of rows more than once and another transaction updates or deletes rows that fall in the range of rows retrieved by the first transaction so that the first transaction sees a different result set each time it retrieves data.

SQL Server Installtion Error

You might encounter this issue while installing SQL Server. The kind of error you will see depends on which component of SQL Server you are installing. For example, if you are installing all the three components, namely, SQL Server Database Engine, SQL Server Analysis Services, SQL Server Reporting Services, SQL Server Integration Services, you will see the following errors during the installation:



The credentials you provided for the SQL Server Agent service are not valid. To continue, provide a valid account and password for the SQL Server Agent service.
The credentials you provided for the SQL Server service are not valid. To continue, provide a valid account and password for the SQL Server service.
The credentials you provided for the Reporting Services service are not valid. To continue, provide a valid account and password for the Reporting Services service
The credentials you provided for the Analysis Services service are not valid. To continue, provide a valid account and password for the Analysis Services service.
Reason – You can’t specify a domain account for Services while being logged in using a non-domain account. In other words, you’ll need to be logged into the machine using a domain account if you want to specify a domain account for the Services. Yes, even the native Administrator account of the machine won’t help if it’s not a domain account. Alternatively, you can specify a local account for the services during installation and later change it to a domain account using SQL Server Configuration Manager. Hope this helps.


Saturday, September 3, 2011

SQL Server general best practices



1. Isolate OS, SQL binaries and Data/Log files.

If possible, do not install SQL Server or any other application on C drive and be sure to isolate OS and SQL Server data/log files by having them on different physical drives. Never place data and transaction log files on the same physical disk. Here is an example configuration that will help avoid contention issues:

  • C: Operating System
  • D: SQL Server (or any other application)
  • E: SQL Server Log Files
  • F: SQL Server Data Files

2. Use the principle of least privilege and reduce the surface area of attack

Two general (but important) rules of security are:

  • Reduce the surface area of attack - This means installing only the REQUIRED components/features and disabling the ones that are not needed immediately. This will improve security by reducing the surface area of attack.
  • Use the principle of least privilege – This means granting just enough permissions to users and service accounts to do the job. Granting unnecessary elevated rights will increase the risk of both intentional and accidental damage to the system resources.
Also, ensure the physical security of each SQL Server instance, by preventing any unauthorized users to physically access the servers.

3. Use a dedicated domain account for SQL Server services

For service accounts, use a dedicated user account or domain account having just enough privileges needed to do the job (principle of least privilege). By dedicated I mean the account should not be used by any other service on the same server. Also, use a separate account for each service so that if one service account gets compromised then only one instance associated with the service will be damaged.


4. Leverage Instant File Initialization 

When SQL Server service is granted the right "Perform Volume Maintenance Tasks", SQL Server will perform file allocation "instantly" by skipping zero initialization. Zero Initialization is the process of filling the contents of a file with zeros. Therefore, whenever a file allocation request is made, SQL Server will claim disk space by overwriting the disk content instead of filling it with zeros. This will save a lot of time during database creation, restore, auto-growth events etc.
The reason why this privilege is not granted by default is because the requested disk space might contain sensitive information which can be accessed using the (undocumented) DBCC PAGE command.


Note1:Only data files can leverage this feature as log files cannot be initialized instantaneously (due to architectural reasons).

Note2: Instant file initialization is available only on Microsoft Windows XP, Windows Server 2003, or later systems.


5. Use SQL Server Configuration Manager (SSCM) to change service accounts

If you ever need to change the service account for SQL Server service or SQL Server Agent service for that matter, use SQL Server Configuration Manager. Though you can also use Services (Administrative Tools->Services) to accomplish the same thing, the recommended method is to use SQL Server Configuration Manager because SQL Server Configuration Manager will automatically grant all the required permissions and rights to the new account. If you use the Services add-in to change service account, you might have to add some additional permissions and rights to the new account manually.


6 Divide tempdb into as many files as your processors

Split tempdb into multiple data files of equal size and these multiple files need not be on different disks/spindles (unless there are I/O bottlenecks). The number of data files should be equal to the number of processors (physical or virtual) on the machine. Since SQL Server allows only one active worker on each scheduler at any given time, all the active workers trying to access tempdb at the same time will be logically split to a separate file in tempdb decreasing contention.

However, if you have memory-intensive work loads, writing out of the spilled data can be slow due to thread synchronization. In this case, the number of data files could be ½ or ¼ of the number of CPUs.

7. Configure default database properties using model database

Use model database to set common properties (recovery model, initial file size, auto-growth etc) across all the databases on your SQL Server instance. For example, on a test server you might want to set the recovery model to simple so that all the new databases created on this instance inherit this property.


8. Use Widows authentication, if possible

Unless the SQL Server instance is being used for applications that can’t work with Windows, don’t go for Mixed Mode authentication. If you do, make sure you choose a strong SA password and enforce strong password policies for all SQL Server logins. In case of windows authentication, change the random password created for the ‘sa’ account after the installation is complete. Windows authentication is more flexible as you can setup your domain policies for changing user's login and lockouts to apply automatically for SQL Server.


9. Use simple recovery model whenever appropriate

Recovery model needs to be business owner’s decision. Don’t be reluctant to use simple recovery model for your databases whenever suitable. It is totally fine to have a production database in simple recovery model as long as the users/business understand the implications. The benefit of having a database in simple recovery model (when appropriate) is that you don’t have to manage transaction logs as the inactive portion of the log will be cleared after check point. If the recovery model is set to full, be sure to schedule log backups. The frequency of which should be decided by business owners.


10. Allocate data/log files to a reasonable initial size and avoid using percentage for growth

Be sure that the database files and log files are large enough so that they will not automatically grow during normal daily operations (causing the users/processes to wait as it is a very slow process). Don’t use percentage for auto-growth, instead monitor and grow your files manually and use auto-growth only to deal with expected growth. Also, grow your databases by substantial amount, otherwise, you will end up with too many Virtual Log Files (VLFs) causing fragmentation.

11. T-SQL best practices
i. Do NOT use sp_xxx as a naming convention as this causes additional searches and added I/O. SQL Server will scan the procedure cache for Master, no matter what database it was executed from. SQL Server will then acquire an exclusive COMPILE lock to perform a second search in the local database. If a user stored procedure has same name as an sp_xxx stored procedure in MASTER, that user procedure will NEVER be used.
ii. Use SET NOCOUNT when creating Stored Procedures. SQL Server sends messages to the client after each T-SQL statement is executed. This option will turn off the messages that are sent back to the client.iii. Avoid using arithmetic operators/functions on WHERE clause column. This prevents optimizer from choosing index on the column.
iv. Fully qualify Database objects - This will reduce name resolution overhead, might avoid execution plan recompiles.
v. Operate on small result sets; don’t use “SELECT *”, and try to include a highly selective filter in the where clause if possible.

12. Use T-SQL for creating maintenance plans

Use T-SQL for maintenance plans as opposed to using the maintenance plan wizard/designer as T-SQL offers more granularity and flexibility. For example, using the wizard, there is no way to determine when to rebuild and when to reorganize an index. By using T-SQL, you can programmatically determine the level of fragmentation in an index and rebuild/reorganize the index based on the fragmentation. It may even be the case that you don’t have any fragmentation and so you don’t need to do anything. Also, don’t forget to include system databases in your maintenance plan. The system databases, master msdb and model should be backed up weekly or at least monthly.