319
9 Jan 01, 2007-431 Dec 31, 2007 SQL SERVER – Remove Duplicate Characters From a String Follow up of my previous article of Remove Duplicate Chars From String here is another great article written by Madhivanan where similar solution is suggested with alternate method of Number table approach. Check out Remove duplicate characters from a string SQL SERVER – Change Password of SA Login Using Management Studio Login into SQL Server using Windows Authentication. In Object Explorer, open Security folder, open Logins folder. Right Click on SA account and go to Properties. Change SA password, and confirm it. Click OK.

9 Jan 01, 2007-431 Dec 31, 2007

  • Upload
    rashmihr

  • View
    1.204

  • Download
    10

Embed Size (px)

Citation preview

Page 1: 9 Jan 01, 2007-431 Dec 31, 2007

9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Remove Duplicate Characters From a String

Follow up of my previous article of Remove Duplicate Chars From String here is another great article written by Madhivanan where similar solution is suggested with alternate method of Number table approach. Check out Remove duplicate characters from a string

SQL SERVER – Change Password of SA Login Using Management Studio

Login into SQL Server using Windows Authentication.

In Object Explorer, open Security folder, open Logins folder. Right Click on SA account and go to Properties.

Change SA password, and confirm it. Click OK.

Page 2: 9 Jan 01, 2007-431 Dec 31, 2007

Make sure to restart the SQL Server and all its services and test new password by log into system using SA login and new password.

SQL SERVER – Difference Between Quality Assurance and Quality Control – QA vs QC

Regular readers of this blog are aware of my current outsourcing assignment. I am managing very large outsourcing project in India. One thing is very special in all Indian offices is “Tea Time.” Everybody wants to attend Tea Time not only for tea or coffee but for the interesting discussion occurs at that time. This is the time when all the department employees are together and discussing whatever they wish.

Today there was interesting discussion about Quality Assurance (QA) and Quality Control (QC). It is very interesting to know that these two similar sounding words are very different in practice. QA is process oriented and QC is product oriented. The goal of QA as well as QC is to deliver quality product. Many of developers did not know the difference between this two important roles in project development.

Quality Assurance: A set of activities designed to ensure that the development and/or maintenance process is adequate to ensure a system will meet its objectives.Example : project audits , process checklists

Quality Control: A set of activities designed to evaluate a developed work product.Example : testing the process

Let me know your thoughts about this post. Let me know if you want me to write more articles like this one.

SQLAuthority News – Book Review – A Practitioner’s Guide to Software Test Design

Page 3: 9 Jan 01, 2007-431 Dec 31, 2007

A Practitioner’s Guide to Software Test Design (Hardcover)by Lee Copeland (Author)

Link to Amazon (This is not affiliate Link)

Short Summary:A Practitioner’s Guide to Software Test Design is one book containing all the important latest test design approaches. This book makes life of software tester very easy. Software tester can find all the information in this book instead of searching through hundreds of books, periodicals and websites.

Detail Summary:In large system it is very important to choose test cases as well carefully find defect which can result in significant losses to organization. A Practitioner’s Guide to Software Test Design is one book which only focuses on software test design. This book avoids all the distractions of less important topics such as test planning, test management, test team developments etc and focuses on core concept of software test design. This book contains detailed examples and step by step instructions about how to design efficient test designs.

Some of the techniques used in this book are classics and well known throughout the testing and developing community. Many of the techniques are not widely used but should be more in practice as they are very effective as well. The balance of breadth and depth of all this techniques makes this one book must read by all software testers.

Each test design technique is approached from practical view point as well it contains important theories along with it. Simple example following with in depth details is what makes this book a true page turner for readers. Each chapter contains summary of its key points, exercises and references. A typical user of this book will be able to start on project right after reading this book.

What makes this book a must read is it’s extremely fluid and interesting methods to explain concepts. Author gets his point through using humor in many areas. Let us see one example from Chapter 16th – When to Stop Testing.

When to stop testing:You have met previously defined coverage goalsThe defect discovery rate has dropped below a previously defined thresholdThe marginal cost of finding the “next” defect exceeds the expected loss from that defectThe project team reaches consensus that it is appropriate to release the productThe boss says, “Ship it!”

Rating: 5 Starts

Page 4: 9 Jan 01, 2007-431 Dec 31, 2007

Summary:This book very well achieves what its goal is about analyze, design and choose such subsets, to implement those tests that are most likely to discover defects and help identify potential pitfalls.

SQL SERVER – FIX : ERROR Msg 1803 The CREATE DATABASE statement failed. The primary file must be at least 2 MB to accommodate a copy of the model database

Following error occurs when database which is attempted to be created is smaller than Model Database. It is must that all the databases are larger than Model database and 512KB.

Following code will create the error discussed in this post.CREATE DATABASE TestsON( NAME = 'Tests',FILENAME = 'c:\tests.mdf',SIZE = 512KB )GO

Msg 1803, Level 16, State 1, Line 1The CREATE DATABASE statement failed. The primary file must be at least 2 MB to accommodate a copy of the model database.

Fix/WorkAround/Solution :Create database which is larger than Model database and 512KB. Size of the Model Database will be displayed in the error message. If database is smaller than 512 KB it will throw error which I have described here : SQL SERVER – FIX : ERROR Msg 5174 Each file size must be greater than or equal to 512 KB

SQL SERVER – DBCC CHECKDB Introduction and Explanation – DBCC CHECKDB Errors Solution

DBCC CHECKDB checks the logical and physical integrity of all the objects in the specified database. If DBCC CHECKDB ran on database user should not run DBCC CHECKALLOC, DBCC CHECKTABLE, and DBCC CHECKCATALOG on database as DBCC CHECKDB includes all the three command. Usage of these included DBCC commands is listed below.

DBCC CHECKALLOC – Checks the consistency of disk space allocation structures for a specified database.

DBCC CHECKTABLE – Checks the integrity of all the pages and structures that make up the table or indexed view.

DBCC CHECKCATALOG – Checks for catalog consistency within the specified database. The database must be online.

Along with above three DBCC commands it also runs following two tasks to check the validity database (physical as well logical) i.e. validates the contents of every indexed view in the database and Validates the Service Broker data in the database.

If database DBCC check has returned any errors, the best solution is to RESTORE DATABASE from BACKUP. (Additional reading : SQL Backup and Restore). There is additional keyword REPAIR with DBCC CHECKDB which can be used to repair database but it is not recommended. I will write additional articles on this subject.

SQL SERVER – TRUNCATE Can’t be Rolled Back Using Log Files After Transaction Session Is Closed

You might have listened and read either of following sentence many many times.

“DELETE can be rolled back and TRUNCATE can not be rolled back”.

OR

Page 5: 9 Jan 01, 2007-431 Dec 31, 2007

“DELETE can be rolled back as well as TRUNCATE can be rolled back”.

As soon as above sentence is completed, someone will object it saying either TRUNCATE can be or can not be rolled back. Let us make sure that we understand this today, in simple words without talking about theory in depth.

While database is in full recovery mode, it can rollback any changes done by DELETE using Log files. TRUNCATE can not be rolled back using log files in full recovery mode.

DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION if the current session is not closed. If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if session is closed, it can not be rolled back but DELETE can be rolled back.

Let us understand this concept in detail.

In case of DELETE, SQL Server removes all the rows from table and records them in Log file in case it is needed to rollback in future. Due to that reason it is slow.

In case of TRUNCATE, SQL Server deallocates the data files in the table and records deallocation of the data files in the log files. If deallocated data files are overwritten by other data it can be recovered using rollback. There is no guarantee of the rollback in case of TRUNCATE. However, while using T-SQL following code demonstrates that TRUNCATE can be rolled back for that particular session.

First create test table which some data. Afterwards run following T-SQL code in Query Editor and test the effect of TRUNCATE on created test table.BEGIN TRANTRUNCATE TABLE TestTable-- Following SELECT will return TestTable emptySELECT *FROM TestTable-- Following SELECT will return TestTable with original dataROLLBACKSELECT *FROM TestTableSummary : DELETE can be recovered from log file always if full recovery mode is set for database. TRUNCATE may or may not be recovered always from log files.

SQL SERVER – Mirrored Backup Introduction and Explanation

SQL Server 2005 Enterprise Edition and Development Edition supports mirrored backup. Mirroring a media set increases backup reliability by adding redundancy of backup media which effectively reduces the impact of backup-device failing. While taking backup of database, same backup is taken on multiple media or locations.

T-SQL code to take Mirrored Backup :

BACKUP DATABASE AdventureWorksTO DISK = 'c:\AdventureWorksBackup.bak'MIRRORTO DISK = 'd:\AdventureWorksBackupCopy.bak'WITH FORMAT;

Above script will create two backups at two different locations, if backup of one location is corrupted backup from another location will work fine.

SQL SERVER – Delete Duplicate Records – Count Duplicate Records Links

I have wrote following two articles for Duplicate Rows Management in SQL Server.

SQL SERVER – Count Duplicate Records – Rows

Page 6: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Delete Duplicate Records – Rows

SQL SERVER – Object Oriented Database Management Systems

I have received few emails and comments about why I do not write about Object Oriented Database Management Systems (OODBMS). The reason for that is that I am big follower of Relational Database Management Systems (RDBMS) and that particularly of Microsoft SQL Server. If you are interested in reading about OODBMS, I have came across one interesting article, which I can share here.

Visit : AN EXPLORATION OF OBJECT ORIENTED DATABASE MANAGEMENT SYSTEMS by Dare Obasanjo

The purpose of above mentioned paper is to provide answers to the following questions

What is an Object Oriented Database Management System (OODBMS)? Is an OODBMS a viable alternative to an RDBMS? What are the tradeoffs and benefits of using an OODBMS over an RDBMS? What does code that interacts with an OODBMS look like?

If above link is not working due to any reason, please contact me.

SQLAuthority News – Download Microsoft SQL Server 2000/2005 Management Pack

Note: Download Microsoft SQL Server 2000/2005 Management Pack by Microsoft

The SQL Server Management Pack monitors the availability and performance of SQL Server 2000 and 2005 and can issue alerts for configuration problems. Availability and performance monitoring is done using synthetic transactions. In addition, the Management Pack collects Event Log alerts and provides associated knowledge articles with additional user details, possible causes, and suggested resolutions. The Management Pack discovers Database Engines, Database Instances, and Databases and can optionally discover Database File and Database File Group objects.

Feature Summary:

Active Directory Helper Service SQL Server Agent Backup Databases and Tables DBCC Full Text Search Log Shipping Clustering DB availability Replication monitoring Agent jobs Backup Query Engine Replication Web Assistant SQL XML

Download Microsoft SQL Server 2000/2005 Management Pack

Abstract courtesy : Microsoft

SQLAuthority News – Jobs, Search, Best Articles, Homepage

If you are looking for solution of any of your question : Search SQLAuthority

If you are looking for best job in IT field : Find Job or email [email protected]

Page 7: 9 Jan 01, 2007-431 Dec 31, 2007

If you are looking for talented IT professional : Post Job or email [email protected]

If you want to read my personally selected articles : Best Articles

If you want to know more about me : pinaldave.com

If you want to subscribe to my blog : Email or Feed

SQL SERVER – 2008 – New DataTypes DATE and TIME

One of our project manager asked me why SQL Server does not have only DATE or TIME datatypes? I thought his question is very valid, he is not DBA however he understands the RDBMS concepts very well. I find his question very interesting. I told him that there are ways to do that in SQL Server 2005 and earlier versions. He asked me but if there are DATE and TIME datatypes not DATETIME combined.

This question we all DBA had for many years and we all wanted DATE and TIME separate datatypes then DATETIME combined. Microsoft has incorporated this feature in SQL Server 2008. It supports many new DATETIME datatypes. Today we will see DATE and TIME specifically.

DATE datatype Explanation

SQL SERVER 2005:DECLARE @Date AS DATETIMESET @Date = GETDATE()SELECT @Date OriginalDate, CONVERT(VARCHAR(10),@Date,111) CastDate

ResultSet:OriginalDate CastDate———————– ———-2007-12-22 17:48:14.640 2007/12/22

SQL SERVER 2008:DECLARE @Date AS DATESET @Date = GETDATE()SELECT @Date OriginalDate

ResultSet:OriginalDate———————–2007-12-22

TIME datatype Explanation

SQL SERVER 2005:DECLARE @Time AS DATETIMESET @Time = GETDATE()SELECT @Time OriginalTime, CONVERT(VARCHAR(10),@Time,108) CastTime

ResultSet:OriginalTime CastTime———————– ———-2007-12-22 17:48:57.200 17:48:57

SQL SERVER 2008:DECLARE @Time AS TIMESET @Time = GETDATE()SELECT @Time OriginalTime

ResultSet:OriginalTime

Page 8: 9 Jan 01, 2007-431 Dec 31, 2007

———————–17:48:57.2000000

SQL SERVER – Difference Between Index Rebuild and Index Reorganize Explained with T-SQL Script

Index Rebuild : This process drops the existing Index and Recreates the index.USE AdventureWorks;GOALTER INDEX ALL ON Production.Product REBUILDGO

Index Reorganize : This process physically reorganizes the leaf nodes of the index.USE AdventureWorks;GOALTER INDEX ALL ON Production.Product REORGANIZEGO

Recommendation: Index should be rebuild when index fragmentation is great than 40%. Index should be reorganized when index fragmentation is between 10% to 40%. Index rebuilding process uses more CPU and it locks the database resources. SQL Server development version and Enterprise version has option ONLINE, which can be turned on when Index is rebuilt. ONLINE option will keep index available during the rebuilding.

SQL SERVER – Enabling Clustered and Non-Clustered Indexes – Interesting Fact

While playing with Indexes I have found following interesting fact. I did some necessary tests to verify that it is true.

When a clustered index is disabled, all the nonclustered indexes on the same tables are auto disabled as well. User do not need to disable non-clustered index separately. However, when clustered index is enabled, it does not automatically enable nonclustered index. All the nonclustered indexes needs to be enabled individually. I wondered if there is any short cut to enable all the indexes together. Index rebuilding came to my mind instantly. I ran T-SQL command of rebuilding all the indexes and it enabled all the indexes on table.

This was very intriguing to me, as I never faced this kind of situation before. Everyday there is something new in SQL Server and that what makes life of DBA refreshing.

T-SQL to rebuild all the indexes on table.USE AdventureWorks;GOALTER INDEX ALL ON Production.Product REBUILDGO

Rebuild All Indexes using SQL Server Management Studio.

Expand AdventureWorks Database, Expand Production.Product Database, Expand Index Group

Page 9: 9 Jan 01, 2007-431 Dec 31, 2007

Right click on Indexes and select Rebuild All

SQL SERVER – DISTINCT Keyword Usage and Common Discussion

Jr. DBA asked me a day ago, how to apply DISTINCT keyword to only first column of SELECT. When asked for additional information about question, he showed me following query.

SELECT Roles, FirstName, LastNameFROM UserNamesHe wanted to apply DISTINCT to only Roles and not across FirstName and LastName. When he finished I

Page 10: 9 Jan 01, 2007-431 Dec 31, 2007

realize that it is not possible and there is logical error in thinking query like that. I helped him with what he needed however, after he left I realize that answer to his original question was “NO”.

Distinct can not be applied to only few columns it is always applied to whole column. In following exam DISTINCT is applied across Roles, FirstName and LastName.

SELECT DISTINCT Roles, FirstName, LastNameFROM UserNames

Same result as above query can be achieved by using GROUP BY as well.

SELECT Roles, FirstName, LastNameFROM UserNamesGROUP BY Roles, FirstName, LastName

Before I end discussion I would like to add that DISTINCT can be used with aggregated functions and can be applied on only one field in that case. Following example demonstrates that scenario.

SELECT MAX(DISTNCT ID), Roles, FirstName, LastNameFROM UserNames, LastName

This subject is very interesting and I decided to search online if any other writers has explained this in depth. I found following good article written by Jeff Smith. He has explained this example in depth so I have skipped explaining similar example in depth.

SQL SERVER – Cumulative Update Package 5 for SQL Server 2005 Service Pack 2

Microsoft SQL Server 2005 hotfixes are created for specific SQL Server service packs. You must apply a SQL Server 2005 Service Pack 2 hotfix to an installation of SQL Server 2005 Service Pack 2. By default, any hotfix that is provided in a SQL Server service pack is included in the next SQL Server service pack.

Cumulative Update 5 contains hotfixes for SQL Server 2005 issues that have been fixed since the release of Service Pack 2.

Latest Build 3215.

Download Information

SQLAuthority News – RML Utilities for SQL Server

The RML utilities allow you to process SQL Server trace files and view reports showing how SQL Server is performing. For example, you can quickly see:

Which application, database or login is using the most resources, and which queries are responsible for that

Whether there were any plan changes for a batch during the time when the trace was captured and how each of those plans performed

What queries are running slower in today’s data compared to a previous set of data

Download RML Utilities for SQL Server (x86)

Download RML Utilities for SQL Server (x64)

SQL SERVER – Get Information of Index of Tables and Indexed Columns

Knowledge of T-SQL inbuilt functions and store procedure can save great amount of time for developers. Following is very simple store procedure which can display name of Indexes and the columns on which indexes are created. Very handy stored Procedure.USE AdventureWorks;GOEXEC sp_helpindex 'Person.Address'

Page 11: 9 Jan 01, 2007-431 Dec 31, 2007

GO

Above SP will return following information.IndexName – IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCodeIndex_Description – nonclustered, unique located on PRIMARYIndex_Keys – AddressLine1, AddressLine2, City, StateProvinceID, PostalCode

Let me know if you think this kind of small tips are useful to you.

SQL SERVER – T-SQL Script to Find Details About TempDB

Two days ago I wrote article about SQL SERVER – TempDB Restrictions – Temp Database Restrictions. Since then I have received few emails asking details about TempDB. I use following T-SQL Script to know details about my TempDB. I have found this script from MSDN site. I have mentioned original source link in reference at the end of this article.SELECTname AS FileName,size*1.0/128 AS FileSizeinMB,CASE max_sizeWHEN 0 THEN 'Autogrowth is off.'WHEN -1 THEN 'Autogrowth is on.'ELSE 'Log file will grow to a maximum size of 2 TB.'END AutogrowthStatus,growth AS 'GrowthValue','GrowthIncrement' =CASEWHEN growth = 0 THEN 'Size is fixed and will not grow.'WHEN growth > 0AND is_percent_growth = 0THEN 'Growth value is in 8-KB pages.'ELSE 'Growth value is a percentage.'ENDFROM tempdb.sys.database_files;GO

Above script will return following result set.

FileName FileSizeinMB AutogrowthStatus GrowthValue GrowthIncrementtempdev 8 Autogrowth is on. 10 Growth value is a percentage.templog 0.5 Autogrowth is on. 10 Growth value is a percentage.

SQL SERVER – Solution – Log File Very Large – Log Full

I have been receiving following question again and again either through email or through comments on this blog.

My log file is too big, what should I do?

Answer to this question is in three steps.

Backup the log file to any device. Truncate the log file. Shrink the log file.

I have previously written two article about this issue. Refer them for additional information and details.

SQL SERVER – Shrinking Truncate Log File – Log Full(Script)

SQL SERVER – Shrinking Truncate Log File – Log Full – Part 2(Management Studio)

SQL SERVER – TempDB Restrictions – Temp Database Restrictions

Page 12: 9 Jan 01, 2007-431 Dec 31, 2007

While conducting Interview for my outsourcing project, I asked one question to interviewer that what are the restrictions on TempDB? Candidate was not able to answer the question. I thought it would be good for all my readers to know answer to this question so if you face this question in interview or if you meet me in interview you will be able to answer this question.

Adding filegroups. Backing up or restoring the database. Changing collation. The default collation is the server collation. Changing the database owner. tempdb is owned by dbo. Creating a database snapshot. Dropping the database. Dropping the guest user from the database. Participating in database mirroring. Removing the primary filegroup, primary data file, or log file. Renaming the database or primary filegroup. Running DBCC CHECKALLOC. Running DBCC CHECKCATALOG. Setting the database to OFFLINE. Setting the database or primary filegroup to READ_ONLY.

SQLAuthority News – Top 10 Tips for Successful Software Outsourcing

Few days ago, I wrote article about SQLAuthority Author Visit – IT Outsourcing to India – Top 10 Reasons Companies Outsource. I received quite a few emails regarding this article. I was really impressed that how much vendors care about their reputation and their client. I received so many requests from my blog readers who are interested in learning how to be successful at Software Outsourcing. I decided to write top 10 tips for the same. I have not described them in depth as they are pretty self explanatory.

1. Define the scope of project clearly and as much as detail it can be.2. Define the schedule for project and expected milestones.3. Look for the domain knowledge experience in service provider.4. Think outsourcing as resource rather then cost saving tool.5. Review portfolios and samples as well as references.6. Start with small or medium size project which can justify the service providers expertize.7. Define the ownership of the work before project starts.8. Always plan for project maintenance and after project support.9. Pay regularly and swiftly when service provider reaches pre-defined milestone on time.10. Always ask for legal agreement and knowledge transfer documentation.

These are basic top 10 tips one should keep in mind when starting software outsourcing. If you have any more tips please add them here as comment. I am very interested to know what all of you think about this topic.

SQL SERVER – Do Not Store Images in Database – Store Location of Images (URL)

Just a day ago I received phone call from my friend in Bangalore. He asked me

What do I think of storing images in database and what kind of datatype he should use?

I have very strong opinion about this issue.

I suggest to store the location of the images in the database using VARCHAR datatype instead of any BLOB or other binary datatype.

Storing the database location reduces the size of database greatly as well updating or replacing the image are much simpler as it is just an file operation instead of massive update/insert/delete in database.

SQL SERVER – White Papers: Migration from Oracle Sybase, or Microsoft Access to Microsoft SQL Server

Page 13: 9 Jan 01, 2007-431 Dec 31, 2007

Guide to Migrating from Oracle to SQL Server 2005This white paper explores challenges that arise when you migrate from an Oracle 7.3 database or later to SQL Server 2005. It describes the implementation differences of database objects, SQL dialects, and procedural code between the two platforms. The entire migration process using SQL Server Migration Assistant for Oracle (SSMA Oracle) is explained in depth, with a special focus on converting database objects and PL/SQL code.

Guide to Migrating from Sybase ASE to SQL Server 2005This white paper covers known issues for migrating Sybase Adaptive Server Enterprise database to SQL Server 2005. Instructions for handling the differences between the two platforms are included. The paper describes how SQL Server Migration Assistant for Sybase, the best tool for this type of migration, can help resolve various migration issues.

Guide to Migrating from Microsoft Access to SQL Server 2005This white paper covers migrating Microsoft Access databases to SQL Server 2005 and discusses the differences between the two platforms. SQL Server Migration Assistant for Access (SSMA Access) is the best tool for this type of migration; this paper tells you how to use it to mitigate potential problems in database conversion. For additional information, also see the white paper Microsoft Access or SQL Server 2005: What’s Right in Your Organization?

Download White Papers

SQL SERVER – Microsoft Synchronization Services for ADO.NET v2.0 CTP1 Refresh

Microsoft Synchronization Services for ADO.NET provides the ability to synchronize data from disparate sources over two-tier, N-tier, and service-based architectures. Rather than simply replicating a database and its schema, the Synchronization Services application programming interface (API) provides a set of components to synchronize data between data services and a local store. Applications are increasingly used on mobile clients, such as laptops and devices, that do not have a consistent or reliable network connection to a central server. It is crucial for these applications to work against a local copy of data on the client. Equally important is the need to synchronize the local copy of the data with a central server when a network connection is available. The Synchronization Services API, which is modeled after the ADO.NET data access APIs, gives you an intuitive way to synchronize data. It makes building applications for occasionally connected environments a logical extension of building applications where you can count on a consistent network connection.

Download here.

SQLAuthority News – Microsoft SQL Server 2008 Community Technology Preview (November 2007) VHD

SQL Server 2008, the next release of Microsoft SQL Server, will provide a comprehensive data platform that is more secure, reliable, manageable and scalable for your mission critical applications, while enabling developers to create new applications that can store and consume any type of data on any device, and enabling all your users to make informed decisions with relevant insights. This download comes as a pre-configured VHD. This allows you to trial SQL Server 2008 CTP in a virtual environment.

Download from here.

SQL SERVER – ACID (Atomicity, Consistency, Isolation, Durability)

ACID (an acronymn for Atomicity Consistency Isolation Durability) is a concept that Database Professionals generally look for when evaluating databases and application architectures. For a reliable database all this four attributes should be achieved.

Atomicity is an all-or-none proposition.

Consistency guarantees that a transaction never leaves your database in a half-finished state.

Isolation keeps transactions separated from each other until they’re finished.

Page 14: 9 Jan 01, 2007-431 Dec 31, 2007

Durability guarantees that the database will keep track of pending changes in such a way that the server can recover from an abnormal termination.

Above four rules are very important for any developers dealing with databases.

SQL SERVER – Generic Architecture Image

Just a day ago, while I was surfing wikipedia about SQL Server, I came across this generic architecture image. I found it interesting. Click on image to view it in large size.

Page 15: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – FIX : Error : 3702 Cannot drop database because it is currently in use.

Msg 3702, Level 16, State 3, Line 2Cannot drop database “DataBaseName” because it is currently in use.

This is very generic error when DROP Database is command is executed and database is not dropped. The common mistake user does is keep the connection open with this database and trying to drop the database.

Following commands will raise above error:USE AdventureWorks;GODROP DATABASE AdventureWorks;GO

Fix/Workaround/Solution:Following commands will not raise error and successfully drop the database:USE Master;GODROP DATABASE AdventureWorks;GO

If you want to drop the database use master database first and then drop the database.

SQL SERVER – 2005 – Dynamic Management Views (DMV) and Dynamic Management Functions (DMF)

Dynamic Management Views (DMV) and Dynamic Management Functions (DMF) return server state information that can be used to monitor the health of a server instance, diagnose problems, and tune performance. They can exactly tell what is going on with SQL Server and its objects at the moment.There are tow kinds of DMVs and DMFs. Server-scoped dynamic management views and functions. Database-scoped dynamic management views and functions. All dynamic management views and functions exist in the sys schema and follow this naming convention dm_*. When you use a dynamic management view or function, you must prefix the name of the view or function by using the sys schema.

Following are major categories of DMVs and DMVs.

Common Language Runtime Related Dynamic Management Views I/O Related Dynamic Management Views and Functions Database Mirroring Related Dynamic Management Views Query Notifications Related Dynamic Management Views Database Related Dynamic Management Views Replication Related Dynamic Management Views Execution Related Dynamic Management Views and Functions Service Broker Related Dynamic Management Views Full-Text Search Related Dynamic Management Views SQL Server Operating System Related Dynamic Management Views Index Related Dynamic Management Views and Functions Transaction Related Dynamic Management Views and Functions

SQL SERVER – UDF – Remove Duplicate Chars From String

Few days ago, I received following wonderful UDF from one of this blog reader. This UDF is written for specific purpose of removing duplicate chars string from one large string. Virendra Chauhan, author of this UDF is working as DBA in Lutheran Health Network.

CREATE FUNCTION dbo.REMOVE_DUPLICATE_INSTR(@datalen_tocheck INT,@string VARCHAR(255))RETURNS VARCHAR(255)ASBEGIN

Page 16: 9 Jan 01, 2007-431 Dec 31, 2007

DECLARE @str VARCHAR(255)DECLARE @count INTDECLARE @start INTDECLARE @result VARCHAR(255)DECLARE @end INTSET @start=1SET @end=@datalen_tocheckSET @count=@datalen_tocheckSET @str = @stringWHILE (@count <=255)BEGINIF (@result IS NULL)BEGINSET @result=''ENDSET @result=@result+SUBSTRING(@str,@start,@end)SET @str=REPLACE(@str,SUBSTRING(@str,@start,@end),'')SET @count=@count+@datalen_tocheckENDRETURN @resultENDGO>, 1)Usage:SET CONCAT_NULL_YIELDS_NULL OFF

SELECT dbo.Remove_duplicate_instr(<CHARacter length OF a

duplicate SUBSTRING >,<string contain duplicate>)Example:To keep char set in a string unique and remove duplicate 3 char long string run this UDF as inline function.

SET CONCAT_NULL_YIELDS_NULL OFF

SELECT dbo.Remove_duplicate_instr(3,f123456789123456456Resultset:123456789

SQLAuthority Author Visit – IT Outsourcing to India – Top 10 Reasons Companies Outsource

Yesterday I had meeting with few of the leading outsourcing companies in Ahmedabad, India. Regular readers of this blog knows that I am currently in India handling large scale outsourcing assignment. My responsibilities includes managing application development, system architecture and database architecture. The purpose of meeting was to exchange the views and learn methodologies from one another regarding how to provide quality service to offshore clients.

There were about 10-15 Sr. Managers from different outsourcing company. The conversation was excellent and we all felt that we have learned a lot from each other. Two major things discussed were quality of products and quality of developers. There are many reason to outsource however the major reason to outsource any product is “get the product done (completed)”. Managers were concerned about so many online rip-off websites clamming as large scale outsourcing companies and listing fake projects. It is common for rip-off companies to claim big and provide nothing. It is very important and crucial for businesses to not to be involved with them.

Outsourcing is about trust, collaboration and success. Helping other countries in need has been always the course of mankind, outsourcing is nothing different then that. With information technology and process improvements increasing the complexity, costs and skills required to accomplish routine tasks as well as challenging complex tasks, companies are outsourcing such tasks to providers who have the expertise to perform them at lower costs , with greater value and quality outcome.

There were many things discussed, I will gradually write them on this blog. After meeting many good industry leaders I was very pleased and felt satisfied that we all care about outsourcing and reputation of the country. One proposal I had made in meeting was to write article about how to find rip-off companies. We will be discussing that in the next meeting. As this was first meeting we discussed Top 10 Reasons Companies Outsource Source: The Outsourcing Institute Membership, 1998

Page 17: 9 Jan 01, 2007-431 Dec 31, 2007

If you are interested in joining this meeting as well as finding good outsourcing company, send me email and I will forward your email to right person. There were few independent contrasters who were available to hire and some senior managers of Multi National Companies (MNC) available in meeting only for advise and discussion. At the end experienced well shared and meeting ended with food in nearby restaurant.

Following article is taken from Survey of Current and Potential Outsourcing End-Users The Outsourcing Institute Membership, 1998

1) Accelerate re engineering benefitsRe engineering aims for dramatic improvements in critical measures of performance such as cost, quality, service and speed. But the need to increase efficiency can come into direct conflict with the need to invest in core business. As non-core internal functions are continually put on the back burner, systems become less efficient and less productive. By outsourcing a non-core function to a world class provider, the organization can begin to see the benefits of re engineering.

2) Access to world class capabilitiesWorld class providers make extensive investments in technology,methodologies, and people. They gain expertise by working with many clients facing similar challenges. This combination of specialization and expertise gives customers a competitive advantage and helps them avoid the cost of chasing technology and training. In addition,there are better career opportunities for personnel who transition to the outsourcing provider.

3) Cash infusionOutsourcing often involves the transfer of assets from the customer to the provider. Equipment, facilities,vehicles and licenses used in the current operations have value and are sold to the vendor. The vendor then uses these assets to provide services back to the client. Depending on the value of the assets involved, this sale may result in a significant cash payment to the customer.

When these assets are sold to the vendor,they are typically sold at book value. The book value can be higher than the market value. In these cases, the difference between the two actually represents a loan from the vendor to the client which is repaid in the price of the services over the life of the contract.

4) Free resources for other purposesEvery organization has limits on the resources available to it. Outsourcing permits an organization to redirect its resources, most often people resources, from non core activities toward activities which serve the customer. The organization can redirect these people or at least the staff slots they represent on to greater value adding activities. People whose energies are currently focused internally can now be focused externally – on the customer.

5) Function difficult to manage or out of controlOutsourcing is certainly one option for addressing this problem. It is critical to remember that outsourcing doesn’t mean abdication of management responsibility nor does it work well as a knee jerk reaction by a company in trouble.

When a function is viewed as difficult to manage or out of control, the organization needs to examine the underlying causes. If the requirements expectations or needed resources are not clearly understood, then outsourcing won’t improve the situation; it may in fact exacerbate it. If the organization doesn’t understand its own requirements, it won’t be able to communicate them to an outside provider.

6) Improve company focusOutsourcing lets a company focus on its core business by having operational functions assumed by an outside expert. Freed from devoting energy to areas that are not in its expertise, the company can focus its resources on meeting its customers’ needs.

7) Make capital funds availableThere is tremendous competition within most organizations for capital funds. Deciding where to invest these funds is one of the most important decisions that senior management makes. It is often hard to justify non-core capital investments when areas more directly related to producing a product or providing a service compete for the same money.

Outsourcing can reduce the need to invest capital funds in non-core business functions. Instead of acquiring the resources through capital expenditures, they are contracted for on an “as used” operational expense basis. Outsourcing can also improve certain financial measurements of the firm by eliminating the need to show return on equity from capital investments in non core areas.

Page 18: 9 Jan 01, 2007-431 Dec 31, 2007

8) Reduce operating costsCompanies that try to do everything themselves may incur vastly higher research, development, marketing and deployment expenses, all of which are passed on to the customer. An outside provider’s lower cost structure, which may be the result of a greater economy of scale or other advantage based on specialization, reduces a company’s operating costs and increases its competitive advantage.

9) Reduce riskTremendous risks are associated with the investments an organization makes. Markets, competition, government regulations, financial conditions and technologies all change extremely quickly. Keeping up with these changes, especially those in which the next generation requires a significant investment, is very risky.

Outsourcing providers make investments on behalf of many clients, not just one. Shared investment spreads risk, and significantly reduces the risk born by a single company.

10) Resources not available internallyCompanies outsource because they do not have access to the required resources within the company. Outsourcing is a viable alternative to building the needed capability from the ground. New organizations, spin-offs, or companies expanding into new geography or new technology should consider the benefits of outsourcing from the very start.

SQL SERVER – Grouping JOIN Clauses In SQL

I always enjoy writing and reading articles about JOIN Clauses. One of my friend and the best ColdFusion Expert Ben Nadel has written good article about SQL JOINs. There are few interesting comments as well at the end of article.

“JOIN grouping is pretty powerful and can get you out of those sticky situations that involve mixed table relationship rules. ” Ben Nadel – Grouping JOIN Clauses In SQL

SQL SERVER – Q and A with Database Administrators

I have been in India for more than a month now, as I am leading a very large outsourcing project. We have conducted few interviews since the project required more Database Administrators and Senior Developers. I am listing few of the questions discussed during all the interviews. The whole event of interviews was very interesting. I met some very good programmers from all over the country. Many interesting questions were discussed between interviewers and candidates. I am listing some of those questions here. Some are technical and some are just my personal opinions. I will appreciate your thought about this article.

Read my complete article here.

SQL SERVER – Sharpen Your Skills: Brush up on FILLFACTOR, ISNULL, NULLIF, and % as wildcard and operator

Read my article in SQL Server Magazine December 2007 Edition

I will be not able to post complete article here due to copyright issues. Please visit the link above to read the article

SQLAuthority News – Download SQL Server 2005 Books Online (September 2007)

Download an updated version of Books Online for Microsoft SQL Server 2005. Books Online is the primary documentation for SQL Server 2005. The September 2007 update to Books Online contains new material and fixes to documentation problems reported by customers after SQL Server 2005 was released. Refer to “New and Updated Books Online Topics” for a list of topics that are new or updated in this version. Topics with significant updates have a Change History table at the bottom of the topic that summarizes the changes. Beginning with the February 2007 update, SQL Server 2005 Books Online reflects product upgrades included in SQL Server 2005 Service Pack 2 (SP2).

Download SQL Server 2005 Books Online

Page 19: 9 Jan 01, 2007-431 Dec 31, 2007

SQLAuthority News – Microsoft SQL Server 2005 MSIT Three Configuration Pack for Configuration Manager 2007

November 14, 2007 by pinaldave

Microsoft SQL Server 2005 MSIT Basic Configuration Pack for Configuration Manager 2007

This configuration pack contains configuration items intended to manage your SQL Server 2005 server roles, and was developed based on settings used by Microsoft IT in the configuration of these server roles.

Microsoft SQL Server 2005 MSIT Intermediate Configuration Pack for Configuration Manager 2007

This configuration pack contains configuration items intended to manage your SQL Server 2005 server roles, and was developed based on settings used by Microsoft IT in the configuration of these server roles.

Microsoft SQL Server 2005 MSIT Comprehensive Configuration Pack for Configuration Manager 2007

This configuration pack contains configuration items intended to manage your SQL Server 2005 server roles, and was developed based on settings used by Microsoft IT in the configuration of these server roles.

The Microsoft SQL Server 2005 MSIT Comprehensive Configuration Pack includes configuration items for the following:

Core Instance System Databases User Databases Cluster Core Cluster Instance Cluster System Databases Cluster User Databases

In some cases, the settings and values will be represented by a Parent and Child configuration item pair. Please note that the Child configuration item will contain the editable rules and values that an administrator may choose to modify to reflect the desired configuration for their specific environment.

Abstract courtesy : Microsoft

SQLAuthority News – SQL Joke, SQL Humor, SQL Laugh – Database Dilbert

November 14, 2007 by pinaldave

This is my favorite Dilbert.

Click on image to see large graphic.

Page 20: 9 Jan 01, 2007-431 Dec 31, 2007

SQLAuthority News – Microsoft SQL Server 2005 Assessment Configuration Pack Download

November 15, 2007 by pinaldave

Microsoft SQL Server 2005 Assessment Configuration Pack for Gramm-Leach Bliley Act (GLBA)This configuration pack contains configuration items intended to help you establish and validate a desired configuration for your SQL 2005 servers in order to support your Gramm-Leach Bliley Act compliance efforts

Microsoft SQL Server 2005 Assessment Configuration Pack for Sarbanes-Oxley Act (SOX)This configuration pack contains configuration items intended to help you establish and validate a desired configuration for your SQL 2005 servers in order to support your Sarbanes-Oxley compliance efforts.

Microsoft SQL Server 2005 Assessment Configuration Pack for Federal Information Security Management Act (FISMA)This configuration pack contains configuration items intended to help you establish and validate a desired configuration for your SQL 2005 servers in order to support your Federal Information Security Management Act compliance efforts.

Microsoft SQL Server 2005 Assessment Configuration Pack for European Union Data Protection Directive (EUDPD)This configuration pack contains configuration items intended to help you establish and validate a desired configuration for your SQL 2005 servers in order to support your European Union Data Protection Directive compliance efforts.

Microsoft SQL Server 2005 Assessment Configuration Pack for Health Insurance Portability and Accountability Act (HIPAA)This configuration pack contains configuration items intended to help you establish and validate a desired configuration for your SQL 2005 servers in order to support your Health Insurance Portability and Accountability Act compliance efforts.

SQL SERVER – 2005 – Generate Script with Data from Database – Database Publishing Wizard

November 16, 2007 by pinaldave

I really enjoyed writing about SQL SERVER – 2005 – Create Script to Copy Database Schema and All The Objects – Stored Procedure, Functions, Triggers, Tables, Views, Constraints and All Other Database Objects. Since then the I have received question that how to copy data as well along with schema. The answer to this is Database Publishing Wizard. This wizard is very flexible and works with modes like schema only, data only or both. It generates a single SQL script file which can be used to recreate the contents of a database by manually executing the script on a target server.

The pre-requisite for Database Publishing Wizard is .NET 2.0 Framework, SQL Server 2005 Management Objects, SMO. The Database Publishing Wizard will script all objects that the supplied User has permissions to see in the source database. Any objects created “WITH ENCRYPTION” cannot be scripted. If such objects exist in the source database, the tool will not produce a script.

First of all install Database Publishing Wizard from here : Download Database Publishing Wizard.

It will be installed at following location : C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\

Now login using Command prompt and run following command on any desire database, it will create the script at your specified location. Script will have schema as well as data which can be used to create the same information on new server.

Command to run which will create schema and database:C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz script -d AdventureWorks “C:\AdventureWorks.sql”

Command to run which will create schema:C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz script -d AdventureWorks “C:\AdventureWorks.sql” -schemaonly

Page 21: 9 Jan 01, 2007-431 Dec 31, 2007

Command to run which will create data:C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz script -d AdventureWorks “C:\AdventureWorks.sql” -dataonly

Command windows will generate output of action it is taking. See below two screen shots of it.

If you have followed this tutorial exactly you will end up with adventurework.sql which will be quite big and if your computer is not powerful enough it will hang your computer for a while. I suggest that you try this on smaller database of size around 100MB.

SQL SERVER – 2005 – Best Practices for SQL Server Health Check

November 17, 2007 by pinaldave

Few days ago, I reviewed SQLAuthority News – Book Review – SQL Server 2005 Management and Administration (Paperback) on this blog. I received few comments on this review. Some people think it is good book, some thought that this waste of time. Well, after so many emails, I feel that I should point out something special about this book, which attracted me.

The reason, I decided to review this book is practical advise, rather then some technical long answer. Technical answers have their places and helps to fix issues in most cases, however common sense is

Page 22: 9 Jan 01, 2007-431 Dec 31, 2007

extremely important. To prove that this book gives practical answers, I have copied one of the section from this book and listed only few of the topics from that section.

I have received authorization from publisher to review this book, this article does not violate any copyright issues.

Conduct general health checks every 6 to 12 months. Create documentation and associate it with production and test SQL Servers to supplement

operations and routine maintenance. Identify all the health issues during the health check and then develop a remediation plan. Don’t

try to fix the issues during the health check because doing so muddles the results and slows down the health check process. And the fix for one issue might affect another.

Retain all health check documentation and information for future use. Using SQL Server 2005 BPA is the most efficient way to scan the core components of SQL Server

2005. When using a locally attached storage, isolate the operating system from the database and

transaction logs, preferably on separate RAID volumes. Allocate enough space on mission-critical databases and transaction logs to accommodate their

growth. Manage antivirus scanning, excluding specific files within SQL Server. Use Windows Authentication. No one should log in as the Service Account to do administration.

SQLAuthority News – Job Opportunity in Ahmedabad, India to Work with Technology Leaders Worldwide – SQL Server, ColdFusion, ASP.NET

November 18, 2007 by pinaldave

If you have one or more years of experience in any web based programming language (.NET, ColdFusion, PHP) and interested in SQL Server as well willing to locate Ahmadabad, India. Please send me your resume, if selected you may get chance to work with one of the most progressing industry in world as well some smartest technology leaders worldwide. Salary depends on Experience.

If selected for interview I suggest you go over SQL Server Interview Questions and Answers Complete List Download, as there is great chance I may be participating in interview.

Please send your resume at pinaldave “at” yahoo.com and pinal “at” sqlauthority.com with subject line as Job Opportunity with SQLAuthority.

SQLAuthority News – SQL Server 2008 Community Technology Preview (CTP) Download Now Available

November 19, 2007 by pinaldave

Download the latest SQL Server 2008 Community Technology Preview (CTP) and try out the latest features of SQL Server 2008! The SQL Server development team uses your CTP feedback to help refine and enhance product features. Download it today and send your feedback.

Microsoft SQL Server 2008, the next release of Microsoft SQL Server, provides a comprehensive data platform that is more secure, reliable, manageable and scalable for your mission critical applications, while enabling developers to create new applications that can store and consume any type of data on any device, and enabling all your users to make informed decisions with relevant insights.

Download Link

SQL SERVER – Sharpen Your Skills: Joins, Groupings, and Data Types

November 20, 2007 by pinaldave

Read my article in SQL Server Magazine November 2007 Edition

Page 23: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Generate Incremented Linear Number Sequence

November 21, 2007 by pinaldave

Just a day ago, I received interesting question on this blog. Read original question here. This is very good question and after reading this question I quickly wrote small script as answer. Let us see the question and answer together.

Q. How can we generate incremented linear number in sql server as in oracle we generate in via sequence?

123456789

A. Run following script which will generate output in sequence, which will generate output as you requested.DECLARE @idt INTSET @idt = 0WHILE (@idt < 100)BEGINSELECT @idt = @idt + 1PRINT @idtEND

SQL SERVER – Shrinking Truncate Log File – Log Full – Part 2

November 22, 2007 by pinaldave

About a year ago, I wrote SQL SERVER – Shrinking Truncate Log File – Log Full. I was just going through some of the earlier posts and comments on this blog and one particular comment by Praveen Barath caught my eye. It is very good explanation. I am copying complete explanation here with full credit to original author.

How to truncate log file in SQL Server 2005

SQL Server 2005 is quite different from SQL Server 2000. To truncate log file is one thing which is different from SQL Server 2000. In SQL Server 2000, you just use Shrink to whatever file size you like. In SQL Server 2005, sometime I cannot shrink the log file at all.

Here I want to describe some tricks to truncate log file for a database in SQL Server 2005. The work environment is MS SQL Server Management Studio.

I. Shrink the log file size at the right time

I found out this trick:

Immediately after I use the SSIS package or Import the data to the database ( highlight the database->Tasks->Import data … ), or Export the data from the database ( highlight the database->Tasks->Export data … ), I can shrink the log file to the desired size, for example, 1MB. That is, highlight the database->Tasks->Shrink->Files

set the file size, say, 1MB.

Then, click OK and you are done.

Page 24: 9 Jan 01, 2007-431 Dec 31, 2007

II. Eliminate the log file completely

Sometimes we just do not need the big log file. For example, I have 40GB log file. I am sure I do not need this log file and want to get rid of it completely to free up the hard drive space. The logic is

a. Detach the database

b. Rename the log file

c. Attach the database without the log file

d. Delete the log file

Let’s say, the database name is testDev. In the SQL Server Management Studio,

Highlight the database-> Tasks->Detach..-> Click OKGo to log file folder -> rename the testDev_log.ldf to be like testDev_log-aa.ldf,Highlight Databases->Attach…-> Click Add -> add the database testDev, highlight the log file and click the ‘Remove’ button. This means you only attach testDev.mdfAfter this is done, you can verify the contents of the attached database and then delete the log file.

SQL SERVER – 2008 – November CPT5 New Improvement

November 23, 2007 by pinaldave

The progress map of SQL Server 2008 is diagrammatically listed here.

I am listing the new improvements here as list.

Data Collection and Performance Warehouse for Relational Engine Service Broker Enhancements Registered Servers Enhancements Synchronous net-changes change tracking for SQL Server T-SQL IntelliSense Declarative Management Framework (DMF) Enhancements Geo-spatial Support Analysis Services Query and Writeback Performance Robust Report Server Platform Integration Services – Lookup Enhancements Analysis Services MDX Query Optimizer – Block Computation Analysis Services Aggregation Design Analysis Services Cube Design Reporting Services Scale Engine Transparent Data Encryption Resource Governor – Limit Specification Backup Compression Plan Freezing Fully Parallel Plans Scale on Partitioned Tables

SQL SERVER – Upgrade Advise – From 2000 to 2005 or 2008

November 24, 2007 by pinaldave

There has some good amount of discussion going on in SQL Server community about should we upgrade from SQL Server 2000 to SQL Server 2005 or wait for SQL Server 2008. I have received quite a few email and invitations to participate in forums on this topic. Instead of talking about this topic on different places, I have decided to write my opinion on my blog.

Page 25: 9 Jan 01, 2007-431 Dec 31, 2007

I recommend to upgrade to SQL Server 2000 users to SQL Server 2005.

SQL Server 2008 is due next year. The RTM may or may not be available till February 2008. After the release the first service pack will be available after few months. This means that stable version will not be available till late 2008. SQL Server 2005 is perfectly has stable version and already two SP are released. This makes SQL Server 2005 very reliable product.

I suggest that SQL Server 2005 with Service Pack 2 installed is good upgrade from SQL Server 2000.

SQLAuthority News – SQL Server Compact 3.5 Downloads and ReportViewer Visual Studio Download

November 25, 2007 by pinaldave

SQL Server Compact 3.5 Books Online and Samples

SQL Server Compact 3.5 is a small footprint in-process database engine that allows developers to build robust applications for Windows Desktops and Mobile Devices. This download contains the Books Online and Samples for SQL Server Compact 3.5

SQL Server Compact 3.5 for Windows Mobile

SQL Server Compact 3.5 is a small footprint in-process database engine that allows developers to build robust applications for Windows Desktops and Mobile Devices. This download contains the CAB files and DLL’s that are used to install SQL Server Compact 3.5 on the Windows Mobile Devices platform

SQL Server Compact 3.5 and Synchronization Services for ADO.Net v1.0 for Windows Desktop

SQL Server Compact 3.5 is a small footprint in-process database engine that allows developers to build robust applications for Windows Desktops and Mobile Devices. This download contains the files for SQL Server Compact 3.5 and Synchronization Services for ADO.Net v1.0 for Windows Desktop platform

ReportViewer Samples for Microsoft Visual Studio 2008

This release provides developer sample applications in Microsoft Visual Basic and Microsoft Visual C# that use the ReportViewer controls for Microsoft Visual Studio 2008.

Abstract courtesy : Microsoft

SQL SERVER – Rules of Third Normal Form and Normalization Advantage – 3NF

November 26, 2007 by pinaldave

I always ask question about Third Normal Form in interviews I take.

Q. What is Third Normal Form and what is its advantage?A. Third Normal Form (3NF) is most preferable normal form in RDBMS. Normalization is the process of designing a data model to efficiently store data in a database. The rules of 3NF are mentioned here

Make a separate table for each set of related attributes, and give each table a primary key. If an attribute depends on only part of a multi-valued key, remove it to a separate table If attributes do not contribute to a description of the key, remove them to a separate table.

Normalization is very close to concept of object oriented schema’s and it stores one data at only one place by removing all the redundant data. It also helps to draw the schema easier. Normalization comes at the cost of performance.

SQL SERVER – 2005 – List All Stored Procedure in Database

Page 26: 9 Jan 01, 2007-431 Dec 31, 2007

November 27, 2007 by pinaldave

Run following simple script on SQL Server 2005 to retrieve all stored procedure in database.

SELECT *FROM sys.procedures;

This will ONLY work with SQL Server 2005.

SQL SERVER – Correct Syntax for Stored Procedure SP

November 28, 2007 by pinaldave

Just a day ago, I received interesting question about correct syntax for Stored Procedure. Many readers of this blog will think that it is very simple question. The reason this is interesting is the question behavior of BEGIN … END statements and GO command in Stored Procedure.

Let us first see what is correct syntax.

Correct Syntax:CREATE PROCEDURE usp_SelectRecordASBEGINSELECT *FROM TABLEENDGO

I have seen many new developers write statements after END statement. This will not work but will probably execute first fine when stored procedure is created. Rule is anything between BEGIN and END will be created as part of the stored procedure and will work fine. However, anything after END statement will be not part of Stored Procedure. Nesting of BEGIN … END statement is allowed in Stored Procedure.

Incorrect Syntax : (This may not throw an error)CREATE PROCEDURE usp_SelectRecordASBEGINSELECT *FROM TABLEENDGO

SQL SERVER – Database Interview Questions and Answers Complete List

November 29, 2007 by pinaldave

If you are subscribed to my blog you will know that I receive request to send Database or SQL Server very frequently. Following is list of articles of my questions and answers series.

Download SQL Server Interview Questions and Answers Complete List

Complete Series of SQL Server Interview Questions and AnswersSQL Server Interview Questions and Answers – IntroductionSQL Server Interview Questions and Answers – Part 1SQL Server Interview Questions and Answers – Part 2SQL Server Interview Questions and Answers – Part 3SQL Server Interview Questions and Answers – Part 4SQL Server Interview Questions and Answers – Part 5SQL Server Interview Questions and Answers – Part 6SQL Server Interview Questions and Answers Complete List Download

Page 27: 9 Jan 01, 2007-431 Dec 31, 2007

Other popular SeriesSQL SERVER Database Coding Standards and Guidelines Complete List DownloadSQL SERVER – Data Warehousing Interview Questions and Answers Complete List DownloadDBA Database SQL Job List Search

SQLAuthority News – Download SQL Server 2005 Books Online (September 2007)

November 30, 2007 by pinaldave

Download an updated version of Books Online for Microsoft SQL Server 2005. Books Online is the primary documentation for SQL Server 2005. The September 2007 update to Books Online contains new material and fixes to documentation problems reported by customers after SQL Server 2005 was released. Refer to “New and Updated Books Online Topics” for a list of topics that are new or updated in this version. Topics with significant updates have a Change History table at the bottom of the topic that summarizes the changes. Beginning with the February 2007 update, SQL Server 2005 Books Online reflects product upgrades included in SQL Server 2005 Service Pack 2 (SP2).

Download SQL Server 2005 Books Online

SQL SERVER – FIX : ERROR Msg 5174 Each file size must be greater than or equal to 512 KB

November 12, 2007 by pinaldave

Following error occurs when database which is attempted to be created is smaller than 512KB. It is must that all the databases are larger than 512KB. It will also follow with another error 1802, which is due to previous error 5174.

Following code will create the error discussed in this post.CREATE DATABASE TestsON( NAME = 'Tests',FILENAME = 'c:\tests.mdf',SIZE = 12KB )GO

Msg 5174, Level 16, State 1, Line 1Each file size must be greater than or equal to 512 KB.Msg 1802, Level 16, State 1, Line 1CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

Fix/WorkAround/Solution :Create database which is larger than 512KB. It is as well important that this database is larger than your model database, which we will see in future posts. If database is smaller than model database it will throw error which I have described here : SQL SERVER – FIX : ERROR Msg 1803 The CREATE DATABASE statement failed. The primary file must be at least 2 MB to accommodate a copy of the model database

SQLAuthority News – SQL Server 2005 Powers Global Forensic Data Security Tool

November 11, 2007 by pinaldave

Note :  Download Whitepaper by Microsoft

Find out how SQL Server 2005 powers a 27 TB data management system called ICE 3.0 that gathers forensic data from more than 85 Microsoft corporate proxy servers into a single database.

The Information Security team at Microsoft uses an internal tool called Information Security Consolidated Event Management (ICE 3.0) to gather forensic data from more than 85 proxy servers around the world. Powered by SQL Server 2005, the 27 TB data management system collects different types of global evidence, such as inbound and outbound e-mail traffic, Login events, and Web browsing, into a single database. ICE 3.0 provides rapid security analysis and queries, robust proxy performance analysis, and extensive troubleshooting functionality.

Page 28: 9 Jan 01, 2007-431 Dec 31, 2007

This paper assumes that readers are technical decision makers who are already familiar with Microsoft SQL Server 2005, including SQL Server Integration Services (SSIS). This paper also assumes a basic understanding of storage technologies such as Very Large Database Systems (VLDBs) and Storage Area Networks (SANs). This paper also discusses the concept of global forensic security systems.

Download Whitepaper

Abstract courtesy : Microsoft

SQL SERVER – 2005 2000 – Search String in Stored Procedure

November 10, 2007 by pinaldave

SQL Server has released SQL Server 2000 edition before 7 years and SQL Server 2005 edition before 2 years now. There are still few users who have not upgraded to SQL Server 2005 and they are waiting for SQL Server 2008 in February 2008 to SQL Server 2008 to release. This blog has is heavily visited by users from both the SQL Server products. I have two previous post which demonstrates the code which can be search string in stored procedure. Many users get confused with the script version and try to execute SQL Server 2005 version on SQL Server 2000, they do send me email or leave comment that this does not work. I am going to list both the post here with clearly indicating the SQL Server version. I am sure this will clear some of the doubts.

SQL Server 2000USE AdventureWorksGO--Option 1SELECT DISTINCT so.nameFROM syscomments scINNER JOIN sysobjects so ON sc.id=so.idWHERE sc.TEXT LIKE '%Employee%'GO--Option 2SELECT DISTINCT o.name ,o.xtypeFROM syscomments cINNER JOIN sysobjects o ON c.id=o.idWHERE c.TEXT LIKE '%Employee%'GO

SQL Server 2005 USE AdventureWorksGO--Searching for Empoloyee tableSELECT NameFROM sys.proceduresWHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Employee%'GO--Searching for Empoloyee table and RateChangeDate column togetherSELECT NameFROM sys.proceduresWHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Employee%'AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%RateChangeDate%'GO

SQL SERVER – Versions, CodeNames, Year of Release

November 9, 2007 by pinaldave

Just a day ago, while I was discussing one of the project with another outsourcing team lead in India (who is leading team of 100+ programmer and developer) he asked me if I know all the codenames of the SQL Server releases so far. I knew only two code names SQL Server 2005 – Yukon and SQL Server 2008 – Katmai. Once our meeting was over, I could not stop thinking about this question. I search online and very easily I found answer to this question on wikipedia.

1993 – SQL Server 4.21 for Windows NT

Page 29: 9 Jan 01, 2007-431 Dec 31, 2007

1995 – SQL Server 6.0, codenamed SQL95 1996 – SQL Server 6.5, codenamed Hydra 1999 – SQL Server 7.0, codenamed Sphinx 1999 – SQL Server 7.0 OLAP, codenamed Plato 2000 – SQL Server 2000 32-bit, codenamed Shiloh (version 8.0) 2003 – SQL Server 2000 64-bit, codenamed Liberty 2005 – SQL Server 2005, codenamed Yukon (version 9.0) Next release – SQL Server 2008, codenamed Katmai (version 10.0)

SQL Server 2008 is expected to be release in February 2008.

SQLAuthority News – Book Review – SQL Server 2005 Management and Administration (Paperback)

November 8, 2007 by pinaldave

SQL Server 2005 Management and Administration (Paperback)by Ross Mistry (Author), Chris Amaris (Author), Alec Minty (Author), Rand Morimoto (Author)

Link to Amazon (This is not affiliate Link)

Short Summary:SQL SERVER 2005 is a trusted database platform that provides organizations a competitive advantage by allowing them to obtain faster results and make better business decisions. This book covers all the topics which can help Database Administrators to be successful and effective.

Detail summary:This book is covers all the topics and modules of the SQL Server 2005, e.g. database engine, Analysis Services, Integration Services, replication, Reporting Services, Notification Services, services broker and full text search. This book improves the experience these professionals have working with SQL Server. Book also provides detailed guidance on management, administration, and monitoring.

Role of DBA does not end when SQL Server is already deployed. The real task of DBA begins when SQL Server is successfully deployed. This book assumes the reader has experience with installing SQL Server 2005, so it goes far beyond the basic installation and setup methods. One thing I really liked about this book is that it focuses on day-to-day administration, best practices, and industry case scenarios. Another interesting fact about this book is all topics and examples covered in this book are based on the new features and functionality included with SQL Server 2005 Service Pack 2.

Page 30: 9 Jan 01, 2007-431 Dec 31, 2007

The topic of SQL Server 2005 administration and management is huge and this book covers almost all of those important topics. This book is divided in total of six parts. Part 5 and part 6 are available online only. Around 300 pages are available online only and it can be downloaded by registering the book. When registered this book it also enables 45 day free subscription of Safari.

Rating: 4 stars

In Summary, This is great concise book which all DBA should keep on desk for frequent reference.

SQLAuthority News – 1 Million Visitors in last 1 year

November 7, 2007 by pinaldave

Today this blog has crossed 1 Million Visitors. I thank you for your reading this blog. I have learned a lot writing on this blog as well.

SQLAuthority News – Microsoft Synchronization Services for ADO.NET v2.0 CTP1

November 6, 2007 by pinaldave

Microsoft Synchronization Services for ADO.NET provides the ability to synchronize data from disparate sources over two-tier, N-tier, and service-based architectures. Rather than simply replicating a database and its schema, the Synchronization Services application programming interface (API) provides a set of components to synchronize data between data services and a local store. Applications are increasingly used on mobile clients, such as laptops and devices, that do not have a consistent or reliable network connection to a central server. It is crucial for these applications to work against a local copy of data on the client. Equally important is the need to synchronize the local copy of the data with a central server when a network connection is available. The Synchronization Services API, which is modeled after the ADO.NET data access APIs, gives you an intuitive way to synchronize data. It makes building applications for occasionally connected environments a logical extension of building applications where you can count on a consistent network connection.

In order to install the Microsoft Synchronization Services for ADO.NET v2.0 CTP1 and SQL Server Compact 3.5, please visit Microsoft Download Site

SQLAuthority News – Few Add-ons for SQLAuthority

November 5, 2007 by pinaldave

SQL Random Article

Find Post SQL Jobs

Search SQLAuthority

Subscribe Email Update

SQLAuthority Feed

My Other Blog

SQLAuthority News – Best Articles on SQLAuthority.com

November 4, 2007 by pinaldave

SQL SERVER – Cursor to Kill All Process in Database

SQL SERVER – Find Stored Procedure Related to Table in Database – Search in All Stored procedure

Page 31: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Shrinking Truncate Log File – Log Full

SQL SERVER – Simple Example of Cursor

SQL SERVER – UDF – Function to Convert Text String to Title Case – Proper Case

SQL SERVER – Restore Database Backup using SQL Script (T-SQL)

SQL SERVER – T-SQL Script to find the CD key from Registry

SQL SERVER – Delete Duplicate Records – Rows

SQL SERVER – QUOTED_IDENTIFIER ON/OFF and ANSI_NULL ON/OFF Explanation

SQL SERVER – Union vs. Union All – Which is better for performance?

SQL SERVER – DBCC RESEED Table Identity Value – Reset Table Identity

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record

SQL SERVER – Difference between DISTINCT and GROUP BY – Distinct vs Group By

SQL SERVER – Index Seek Vs. Index Scan (Table Scan)

SQL SERVER – TempDB is Full. Move TempDB from one drive to another drive

SQL SERVER – T-SQL Paging Query Technique Comparison – SQL 2000 vs SQL 2005

SQL SERVER – Performance Optimization of SQL Query and FileGroups

SQL SERVER – Search Text Field – CHARINDEX vs PATINDEX

SQL SERVER – 2005 Explanation of TRY…CATCH and ERROR Handling

SQL SERVER – Script to find SQL Server on Network

SQL SERVER – Stored Procedures Advantages and Best Advantage

SQL SERVER – CASE Statement/Expression Examples and Explanation

SQL SERVER – Raid Configuration – RAID 10

SQL SERVER – Understanding new Index Type of SQL Server 2005 Included Column Index along with Clustered Index and Non-clustered Index

SQL SERVER – Query to Find Seed Values, Increment Values and Current Identity Column value of the table

SQL SERVER – Six Properties of Relational Tables

SQL SERVER – TRIM() Function – UDF TRIM()

SQL SERVER – Difference between Unique Index vs Unique Constraint

SQL SERVER – 2005 Locking Hints and Examples

Page 32: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Good, Better and Best Programming Techniques

SQL SERVER – Random Number Generator Script – SQL Query

SQL SERVER – 2005 TOP Improvements/Enhancements

SQL SERVER – 2005/2000 Examples and Explanation for GOTO

SQL SERVER – Explanation SQL Commando GO

SQL SERVER – 2005 – List all the database

SQL SERVER – UDF – Function to Parse AlphaNumeric Characters from String

SQL SERVER – Disable Index – Enable Index – ALTER Index

SQL SERVER – 2005 – SSMS Change T-SQL Batch Separator

SQL SERVER – SQL Code Formatter Tools

SQL SERVER – 2005 Comparison EXCEPT operator vs. NOT IN

SQL SERVER – 2005 NorthWind Database or AdventureWorks Database – Samples Databases

SQL SERVER – 2005 Find Table without Clustered Index – Find Table with no Primary Key

SQL SERVER – 2005 Limiting Result Sets by Using TABLESAMPLE – Examples

SQL SERVER – 2005 Change Database Compatible Level – Backward Compatibility

SQL SERVER – 2005 Constraint on VARCHAR(MAX) Field To Limit It Certain Length

SQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – Insert Multiple Records Using One Insert Statement – Use of UNION ALL

SQL SERVER – Retrieve – Select Only Date Part From DateTime – Best Practice

SQL SERVER – 2005 T-SQL Paging Query Technique Comparison (OVER and ROW_NUMBER()) – CTE vs. Derived Table

SQL SERVER – Easy Sequence of SELECT FROM JOIN WHERE GROUP BY HAVING ORDER BY

SQL SERVER – 2005 – UDF – User Defined Function to Strip HTML – Parse HTML – No Regular Expression

SQL SERVER – Retrieve Current Date Time in SQL Server CURRENT_TIMESTAMP, GETDATE(), {fn NOW()}

SQL SERVER – Explanation and Comparison of NULLIF and ISNULL

SQL SERVER – 2005 Row Overflow Data Explanation

SQL SERVER – Comparison Index Fragmentation, Index De-Fragmentation, Index Rebuild – SQL SERVER 2000 and SQL SERVER 2005

SQL SERVER – Comparison : Similarity and Difference #TempTable vs @TempVariable

Page 33: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Definition, Comparison and Difference between HAVING and WHERE Clause

SQL SERVER – 2005 Best Practices Analyzer Tutorial – Sample Example

SQL SERVER – 2005 – List All Stored Procedure Modified in Last N Days

SQL SERVER – Count Duplicate Records – Rows

SQL SERVER – CASE Statement in ORDER BY Clause – ORDER BY using Variable

SQL SERVER – Restore Database Without or With Backup – Everything About Restore and Backup

SQL SERVER – UDF – Function to Get Previous And Next Work Day – Exclude Saturday and Sunday

SQL SERVER – One Thing All DBA Must Know

SQL SERVER – 2005 – List Tables in Database Without Primary Key

SQL SERVER – 2005 – Find Stored Procedure Create Date and Modified Date

SQL SERVER – UDF – Validate Integer Function

SQL SERVER – What is SQL? How to pronounce SQL?

SQL SERVER – 2005 – Difference and Similarity Between NEWSEQUENTIALID() and NEWID()

SQL SERVER – 2005 – Explanation and Script for Online Index Operations – Create, Rebuild, Drop

SQL SERVER – Find Last Day of Any Month – Current Previous Next

SQL SERVER – T-SQL Script to Insert Carriage Return and New Line Feed in Code

SQL SERVER – 2005 – T-SQL Script to Attach and Detach Database

SQL SERVER – Actual Execution Plan vs. Estimated Execution Plan

SQL SERVER – 2005 – Search Stored Procedure Code – Search Stored Procedure Text

SQL SERVER – 2005 – Find Tables With Foreign Key Constraint in Database

SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database

SQL SERVER – 2005 – Introduction and Explanation to sqlcmd

SQL SERVER – UDF – User Defined Function – Get Number of Days in Month

SQL SERVER – 2005 – Start Stop Restart SQL Server From Command Prompt

SQL SERVER – 2005 – List All The Constraint of Database – Find Primary Key and Foreign Key Constraint in Database

SQL SERVER – UDF – Validate Positive Integer Function – Validate Natural Integer Function

SQL SERVER – Effect of TRANSACTION on Local Variable – After ROLLBACK and After COMMIT

SQL SERVER – 2005 – OUTPUT Clause Example and Explanation with INSERT, UPDATE, DELETE

Page 34: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 – Sample Example of RANKING Functions – ROW_NUMBER, RANK, DENSE_RANK, NTILE

SQL SERVER – Three T-SQL Script to Create Primary Keys on Table

SQLAuthority News – Best SQLAuthority Articles on Other Popular Sites

November 3, 2007 by pinaldave

Best SQLAuthority Articles on Other Popular Sites

SQL SERVER – UDF vs. Stored Procedures and Having vs. WHERE (SQL Server Magazine)

SQL SERVER – Pre-Code Review Tips – Tips For Enforcing Coding Standards (dotnetslackers.com)

SQLAuthority News – Best Downloads on SQLAuthority.com

November 2, 2007 by pinaldave

Best Downloads on SQLAuthority.com

SQL SERVER – Query Analyzer Shortcuts

SQL Server Interview Questions and Answers Complete List Download

SQL SERVER – Download SQL Server Management Studio Keyboard Shortcuts (SSMS Shortcuts)

SQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

SQLAuthority News – First Birthday of Blog – 365 Post in One Year

November 1, 2007 by pinaldave

Hello Everyone,

Today is birthday of this blog. Exactly one year ago, I started this journey of SQL Server and today I have reached first mile stone. There are so many great experience I had during this year. One thing I enjoyed the most is My Extremely Knowledgeable and Friendly Readers. I have learned a lot from all my readers, their emails and comments on this blog. You have been wonderful part of this blog.

I was very surprised when I counted how many articles I had posted last year. It was perfect 365! One article a day!! Once again, I want to thank YOU for encouraging me and I want to express my gratitude to my supportive family without their support, I would have not reached here. I would like to also thank SQL Server Magazine for giving me opportunity as regular columnist in the magazine.

One more interesting thing I would like to share with all of you is that I have arrived to India today due to one extremely important assignment I am working on. Those who have requested my visit to their organization as well wanted me to talk about SQL Server, I have already sent them email. If you have not received email or want me to visit your company send me email and I will accommodate every possible request.

For next week I will post my personal favorite articles as well most requested articles by users. Today I have reached my first milestone my journey has just started. I will end this post with my favorite quote of Robert Frost “Miles to go before I sleep“.

Best Regards,

Page 35: 9 Jan 01, 2007-431 Dec 31, 2007

Pinal Dave

SQL SERVER – Importance of Master Database for SQL Server Startup

October 31, 2007 by pinaldave

I have received following questions many times. I will list all the questions here and answer them together.

What is the purpose of Master database?Should we backup Master database?Which database is must have database for SQL Server for startup?Which are the default system database created when SQL Server 2005 is installed for first time?What happens if Master database is corrupted?

Answers to all of the questions are very much related. Master database is system database and it contains information about running server’s configuration. When SQL Server 2005 is installed it usually creates master, model, msdb, tempdb resource and distribution (last two depends on version of SQL Server) system database by default. Only Master database is the one which is absolutely must have database. Without Master database SQL Server can not be started. This is the reason it is extremely important to backup Master database.

If Master database is corrupted it should be restored from the latest backup, considering SQL Server was able to start with damaged Master database. Sometimes Master database is corrupted so much it can not start SQL Server at all and it can not be restored. SQL Server should be rebuild using command prompt and restored from latest backup once again.

I am very much interested to know the feedback of readers who have asked questions regarding this issues.

SQL SERVER – Business Intelligence (BI) Basic Terms Explanation

October 30, 2007 by pinaldave

Business IntelligenceBusiness intelligence is a method of storing and presenting key enterprise data so that anyone in your company can quickly and easily ask questions of accurate and timely data. Effective BI allows end users to use data to understand why your business go the particular results that it did, to decide on courses of action based on past data, and to accurately forecast future results.

Data WarehouseA single structure that usually, but not always, consists of one or more cubes.

Data MartA defined subset of a data warehouse, often a single cube from a group. It represents one business unit.

CubeA storage structure used by classic data warehousing products in place of many. Cube usually present data that is aggregated, rather than each individual item. Cubes present a summarized, aggregated view of enterprise data, as opposed to normalized table sources that present detailed data.

Decision Support SystemThe term’s broad definition can mean anything from a read-only copy of an online transaction processing (OLTP) database to a group of OLAP cubes or even a mixture of both.

ETLETL is abbreviation of Extraction, Transform, and Load.

OLAPOLAP is abbreviation of online analytical processing.

Page 36: 9 Jan 01, 2007-431 Dec 31, 2007

OLTPOLTP is abbreviation of online transactional processing.

SQL SERVER – Disable All Triggers on a Database – Disable All Triggers on All Servers

October 29, 2007 by pinaldave

Just a day ago, I received question in email regarding my article SQL SERVER – 2005 Disable Triggers – Drop Triggers.

Question : How to disable all the triggers for database? Additionally, how to disable all the triggers for all servers?Answer:Disable all the triggers for a single database:USE AdventureWorks;GODISABLE TRIGGER Person.uAddress ON AdventureWorks;GO

Disable all the triggers for all servers:USE AdventureWorks;GODISABLE TRIGGER ALL ON ALL SERVER;GO

SQL SERVER – 2008 – Server Consolidation WhitePaper Download

October 28, 2007 by pinaldave

Server Consolidation with SQL Server 2008Writer: Martin EllisReviewer: Prem Mehra,Lindsey Allen, Tiffany Wissner, Sambit SamalPublished: March 2009

Microsoft SQL Server 2008 supports multiple options for server consolidation, which provides organizations with the flexibility to choose the consolidation approach that best meets their requirements to centralize data services management and reduce hardware and maintenance costs. By providing centralized management, auditing, and monitoring capabilities, SQL Server 2008 makes it easy to manage multiple databases and data services, which significantly reduces administrative overheads in large enterprises. Finally, SQL Server 2008 provides the reassurance of industry-leading performance and scalability, and unprecedented control over server resource to maximize the performance of consolidated data services.

Download WhitePaper

Abstract courtesy : Microsoft

SQL SERVER – 2005 – Get Current User – Get Logged In User

October 27, 2007 by pinaldave

Interesting enough Jr. DBA asked me how he can get current user for any particular query is ran. He said he wants it for debugging purpose as well for security purpose. I totally understand the need of this request. Knowing the current user can be extremely helpful in terms of security.

To get current user run following script in Query Editor

SELECT SYSTEM_USER

SYSTEM_USER will return current user. From Book On-Line – SYSTEM_USER returns the name of the currently executing context. If the EXECUTE AS statement has been used to switch context, SYSTEM_USER returns the name of the impersonated context.

Page 37: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Deterministic Functions and Nondeterministic Functions

October 26, 2007 by pinaldave

Deterministic functions always returns the same output result all the time it is executed for same input values. i.e. ABS, DATEDIFF, ISNULL etc.

Nondeterministic functions may return different results each time they are executed. i.e. NEWID, RAND, @@CPU_BUSY etc. Functions that call extended stored procedures are nondeterministic. User-defined functions that create side effects on the database are not recommended.

SQL SERVER – 2005 – Forced Parameterization and Simple Parameterization – T-SQL and SSMS

October 25, 2007 by pinaldave

SQL Server compiles query and saves the procedures cache plans in the database. When the same query is called it uses compiled execution plan which improves the performance by saving compilation time. Queries which are parametrized requires less recompilation and dynamically built queries needs compilations and recompilation very frequently. Forced parameterization may improve the performance of certain databases by reducing the frequency of query compilations and recompilations. Database which has high volumes of the queries can be most benefited from this feature.

When the PARAMETERIZATION option is set to FORCED, any literal value that appears in a SELECT, INSERT, UPDATE or DELETE statement is converted to a parameter during query compilation. When the PARAMETERIZATION database option is SET to SIMPLE, the SQL Server query optimizer may choose to parametrize the queries.

Using T-SQL:-- Change database Parameterization to ForcedALTER DATABASE AdventureWorksSET PARAMETERIZATION FORCEDGO-- Change database Parameterization to SimpleALTER DATABASE AdventureWorksSET PARAMETERIZATION SimpleGO

Using SQL Server Management Studio:Right Click on Database >> Click On Property >> Click on Options >> Change Paramterization Attribute to

Page 38: 9 Jan 01, 2007-431 Dec 31, 2007

either SIMPLE or FORCED.

This article is just an introduction. There are lots of things to read. I recommend to read references listed below.

SQL SERVER – Simple Example of WHILE Loop With CONTINUE and BREAK Keywords

October 24, 2007 by pinaldave

This is question is one of those question which is very simple and most of the users get it correct, however few users find it confusing for first time. I have tried to explain the usage of simple WHILE loop in first example. BREAK keyword will exit the stop the while loop and control is moved to next statement after the while loop. CONTINUE keyword skips all the statement after its execution and control is sent to first statement of while loop. Run following examples in Query Editor and see the result. This is very easy to understand example.

1) Example of WHILE LoopDECLARE @intFlag INTSET @intFlag = 1WHILE (@intFlag <=5)BEGINPRINT @intFlagSET @intFlag = @intFlag + 1ENDGO

ResultSet:123

Page 39: 9 Jan 01, 2007-431 Dec 31, 2007

45

2) Example of WHILE Loop with BREAK keywordDECLARE @intFlag INTSET @intFlag = 1WHILE (@intFlag <=5)BEGINPRINT @intFlagSET @intFlag = @intFlag + 1IF @intFlag = 4BREAK;ENDGO

ResultSet:123

3) Example of WHILE Loop with CONTINUE and BREAK keywordsDECLARE @intFlag INTSET @intFlag = 1WHILE (@intFlag <=5)BEGINPRINT @intFlagSET @intFlag = @intFlag + 1CONTINUE;IF @intFlag = 4 -- This will never executedBREAK;ENDGO

ResultSet:12345

SQL SERVER – Get Permissions of My Username / Userlogin on Server / Database

October 23, 2007 by pinaldave

Few days ago, I was invited to one of the largest database company. I was asked to review database schema and propose changes to it. There was special username or userlogic was created for me, so I can review their database. I was very much interested to know what kind of permissions I was assigned per server level and database level. I did not feel like asking there Sr. DBA the question about permissions.

I run following two queries to know what are the permissions I am assigned at Server level and Database level.SELECT * FROM fn_my_permissions(NULL, 'SERVER');USE AdventureWorks;SELECT * FROM fn_my_permissions (NULL, 'DATABASE');GOResults were interesting. After I came back from my visit, I ran above script on my personal database server, where I logged as SA.

Resultset for Server:entity_name subentity_name permission_nameserver CONNECT SQLserver SHUTDOWNserver CREATE ENDPOINTserver CREATE ANY DATABASEserver ALTER ANY LOGINserver ALTER ANY CREDENTIAL

Page 40: 9 Jan 01, 2007-431 Dec 31, 2007

server ALTER ANY ENDPOINTserver ALTER ANY LINKED SERVERserver ALTER ANY CONNECTIONserver ALTER ANY DATABASEserver ALTER RESOURCESserver ALTER SETTINGSserver ALTER TRACEserver ADMINISTER BULK OPERATIONSserver AUTHENTICATE SERVERserver EXTERNAL ACCESS ASSEMBLYserver VIEW ANY DATABASEserver VIEW ANY DEFINITIONserver VIEW SERVER STATEserver CREATE DDL EVENT NOTIFICATIONserver CREATE TRACE EVENT NOTIFICATIONserver ALTER ANY EVENT NOTIFICATIONserver ALTER SERVER STATEserver UNSAFE ASSEMBLYserver CONTROL SERVER

ResultSet for Database:entity_name subentity_name permission_namedatabase CREATE TABLEdatabase CREATE VIEWdatabase CREATE PROCEDUREdatabase CREATE FUNCTIONdatabase CREATE RULEdatabase CREATE DEFAULTdatabase BACKUP DATABASEdatabase BACKUP LOGdatabase CREATE DATABASEdatabase CREATE TYPEdatabase CREATE ASSEMBLYdatabase CREATE XML SCHEMA COLLECTIONdatabase CREATE SCHEMAdatabase CREATE SYNONYMdatabase CREATE AGGREGATEdatabase CREATE ROLEdatabase CREATE MESSAGE TYPEdatabase CREATE SERVICEdatabase CREATE CONTRACTdatabase CREATE REMOTE SERVICE BINDINGdatabase CREATE ROUTEdatabase CREATE QUEUEdatabase CREATE SYMMETRIC KEYdatabase CREATE ASYMMETRIC KEYdatabase CREATE FULLTEXT CATALOGdatabase CREATE CERTIFICATEdatabase CREATE DATABASE DDL EVENT NOTIFICATIONdatabase CONNECTdatabase CONNECT REPLICATIONdatabase CHECKPOINTdatabase SUBSCRIBE QUERY NOTIFICATIONSdatabase AUTHENTICATEdatabase SHOWPLANdatabase ALTER ANY USERdatabase ALTER ANY ROLEdatabase ALTER ANY APPLICATION ROLEdatabase ALTER ANY SCHEMAdatabase ALTER ANY ASSEMBLYdatabase ALTER ANY DATASPACEdatabase ALTER ANY MESSAGE TYPEdatabase ALTER ANY CONTRACTdatabase ALTER ANY SERVICEdatabase ALTER ANY REMOTE SERVICE BINDINGdatabase ALTER ANY ROUTEdatabase ALTER ANY FULLTEXT CATALOGdatabase ALTER ANY SYMMETRIC KEYdatabase ALTER ANY ASYMMETRIC KEY

Page 41: 9 Jan 01, 2007-431 Dec 31, 2007

database ALTER ANY CERTIFICATEdatabase SELECTdatabase INSERTdatabase UPDATEdatabase DELETEdatabase REFERENCESdatabase EXECUTEdatabase ALTER ANY DATABASE DDL TRIGGERdatabase ALTER ANY DATABASE EVENT NOTIFICATIONdatabase VIEW DATABASE STATEdatabase VIEW DEFINITIONdatabase TAKE OWNERSHIPdatabase ALTERdatabase CONTROL

SQL SERVER – Difference Between @@Version and xp_msver – Retrieve SQL Server Information

October 22, 2007 by pinaldave

Just a day ago, I was asked which SQL Server version I am using. I said SQL Server 2005. However, the person I was talking was looking for more information then that. He requested more detail about the version. I responded with SQL Server 2005 Service Pack 2. After the discussion was over I thought there must be some global variable which brings back this information. I took guess and typed following command in SQL Query Editor

SELECT @@Version 'SQL Version'

I was really glad when it worked and returned following result.

Resultset:Microsoft SQL Server 2005 – 9.00.3054.00 (Intel X86) Mar 23 2007 16:28:52 Copyright (c) 1988-2005 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

One additional information I learned that Microsoft was established on 1988.

After searching online I also realized that there is Extended Stored Procedure xp_msver, which also returns the similar results however, it returns much more details. Let us see its example.

EXEC xp_msver

Resultset:Index Name Internal_Value Character_Value—— ——————————– ————– ————————————————————————————————————————1 ProductName NULL Microsoft SQL Server2 ProductVersion 589824 9.00.3054.003 Language 1033 English (United States)4 Platform NULL NT INTEL X865 Comments NULL NT INTEL X866 CompanyName NULL Microsoft Corporation7 FileDescription NULL SQL Server Windows NT8 FileVersion NULL 2005.090.3054.009 InternalName NULL SQLSERVR10 LegalCopyright NULL © Microsoft Corp. All rights reserved.11 LegalTrademarks NULL Microsoft® is a registered trademarkof Microsoft Corporation. Windows(TM) is a trademark of Microsoft Corporation12 OriginalFilename NULL SQLSERVR.EXE13 PrivateBuild NULL NULL14 SpecialBuild 200146944 NULL15 WindowsVersion 170393861 5.1 (2600)16 ProcessorCount 1 117 ProcessorActiveMask 1 0000000118 ProcessorType 586 PROCESSOR_INTEL_PENTIUM19 PhysicalMemory 1023 1023 (1073111040)20 Product ID NULL NULL

Page 42: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 – Limitation of Online Index Rebuld Operation

October 21, 2007 by pinaldave

Just a day ago, during one interview question of Online Indexing come up. I really enjoy discussing this issue as I was talking with candidate who was very smart.

Following two questions were discussed.

1) What is Online Index Rebuild Operation?Online operation means when online operations are happening the database are in normal operational condition, the processes which are participating in online operations does not require exclusive access to database.Read about this in-depth in my previous article SQL SERVER – 2005 – Explanation and Script for Online Index Operations – Create, Rebuild, Drop

2) What are the limitation of the Online Index Rebuild Operation?Following indexes can not be build online. We were able to come up with first four kind of the indexes. I researched book online before I wrote this article have listed all the six exceptions of index rebuild operation.

Disabled indexes XML indexes Indexes on local temp tables Partitioned indexes Clustered indexes if the underlying table contains LOB data types Nonclustered indexes that are defined with LOB data type columns

SQL SERVER – Set Server Level FILLFACTOR Using T-SQL Script

October 20, 2007 by pinaldave

As title is very clear what this post is about I will not write long description. I have listed definition of FILLFACTOR from BOL here.

FILLFACTOR

Specifies a percentage that indicates how full the Database Engine should make the leaf level of each index page during index creation or alteration. fillfactor must be an integer value from 1 to 100. The default is 0.

T-SQL Script to set Server level FILLFACTOR to 90

EXEC sys.sp_configure 'show advanced options', '1'RECONFIGURE WITH OVERRIDEGOEXEC sys.sp_configure 'fill factor (%)', '90'GORECONFIGURE WITH OVERRIDEGOEXEC sys.sp_configure 'show advanced options', '0'RECONFIGURE WITH OVERRIDEGO

SQL SERVER – Types of DBCC Commands When Used as Database Console Commands

October 19, 2007 by pinaldave

Just a day ago, while discussing some SQL issues with one of the Sr. Database Administrator in India, we end up discussing DBCC as Database Console Commands when used as T-SQL. We both tried to remember

Page 43: 9 Jan 01, 2007-431 Dec 31, 2007

what are the types of DBCC as Database Console Commands and could not come up with more than two types, however we both knew there are four.

When the conversation was over, I looked up MSDN for the types of the DBCC. I found following documentation here. There are four types of the Database Console Commands.

Maintenance

Maintenance tasks on a database, index, or filegroup.

Examples:

DBCC INPUTBUFFER

DBCC SHOWCONTIG

Miscellaneous

Miscellaneous tasks such as enabling trace flags or removing a DLL from memory.

Examples:

DBCC CHECKCATALOG

DBCC CHECKIDENT

Informational

Tasks that gather and display various types of information.

Examples:

DBCC DROPCLEANBUFFERS

DBCC SHRINKFILE

Validation

Validation operations on a database, table, index, catalog, filegroup, or allocation of database pages.

Examples:

DBCC dllname (FREE)

DBCC TRACEOFF

SQL SERVER – 2005 – Fix : Error : Msg 7411, Level 16, State 1 Server is not configured for RPC

October 18, 2007 by pinaldave

Error : Msg 7411, Level 16, State 1 Server is not configured for RPC

This was annoying error which was fixed by Jr. DBA, whom I am personally training at my organization. I think he is going to be great programmer. He worked in my organization for more than 8 months. I finally have decided to coach him myself. When I encountered this error, I gave him task to figure this out himself. I absolutely gave him no direction and very few min to fix this problem. As you might have

Page 44: 9 Jan 01, 2007-431 Dec 31, 2007

guessed without using internet help (as there is no help online available for this error) he found the solution.

Go to ServerInstance and follow next two diagrams. They are self-explanatory. Turn on the RPC from False to True.

Page 45: 9 Jan 01, 2007-431 Dec 31, 2007

SQLAuthority News – Book Review – Backup & Recovery (Paperback)

October 17, 2007 by pinaldave

Backup & Recovery [ILLUSTRATED] (Paperback)by W. Curtis Preston (Author)

Page 46: 9 Jan 01, 2007-431 Dec 31, 2007

Link to Amazon (This is not affiliate Link)

Short Summary:This book’s does not only teaches you have to create safe backup but it takes you to the next level where a large organization can save tons of dollars a year by making their backup and restore faster and more reliable process.

Detail Summary:Backup and Recovery is the most interesting subject to me. I have always enjoyed reading and writing about this subject. I personally believe that without proper backup and ability to restore the backup to recover the system to original state, any organization is at great risk. Biggest change in the recent industry has been the proliferation of Windows, Exchange and SQL Server.

This book is aimed at the people who feel that the commercial software precuts aren’t meeting all their needs. Almost everything which is discussed in this book is either included with operating system or application. This book vastly covers the tools which are open-source projects. This book covers how to back up and recover everything from a basic Linux, Windows, or Max OS workstation to a complicated DB2, Oracle, Sybase or SQL Server (my favorite) databases as well many other things.

This book suggests tools which are less than $100 or in most of the cases almost free. This book is for every developer or system administrator. This book tells users how exactly to choose which backup tool is best. This book stays away from ever changing product names. It focuses on concepts only – what a novel approach! I appreciate author for the same.

This book focuses on two people mainly – Database Administrators (DBA) and System Administrator (SA). Concepts for both the roles are explained in detail in this book. In author’s own word “I explained the backup utilities in plain language so that any DBA can understand them, and I explain database architecture in such a way that an SA, even one who has never before seen a database, can understand it.”

A book on Backup and Recovery are incomplete without discussing Bare-Metal Recovery. When operating system disk is lost and it is needed to recovered, it is called Bare-Metal Recovery. Out of hundreds of way to recover, this book focuses on best ways for Bare-Metal Recovery.

Working as SQL Server Principal Database Administrator, I have been involved with Database Backup since day one. In several years of my career, I have seen many large organizations ignoring backup of master

Page 47: 9 Jan 01, 2007-431 Dec 31, 2007

database. I was very glad when I see in just three lines author has conveyed clear message about master database. These three lines explain the understanding of author for SQL Server.

“It is extremely important to backup the master database on regular basis. This database holds all the configuration information for the running system as well as all the configuration information for all databases and other information such as logon accounts. Without this database, the rest of the system is useless!”

Rating: 4 and 1/2 stars

In Summary, Backup and Recovery is not everything. This book takes you to highest level of the backup and recovery at conceptually strong working examples.

SQL SERVER – Three T-SQL Script to Create Primary Keys on Table

October 16, 2007 by pinaldave

I have always enjoyed writing about three topics Constraint and Keys, Backup and Restore and Datetime Functions.

Primary Keys constraints prevents duplicate values for columns and provides unique identifier to each column, as well it creates clustered index on the columns.-- Primary Key Constraint upon Table Created Method 1USE AdventureWorksGOCREATE TABLE ConstraintTable(ID INT CONSTRAINT Ct_ID PRIMARY KEY, ColSecond INT)GO--Clean UpDROP TABLE ConstraintTableGO-- Primary Key Constraint upon Table Created Method 2USE AdventureWorksGOCREATE TABLE ConstraintTable(ID INT, ColSecond INT,CONSTRAINT Ct_ID PRIMARY KEY (ID))GO--Clean UpDROP TABLE ConstraintTableGO-- Primary Key Constraint after Table Created Method 3USE AdventureWorksGOCREATE TABLE ConstraintTable(ID INT, ColSecond INT)GO-- Primary Key Column must not allow NULLALTER TABLE ConstraintTableALTER COLUMN ID INT NOT NULLGOALTER TABLE ConstraintTableADD CONSTRAINT Ct_ID PRIMARY KEY (ID)--Clean UpDROP TABLE ConstraintTableGO

SQL SERVER – 2005 – Driver for PHP Community Technology Preview (October 2007)

October 16, 2007 by pinaldave

In its continued commitment to interoperability, Microsoft has released a new SQL Server 2005 Driver for PHP. The SQL Server 2005 Driver for PHP Community Technology Preview (CTP) download is available to all SQL Server users at no additional charge. The SQL Server 2005 Driver for PHP is a PHP 5 extension that

Page 48: 9 Jan 01, 2007-431 Dec 31, 2007

allows for the reading and writing of SQL Server data from within PHP scripts. The extension provides a procedural interface for accessing data in all editions of SQL Server 2005 and SQL Server 2000.

How to install driver1. Download sqlsrv-for-php_version_language.exe to a temporary directory.2. Run sqlsrv-for-php_version_language.exe.3. Enter an installation directory when prompted. It is recommended that you extract the file to %ProgramFiles% with the default directory: “Microsoft SQL Server 2005 Driver for PHP”.4. After extracting the files, read the Installation section of the Php_sqlsrv_readme.txt file for next steps.

Download the Driver

SQL SERVER – T-SQL Script to Add Clustered Primary Key

October 11, 2007 by pinaldave

Jr. DBA asked me three times in a day, how to create Clustered Primary Key. I gave him following sample example. That was the last time he asked “How to create Clustered Primary Key to table?”USE [AdventureWorks]GOALTER TABLE [Sales].[Individual]ADD CONSTRAINT [PK_Individual_CustomerID]PRIMARY KEY CLUSTERED([CustomerID] ASC)

SQL SERVER – Pre-Code Review Tips – Tips For Enforcing Coding Standards

October 12, 2007 by pinaldave

Each organization has its own coding standards and enforcement rules. It is sometime difficult for DBAs to change code following code review, as it may affect many different layers of the application. In large organizations, many stored procedures are written and modified every day. It is smart to keep watch on all stored procedures, at frequent intervals, before code comes to final code review. Pre-code reviewing in this manner will save lots of time. I run a few scripts every day to check the status of the all stored procedures on our development server. Doing so gives me a good indication about which stored procedures are not up to coding standards.

Read my complete article SQL Server Pre-Code Review Tips

Read SQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – 2005 – SQL Server Surface Area Configuration Tool Examples and Explanation

October 13, 2007 by pinaldave

Microsoft has turned off all the potential features of SQL Server 2005 that could be susceptible to security risks and hacker attacks. Many features of SQL Server 2005 i.e. xp_cmdshell, DAC etc comes disabled by default, this makes the vulnerable surface area less visible to potential attacks. The Surface Area Configuration tool provides DBAs with a single, easy-to-use method of configuring external security of SQL Server. Use SQL Server Surface Area Configuration to enable, disable, start, or stop the features, services, and remote connectivity of your SQL Server 2005 installations. You can use SQL Server Surface Area Configuration on local and remote servers.

Following are the features of the SQL Server Surface Area Configuration Tool, which can be turned on and off as needed by application.

Analysis Services Features

Ad-hoc Data Mining Queries

Page 49: 9 Jan 01, 2007-431 Dec 31, 2007

Anonymous Connections Linked Objects User-Defined Functions

Database Engine Features

Ad-hoc Remote Queries CLR Integration Database Mail HTTP Access OLE Automation Service Brokerenables SMO and DMO SQL Mail Web Assistant xp_cmdshell

Reporting Services Features

HTTP and Web Service Requests Scheduled Events and Report Delivery

Following are the services of the SQL Server Surface Area Configuration Tool, which can be turned on and off as needed by application. Not all services are available in all the edition of SQL Server.

Analysis Services Database Engine Full-Text Search Service Integration Services Service MSSQLServerADHelper Service Notification Services Service Reporting Services Service SQL Server Agent Service SQL Server Browser Service SQL Server Writer Service

Following diagrams explains the methods to enable the features and services using SQL Server Surface Area Configuration Tool.

1) On the Start menu, point to All Programs, Microsoft SQL Server 2005, Configuration Tools, and then click SQL Server Surface Area Configuration.

2) Click the change computer link adjacent to Configure Surface Area for. The default value is localhost. This can be changed and connected to any other SQL Server node.

Page 50: 9 Jan 01, 2007-431 Dec 31, 2007
Page 51: 9 Jan 01, 2007-431 Dec 31, 2007

3) After selecting the computer to configure, you can launch either of services.

Surface Area Configuration for Services and Connections

Page 52: 9 Jan 01, 2007-431 Dec 31, 2007
Page 53: 9 Jan 01, 2007-431 Dec 31, 2007

Surface Area Configuration for Features

Page 54: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Three Rules to Use UNION

October 14, 2007 by pinaldave

I have previously written two articles on UNION and they are quite popular. I was reading SQL book Sams Teach Yourself Microsoft SQL Server T-SQL in 10 Minutes By Ben Forta and I came across three rules of UNION and I felt like mentioning them here.

UNION RULES

A UNION must be composed of two or more SELECT statements, each separated by the keyword UNION.

Each query in a UNION must contain the same columns, expressions, or aggregate functions, and they must be listed in the same order.

Column datatypes must be compatible: They need not be the same exact same type, but they must be of a type that SQL Server can implicitly convert.

SQL SERVER – Union vs. Union All – Which is better for performance?SQL SERVER – Insert Multiple Records Using One Insert Statement – Use of UNION ALL

SQL SERVER – Explanation and Understanding NOT NULL Constraint

October 15, 2007 by pinaldave

NOT NULL is integrity CONSTRAINT. It does not allow creating of the row where column contains NULL value. Most discussed question about NULL is what is NULL? I will not go in depth analysis it. Simply put NULL is unknown or missing data. When NULL is present in database columns, it can affect the integrity of the database. I really do not prefer NULL in database unless they are absolutely necessary. (Please make sure it is just my preference, and I use NULL it is absolutely needed).

To prevent nulls to be inserted in the database, table should have NOT NULL constraint. Two ways NOT NULL constraint can be implemented on database.

Page 55: 9 Jan 01, 2007-431 Dec 31, 2007

1) Implement Constraint when Table is created2) Implement Constraint after Table is created

Following example demonstrates both the way to create NOT NULL constraints.USE AdventureWorksGO-- NOT NULL Constraint when Table is createdCREATE TABLE ConstraintTable(ID INT, ColSecond INT NOT NULL)GO-- NOT NULL Constraint after Table is createdALTER TABLE ConstraintTableALTER COLUMN ID INT NOT NULLGO--Clean UpDROP TABLE ConstraintTableGO

SQL SERVER – 2005 – Sample Example of RANKING Functions – ROW_NUMBER, RANK, DENSE_RANK, NTILE

October 9, 2007 by pinaldave

I have not written about this subject for long time, as I strongly believe that Book On Line explains this concept very well. SQL Server 2005 has total of 4 ranking function. Ranking functions return a ranking value for each row in a partition. All the ranking functions are non-deterministic.

ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>)Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

RANK () OVER ([<partition_by_clause>] <order_by_clause>)Returns the rank of each row within the partition of a result set.

DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>)Returns the rank of rows within the partition of a result set, without any gaps in the ranking.

NTILE (integer_expression) OVER ([<partition_by_clause>] <order_by_clause>)Distributes the rows in an ordered partition into a specified number of groups.

All the above definition and syntax are taken from BOL. It is difficult to explain above function anything else than what they are explained in BOL. Following example is excellent example from BOL again. This function explains usage of all the four function together in one query.USE AdventureWorks;GOSELECT c.FirstName, c.LastName,ROW_NUMBER() OVER (ORDER BY a.PostalCode) AS 'Row Number',RANK() OVER (ORDER BY a.PostalCode) AS 'Rank',DENSE_RANK() OVER (ORDER BY a.PostalCode) AS 'Dense Rank',NTILE(4) OVER (ORDER BY a.PostalCode) AS 'Quartile',s.SalesYTD, a.PostalCodeFROM Sales.SalesPerson sINNER JOIN Person.Contact cON s.SalesPersonID = c.ContactIDINNER JOIN Person.Address aON a.AddressID = c.ContactIDWHERE TerritoryID IS NOT NULLAND SalesYTD <> 0;

Page 56: 9 Jan 01, 2007-431 Dec 31, 2007

Resultset:

Most of the content of this article is taken from BOL.

SQL SERVER – 2005 – Connection Property of SQL Server Management Studio SSMS

October 8, 2007 by pinaldave

Following images quickly explain how to connect to SQL Server with different connection property. It can be useful when connection properties needs to be changed for SQL Server when connected. I use this in my company when I connect to one of our server using named pipes instead of TCP/IP.

Page 57: 9 Jan 01, 2007-431 Dec 31, 2007

Image 1: Default Login

Image 2: Options

Page 58: 9 Jan 01, 2007-431 Dec 31, 2007

Image 3: Option Network Protocol Example

SQLAuthority News – Latest Interesting Downloads and Articles

October 7, 2007 by pinaldave

White Paper: Precision Considerations for Analysis Services UsersThis white paper covers accuracy and precision considerations in SQL Server 2005 Analysis Services. For example, it is possible to query Analysis Services with similar queries and obtain two different answers. While this appears to be a bug, it actually is due to the fact that Analysis Services caches query results and the imprecision that is associated with approximate data types. This white paper discusses how these issues manifest themselves, why they occur, and best practices to minimize their effect.

Microsoft SQL Server 2005 JDBC Driver 1.1In its continued commitment to interoperability, Microsoft provides a Java Database Connectivity (JDBC) driver for use with SQL Server 2005. The SQL Server 2005 JDBC Driver is available to all SQL Server users at no additional charge, and provides access to SQL Server 2000 and SQL Server 2005 from any Java application, application server, or Java-enabled applet. This driver is a Type 4 JDBC driver that provides database connectivity through the standard JDBC application program interfaces (APIs) available in J2EE (Java2 Enterprise Edition).

High Performance Data Warehouse with SQL Server 2005This document discusses things to consider when architecting a large, high-performance relational data warehouse, especially one that is host to unpredictable ad hoc queries. The discussion includes some of the new features of SQL Server 2005 and considerations to take into account when using these features. It also includes methodologies for creating and storing pre-aggregated result sets to facilitate mainstream queries and reports.

Page 59: 9 Jan 01, 2007-431 Dec 31, 2007

Abstract courtesy : Microsoft

SQL SERVER – Executing Remote Stored Procedure – Calling Stored Procedure on Linked Server

October 6, 2007 by pinaldave

I was going through comments on various posts to see if I have missed to answer any comments. I realized that there are quite a few times I have answered question which discuss about how to call stored procedure or query on linked server or another server. This is very detailed topic, I will keep it very simple.

I am making assumptions that remote server is already set up as linked server with proper permissions in application and network is arranged.

Method 1 : Remote Stored Procedure can be called as four part name:Syntax:

EXEC [RemoteServer] .DatabaseName.DatabaseOwner.StoredProcedureName

‘Params’Example:

EXEC [DEVSQL] .AdventureWorks.dbo.uspGetEmployeeManagers ‘42′

Method 2 : Use Distributed Query functions (OpenQuery())Syntax: SELECT *

FROM OPENQUERY([RemoteServer],DatabaseName.DatabaseOwner.StoredProcedureName)

Example: SELECT *

FROM OPENQUERY([DEVSQL],AdventureWorks.dbo.spAdmin_GetAllUsers)

Let me know if you want me write about above two methods in detail.

SQL SERVER – 2005 – Open SSMS From Command Prompt – sqlwb.exe Example

October 5, 2007 by pinaldave

This article is written by request and suggestion of Sr. Web Developer at my organization. Due to nature of this article most of the content are referred from Book On-Line. sqlwb command prompt utility which opens SQL Server Management Studio. sqlwb command does not run queries from command prompt. sqlcmd utility runs queries from command prompt, read for more information.

The syntax of this sqlwb is very simple. I will copy complete syntax from BOL here :sqlwb[scriptfile] [projectfile] [solutionfile][-S servername] [-d databasename] [-U username] [-P password][-E] [-nosplash] [-?]

I use following script very frequently.

1) Open SQL Server Management Studio.sqlwb

2) Open SQL Server Management Studio with windows authentication with no splash screen and default database as AdventureWorkssqlwb -E -S SQLServerName -D AdventureWorks – nosplash

Page 60: 9 Jan 01, 2007-431 Dec 31, 2007

3) Open SQL Server Management Studio with username and password with no splash screen and default database as AdventureWorkssqlwb -S SQLServerName -U MyUserName -P MyPassWord -D AdventureWorks – nosplash

To execute above commands you should have access to sqlwb.exe file. My local computer has sqlwb file in folder : C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDEClick on Start >> click on run >> type in following command to launch SQL Server Management Studio :“C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\sqlwb.exe” -E -S SQL -nosplash

SQL SERVER – 2005 – Different Types of Cache Objects

October 4, 2007 by pinaldave

About two months ago I reviewed book SQL Server 2005 Practical Troubleshooting: The Database Engine. Yesterday I received a request from reader, if I can write something from this book, which is not common knowledge in DBA community. I really like the idea, however I must respect the Authors copyright about this book. This book is unorthodox SQL book, it talks about things which can get you to fix your problem faster, if problem is discussed in book. There are few places it teaches behind the scene SQL stories.

Following four lines are taken from Chapter 4 ; Procedure cache Issues Page 184-185.

Serveral kind of objects can be stored in the procedure cache:

Compiled Plans: When the query optimizer finishes compiling a query plan, the principal output is compiled plan.

Execution contexts: While executing a compiled plan, SQL Server has to keep track of information about the state of execution.

Cursors: Cursors track the execution state of server-side cursors, including the cursor’s current location within a resultset.

Algebrizer trees: The Algebrizer’s job is to produce an algebrizer tree, which represents the logic structure of a query.

Book has above four topics discussed in depth. I will limit myself with one line due to copyright reasons. You can read my review about book on amazon(not affiliate link).

SQL SERVER – 2005 – Explanation of TRY…CATCH and ERROR Handling With RAISEERROR Function

October 3, 2007 by pinaldave

One of the developer at my company thought that we can not use RAISEERROR function in new feature of SQL Server 2005 TRY…CATCH. When asked for explanation he suggested SQL SERVER – 2005 Explanation of TRY…CATCH and ERROR Handling article as excuse suggesting that I did not give example of RAISEERROR with TRY…CATCH. We all thought it was funny. Just to keep record straight, TRY…CATCH can sure use RAISEERROR function.

First read original article for additional information about how TRY…CATCH works with ERROR codes. SQL SERVER – 2005 Explanation of TRY…CATCH and ERROR Handling

Example 1 : Simple TRY…CATCH without RAISEERROR functionBEGIN TRYDECLARE @MyInt INT;-- Following statement will create Devide by Zero ErrorSET @MyInt = 1/0;END TRYBEGIN CATCHSELECT 'Divide by zero error encountered.' ErrorMessage

Page 61: 9 Jan 01, 2007-431 Dec 31, 2007

END CATCH;GO

ResultSet:ErrorMessage———————————Divide by zero error encountered.

Example 2 : Simple TRY…CATCH with RAISEERROR functionBEGIN TRYDECLARE @MyInt INT;-- Following statement will create Devide by Zero ErrorSET @MyInt = 1/0;END TRYBEGIN CATCHDECLARE @ErrorMessage NVARCHAR(4000);SELECT @ErrorMessage = ERROR_MESSAGE();RAISERROR (@ErrorMessage, 16, 1);END CATCH;GO

ResultSet:Msg 50000, Level 16, State 1, Line 9Divide by zero error encountered.

SQL SERVER – Find Name of The SQL Server Instance

October 2, 2007 by pinaldave

Few days ago, there was complex condition when we had one database on two different server. We were migrating database from one server to another server using nightly backup and restore. Based on database server stored procedures has to run different logic. We came up with two different solutions.

1) When database schema is very much changed, we wrote completely new stored procedure and deprecated older version once it was not needed.

2) When logic depended on Server Name we used global variable @@SERVERNAME. It was very convenient while writing migrating script which depended on server name for the same database.

Syntax:SELECT @@SERVERNAME AS 'Server Name'ResultSet:Server Name——————–SQLAUTHORITY

SQL SERVER – 2005 – OUTPUT Clause Example and Explanation with INSERT, UPDATE, DELETE

October 1, 2007 by pinaldave

SQL Server 2005 has new OUTPUT clause, which is quite useful. OUTPUT clause has accesses to inserted and deleted tables (virtual tables) just like triggers. OUTPUT clause can be used to return values to client clause. OUTPUT clause can be used with INSERT, UPDATE, or DELETE to identify the actual rows affected by these statements.

OUTPUT clause can generate table variable, a permanent table, or temporary table. Even though, @@Identity will still work in SQL Server 2005, however I find OUTPUT clause very easy and powerful to use. Let us understand OUTPUT clause using example.—————————————————————————————————————————-Example 1 : OUTPUT clause into Table with INSERT statement————————————————————————————————————————USE AdventureWorks;GO--------Creating the table which will store permanent table

Page 62: 9 Jan 01, 2007-431 Dec 31, 2007

CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))----Creating temp table to store ovalues of OUTPUT clauseDECLARE @TmpTable TABLE (ID INT, TEXTVal VARCHAR(100))----Insert values in real table as well use OUTPUT clause to insert----values in the temp table.INSERT TestTable (ID, TEXTVal)OUTPUT Inserted.ID, Inserted.TEXTVal INTO @TmpTableVALUES (1,'FirstVal')INSERT TestTable (ID, TEXTVal)OUTPUT Inserted.ID, Inserted.TEXTVal INTO @TmpTableVALUES (2,'SecondVal')----Check the values in the temp table and real table----The values in both the tables will be sameSELECT * FROM @TmpTableSELECT * FROM TestTable----Clean up timeDROP TABLE TestTableGOResultSet 1:ID TextVal——————— ————————1 FirstVal2 SecondVal

ID TextVal——————— ———————1 FirstVal2 SecondVal—————————————————————————————————————————-Example 2 : OUTPUT clause with INSERT statement————————————————————————————————————————USE AdventureWorks;GO----Creating the table which will store permanent tableCREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))----Insert values in real table as well use OUTPUT clause to insert----values in the temp table.INSERT TestTable (ID, TEXTVal)OUTPUT Inserted.ID, Inserted.TEXTValVALUES (1,'FirstVal')INSERT TestTable (ID, TEXTVal)OUTPUT Inserted.ID, Inserted.TEXTValVALUES (2,'SecondVal')----Clean up timeDROP TABLE TestTableGOResultSet 2:ID TextVal——————— ———————1 FirstVal

(1 row(s) affected)

ID TextVal——————— ———————2 SecondVal—————————————————————————————————————————-Example 3 : OUTPUT clause into Table with UPDATE statement————————————————————————————————————————USE AdventureWorks;GO----Creating the table which will store permanent tableCREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))----Creating temp table to store ovalues of OUTPUT clauseDECLARE @TmpTable TABLE (ID_New INT, TEXTVal_New VARCHAR(100),ID_Old INT, TEXTVal_Old VARCHAR(100))----Insert values in real tableINSERT TestTable (ID, TEXTVal)

Page 63: 9 Jan 01, 2007-431 Dec 31, 2007

VALUES (1,'FirstVal')INSERT TestTable (ID, TEXTVal)VALUES (2,'SecondVal')----Update the table and insert values in temp table using Output clauseUPDATE TestTableSET TEXTVal = 'NewValue'OUTPUT Inserted.ID, Inserted.TEXTVal, Deleted.ID, Deleted.TEXTVal INTO @TmpTableWHERE ID IN (1,2)----Check the values in the temp table and real table----The values in both the tables will be sameSELECT * FROM @TmpTableSELECT * FROM TestTable----Clean up timeDROP TABLE TestTableGOResultSet 3:ID_New TextVal_New ID_Old TextVal_Old——————— ——————— ——————— ———————1 NewValue 1 FirstVal2 NewValue 2 SecondVal

ID TextVal——————— ———————1 NewValue2 NewValue—————————————————————————————————————————-Example 4 : OUTPUT clause into Table with DELETE statement————————————————————————————————————————USE AdventureWorks;GO----Creating the table which will store permanent tableCREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))----Creating temp table to store ovalues of OUTPUT clauseDECLARE @TmpTable TABLE (ID INT, TEXTVal VARCHAR(100))----Insert values in real tableINSERT TestTable (ID, TEXTVal)VALUES (1,'FirstVal')INSERT TestTable (ID, TEXTVal)VALUES (2,'SecondVal')----Update the table and insert values in temp table using Output clauseDELETEFROM TestTableOUTPUT Deleted.ID, Deleted.TEXTVal INTO @TmpTableWHERE ID IN (1,2)----Check the values in the temp table and real table----The values in both the tables will be sameSELECT * FROM @TmpTableSELECT * FROM TestTable----Clean up timeDROP TABLE TestTableGOResultSet 4:ID TextVal——————— ———————1 FirstVal2 SecondVal

ID TextVal——————— ———————If you run all the above four example, you will find that OUTPUT clause is very useful.

SQL SERVER – 2005 Query Editor – Microsoft SQL Server Management Studio

September 30, 2007 by pinaldave

This post may be very simple for most of the users of SQL Server 2005. Earlier this year, I have received one question many times – Where is Query Analyzer in SQL Server 2005? I wrote small post about it and

Page 64: 9 Jan 01, 2007-431 Dec 31, 2007

pointed many users to that post – SQL SERVER – 2005 Query Analyzer – Microsoft SQL SERVER Management Studio. Recently I have been receiving similar question.

Where is Query Editor in SQL Server 2005? SQL SERVER 2005 has combined Query Analyzer and Enterprise Manager into one Microsoft SQL SERVER Management Studio (MSSMS).

I have been pointing my users to my previous post so far. One of my reader asked recently is it really true SSMS = QE + EM . I realize that my answer is not complete. SQL Server 2005 Query Editor has many other enhancements over previous versions. There are many standard features also brought over from previous tools. From MSDN I found following list which is quite complete and concise.

Statement auto-completion.Parameter tipping for system stored procedures and user-defined functions.Color-coding of Transact-SQL and MDX syntax.Templates to speed development of the T-SQL.Editing of execute and parse queries with SQLCMD extensions.Results presented in either a grid or a free-form text window, or in XML form.Graphical representation of the showplan information.

SQL SERVER – Two Connections Related Global Variables Explained – @@CONNECTIONS and @@MAX_CONNECTIONS

September 29, 2007 by pinaldave

Few days ago, I was searching MSDN and I stumbled upon following two global variables. Following variables are very briefly explained in the BOL. I have taken their definition from BOL and modified BOL example to displayed both the global variable together.

@@CONNECTIONSReturns the number of attempted connections, either successful or unsuccessful since SQL Server was last started.

Page 65: 9 Jan 01, 2007-431 Dec 31, 2007

@@MAX_CONNECTIONSReturns the maximum number of simultaneous user connections allowed on an instance of SQL Server. The number returned is not necessarily the number currently configured.

@@MAX_CONNECTIONS is the maximum number of connections allowed simultaneously to the server. @@CONNECTIONS is incremented with each login attempt, therefore @@CONNECTIONS can be greater than @@MAX_CONNECTIONS.

Example:SELECT GETDATE() AS 'Currunt Time',@@CONNECTIONS AS 'Total Logins so far',@@MAX_CONNECTIONS AS 'Max Connection Simultaneously'

Currunt Time Total Logins so far Max Connection Simultaneously———————– ——————- —————————–2007-09-03 17:28:12.013 71 32767

SQL SERVER – Introduction and Example for DATEFORMAT Command

September 28, 2007 by pinaldave

While doing surprise code review of Jr. DBA I found interesting syntax DATEFORMAT. This keywords is very less used as CONVERT and CAST can do much more than this command. It is still interesting to learn about learn about this new syntax.

Sets the order of the dateparts (month/day/year) for entering datetime or smalldatetime data. This command allows you to input strings that would normally not be recognized by SQL server as dates. The SET DATEFORMAT command lets you specify order of data parts. The options for DATEFORMAT are mdy, dmy, ymd, ydm, myd, or dym. The default DATEFORMAT is mdy. This commands allows to INSERT/UPDATE dates with different formats without doing any special data conversions.The setting of SET DATEFORMAT is set at execute or run time and not at parse time. Following example demonstrate how character string can be converted to proper dateformat using SET DATEFORMAT command.

Example:CREATE TABLE #tempTable (DateFormatSample SMALLDATETIME)SET DATEFORMAT MDYINSERT INTO #tempTableVALUES ('09/28/2007')SET DATEFORMAT YDMINSERT INTO #tempTableVALUES ('2007/28/09')SET DATEFORMAT YMDINSERT INTO #tempTableVALUES ('2007/08/28')SELECT DateFormatSampleFROM #tempTableDROP TABLE #tempTableResultset:DateFormatSample———————–2007-09-28 00:00:002007-09-28 00:00:002007-08-28 00:00:00

SQL SERVER – FIX : Error 3154: The backup set holds a backup of a database other than the existing database

September 27, 2007 by pinaldave

Our Jr. DBA ran to me with this error just a few days ago while restoring the database.

Error 3154: The backup set holds a backup of a database other than the existing database.

Page 66: 9 Jan 01, 2007-431 Dec 31, 2007

Solution is very simple and not as difficult as he was thinking. He was trying to restore the database on another existing active database.

Fix/WorkAround/Solution:

1) Use WITH REPLACE while using the RESTORE command. View Example

2) Delete the older database which is conflicting and restore again using RESTORE command.

I understand my solution is little different than BOL but I use it to fix my database issue successfully.

3) Sample Example :RESTORE DATABASE AdventureWorksFROM DISK = 'C:\BackupAdventureworks.bak'WITH REPLACE

SQLAuthority News – Book Review – Programming SQL Server 2005 [ILLUSTRATED]

September 26, 2007 by pinaldave

Programming SQL Server 2005 [ILLUSTRATED] (Paperback) by Bill Hamilton (Author)

Link to Amazon – This is not affiliate Link

User does not have to be experience SQL Server 2005 programmer to use this book; as it is designed for users of all levels. This book also suggests that user does not have to be experienced with SQL Server 2000. However, I disagree with that. This book only covers new features of SQL Server 2005. Understanding of fundamental relational database concepts is helpful to digest and accept the concepts introduced in this book.

This book covers following perspective of SQL Server 2005 new features.

Tools and utilities Data types T-SQL enhancements Programmability enhancements XML support Native XML web services SQL Management Objects

Page 67: 9 Jan 01, 2007-431 Dec 31, 2007

SQL Server Integration Services SQL Server Reporting Services SQL Server Notification Services SQL Server Service Broker Replication Management Objects SQL Server Agent SQL Server Mobile Edition

The code used in the book is available for download on O’Reilly web site. I always like this as I really do not like to retype examples from the book. Most of the examples of this book use C# code and Visual Studio 2005. One good thing about this book is it uses AdventureWorks sample database, I always prefer book which uses samples database which comes along the SQL Server, this makes it easily useable by developer. This book is also Safari enabled.

Appendix of this book has in depth explanation of the ADO.NET 2.0, which can be quite useful to users interested in the topic. There are very few good books which covers this topic such in depth.

Rating: 4 stars

Summary: This book is quite good for new learning; I enjoy reading it and learning new concepts from this book.

Pinal DavePrincipal Database Administrator(blog.sqlauthority.com)

SQL SERVER – Effect of TRANSACTION on Local Variable – After ROLLBACK and After COMMIT

September 25, 2007 by pinaldave

Few days ago, one of the Jr. Developer asked me this question (What will be the Effect of TRANSACTION on Local Variable – After ROLLBACK and After COMMIT?) while I was rushing to an important meeting. I was getting late so I asked him to talk with his Application Tech Lead. When I came back from meeting both of them were looking for me. They said they are confused. I quickly wrote down following example for them.

Example:PRINT 'After ROLLBACK example'DECLARE @FlagINT INTSET @FlagInt = 1PRINT @FlagInt ---- @FlagInt Value will be 1BEGIN TRANSACTIONSET @FlagInt = 2 ---- @FlagInt Value will be 2PRINT @FlagIntROLLBACK TRANSACTIONPRINT @FlagInt ---- @FlagInt Value will be ?GOPRINT '--------------------'PRINT 'After COMMIT example'DECLARE @FlagINT INTSET @FlagInt = 1PRINT @FlagInt ---- @FlagInt Value will be 1BEGIN TRANSACTIONSET @FlagInt = 2 ---- @FlagInt Value will be 2PRINT @FlagIntCOMMIT TRANSACTIONPRINT @FlagInt ---- @FlagInt Value will be ?GOResultSet:After ROLLBACK example122——————–

Page 68: 9 Jan 01, 2007-431 Dec 31, 2007

After COMMIT example122

It is very clear that local variables are not affected with transaction. In both of the above cases we got the same result. Jr. DBA and Application Tech Lead were pleased with this simple example and asked me to blog about it. Let me know if you like this kind of articles. I will post some more like this.

SQL SERVER – Order of Result Set of SELECT Statement on Clustered Indexed Table When ORDER BY is Not Used

September 24, 2007 by pinaldave

“What will be the order of the result set of SELECT statement on clustered indexed table when ORDER BY clause is not used?”

I was asked this question by one of the smartest tech team manager in my company. I really enjoyed answering the question.

The common misconception is:If ORDER BY clause is not explicitly specified and table has clustered index it will return the resultset in order of how clustered index is built.

Above theory is true in most of the cases. However SQL Server does not use that logic when returning the resultset. SQL Server always returns the resultset which it can return fastest. In most of the cases the resultset which can be returned fastest is the resultset which is returned using clustered index.

There are few incidence I have observed that, when parallelism is used to return the query results, many times due to different speed and work load on different CPU the resultset is not according to clustered index. SQL Server Parametrization and SQL Server cache can return the results which are not built by clustered index. This paragraph is written assuming there is ORDER BY clause specified in the SELECT clause.

I am in strong favor of clustered index which are primary key. There is not a single table in my database server farm which does not have clustered index (usually primary key, but not necessarily). This article is just stating the observation in certain conditions.

SQL Server uses clustered index to return the resultset efficiently and speedily. If SQL Server can return resultset faster in comparisons to clustered index SQL Server will use faster method. Either way, user wins with faster results.

SQL SERVER – Stored Procedure to Know Database Access Permission to Current User

September 23, 2007 by pinaldave

Jr. DBA in my company only have access to the database which they need to use. Often they try to access database and if they do not have permission they face error. Jr. DBAs always check which database they have access using following system stored procedure. It is very reliable and provides accurate information.

Sytanx:EXEC sp_MShasdbaccessGO

ResultSet: ( I have listed only one column)AdventureWorksAdventureWorksDWmastermodelmsdbMyDBReportServer

Page 69: 9 Jan 01, 2007-431 Dec 31, 2007

ReportServerTempDBtempdb

SQL SERVER – 2005 – Version Information and Additional Information – Extended Stored Procedure xp_msver

September 22, 2007 by pinaldave

I was glad when I discovered this Extended Stored Procedure myself. I always used different syntax to retrieve server information. Many of information I was looking up using system information of the windows operating system.

Syntax:EXEC xp_msverResultSet:Index Name Internal_Value Character_Value—— ——————————– ————– ————————————-1 ProductName NULL Microsoft SQL Server2 ProductVersion 589824 9.00.3042.003 Language 1033 English (United States)4 Platform NULL NT INTEL X865 Comments NULL NT INTEL X866 CompanyName NULL Microsoft Corporation7 FileDescription NULL SQL Server Windows NT8 FileVersion NULL 2005.090.3042.009 InternalName NULL SQLSERVR10 LegalCopyright NULL © Microsoft Corp. All rights reserved.11 LegalTrademarks NULL Microsoft® is a registered trademark of Microsoft Corporation. Windows(TM) is a trademark of Microsoft Corporation12 OriginalFilename NULL SQLSERVR.EXE13 PrivateBuild NULL NULL14 SpecialBuild 199360512 NULL15 WindowsVersion 170393861 5.1 (2600)16 ProcessorCount 1 117 ProcessorActiveMask 1 0000000118 ProcessorType 586 PROCESSOR_INTEL_PENTIUM19 PhysicalMemory 1023 1023 (1073111040)20 Product ID NULL NULL

SQL SERVER – 2005 – Multiple Language Support

September 21, 2007 by pinaldave

SQL Server supports multiple languages. Information about all the languages are stored in sys.syslanguages system view. You can run following script in Query Editor and see all the information about each language. Information about Months and Days varies for each language.

Syntax:SELECT Alias, *FROM sys.syslanguages

ResultSet: (* results not included)Alias————–EnglishGermanFrenchJapaneseDanishSpanishItalianDutchNorwegianPortugueseFinnish

Page 70: 9 Jan 01, 2007-431 Dec 31, 2007

SwedishCzechHungarianPolishRomanianCroatianSlovakSlovenianGreekBulgarianRussianTurkishBritish EnglishEstonianLatvianLithuanianBrazilianTraditional ChineseKoreanSimplified ChineseArabicThai

SQL SERVER – FIX : ERROR : 3260 An internal buffer has become full

September 20, 2007 by pinaldave

ERROR : 3260 An internal buffer has become full

The reason I have picked to write about this error is because we have encountered this error many times in one of our older server.

Fix/WorkAround/Solution:We were not able to absolutely reduce this error but following changes helped.

1) Rebooted server if error is happening frequently.2) Increased RAM to Server.3) Increased RAM allocation to SQL Server application.

SQL SERVER – Rename Database to New Name Using Stored Procedure by Changing to Single User Mode

September 19, 2007 by pinaldave

In my organization we rename the database on development server when are refreshing the development server with live data. We save the old database with new name and restore the database from live with same name. If developer/Jr. DBA have not saved the SQL Script from development server, he/she can go back to old Server and retrieve the script.

There are few interesting facts to note when the database is renamed.

When renamed the database, filegroup name or filename (.mdf,.ldf) are not changed. User with SA privilege can rename the database with following script when the context of the

database is master database.

USE master;GOEXEC sp_dboption AdventureWorks, 'Single User', TrueGOEXEC sp_renamedb 'AdventureWorks', 'AdventureWorks_New'GOEXEC sp_dboption AdventureWorks, 'Single User', FalseGO

Page 71: 9 Jan 01, 2007-431 Dec 31, 2007

SQLAuthority News – Scale-Out Querying with Analysis Services Using SAN Snapshots

September 18, 2007 by pinaldave

White paper describes the use of virtual copy Storage Area Network (SAN) snapshots in a load-balanced scalable querying environment for SQL Server 2005 Analysis Services.

This architecture provides the following improvements

Improves the utilization of disk resources Optimizes cube processing operations Supports dedicated snapshots for specific users at different points in time

In selecting a snapshot implementation for use with for Analysis Services, users may wish to consider the following snapshot attributes:

Provisioning of snapshots Writeability of snapshots Scalability of snapshots Performance of snapshots Efficiency of snapshots

I have created this article here only to promote the original White Paper, which is very easy to read and describes the SAN configuration with Database.

SQL SERVER – UDF – Validate Positive Integer Function – Validate Natural Integer Function

September 18, 2007 by pinaldave

Few days ago I wrote SQL SERVER – UDF – Validate Integer Function. It was very interesting to write this and developers at my company started to use it. One Jr. DBA modified this function to validate only positive integers. I will share this with everybody who are interested in similar functionality.

Code:CREATE FUNCTION [dbo].[udf_IsNatural](@Number VARCHAR(100))RETURNS BITBEGINDECLARE @Ret BITIF (PATINDEX('%[^0-9-]%', @Number) = 0AND CHARINDEX('-', @Number) <= 1AND @Number NOT IN ('.', '-', '+', '^')AND LEN(@Number)>0AND @Number NOT LIKE '%-%')SET @Ret = 1ELSESET @Ret = 0RETURN @RetENDGO

Example:SELECT '999' TestValue,dbo.udf_IsNumeric('999') NumericTest;SELECT '-999' TestValue,dbo.udf_IsNumeric('-999') NumericTest;SELECT 'abc' TestValue,dbo.udf_IsNumeric('abc') NumericTest;SELECT '9+9' TestValue,dbo.udf_IsNumeric('9+9') NumericTest;SELECT '$9.9' TestValue,dbo.udf_IsNumeric('$9.9') NumericTest;SELECT 'SQLAuthority' TestValue,dbo.udf_IsNumeric('SQLAuthority') NumericTest

Page 72: 9 Jan 01, 2007-431 Dec 31, 2007

ResultSet:TestValue NumericTest——— ———–999 1

TestValue NumericTest——— ———–-999 0

TestValue NumericTest——— ———–abc 0

TestValue NumericTest——— ———–9+9 0

TestValue NumericTest——— ———–$9.9 0

TestValue NumericTest———— ———–SQLAuthority 0

SQLAuthority News – NASDAQ Uses SQL Server 2005 – Reducing Costs through Better Data Management

September 17, 2007 by pinaldave

I just came across PDF published by Microsoft to promote SQL Server 2005. I find few things very interesting. I will list them here.

NASDAQ

NASDAQ, the world’s first electronic stock market replaced its aging mainframe computers with Microsoft® SQL Server™ 2005 on two 4-node clusters to support its Market Data Dissemination System (MDDS).

Every trade processed in the NASDAQ marketplace goes through the system with Microsoft® SQL Server™ 2005 handling some 5,000 transactions per second at market open.

The system also responds to about 10,000 queries a day and is able to handle real-time queries against data without slowing the database down.

SQL Server 2005 Features

Scalability Availability Manageability Built-in Business Intelligence

Data Management Capability: Business Benefits

Faster results Better decisions Trusted Platform Total cost of ownership

SQL SERVER – Difference Between UPDATE and UPDATE()

September 17, 2007 by pinaldave

Page 73: 9 Jan 01, 2007-431 Dec 31, 2007

What is the difference between UPDATE and UPDATE()?

UPDATE is syntax used to update the database tables or database views.USE AdventureWorks ;GOUPDATE Production.ProductSET ListPrice = ListPrice * 2;GO

UPDATE() is used in triggers to check update/insert to the database tables or database views.Returns a Boolean value that indicates whether an INSERT or UPDATE attempt was made on a specified column of a table or view. UPDATE() is used anywhere inside the body of a Transact-SQL INSERT or UPDATE trigger to test whether the trigger should execute certain actions.USE AdventureWorks ;GOCREATE TRIGGER reminderON Person.AddressAFTERUPDATEASIF (UPDATE (StateProvinceID)ORUPDATE (PostalCode) )BEGINRAISERROR (50009, 16, 10)END;GO

Please read additional details on BOL – UPDATE, BOL – UPDATE()

SQLAuthority News – Active Directory Integration Sample Script

September 16, 2007 by pinaldave

A sample script that enables you to extract a list of computer names from your custom SQL Server database and add them to an Active Directory security group. The security group can then be referenced in the Agent Assignment and Failover Wizard to automate agent assignments to Management Servers.

1. Queries customer SQL asset database.2. Populates custom security group with computer accounts of computers returned by the SQL query.

Download from MSDN

Abstract courtesy : Microsoft

SQL SERVER – 2005 – List All The Constraint of Database – Find Primary Key and Foreign Key Constraint in Database

September 16, 2007 by pinaldave

Following script are very useful to know all the constraint in the database. I use this many times to check the foreign key and primary key constraint in database. This is simple but useful script from my personal archive.USE AdventureWorks;GOSELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,SCHEMA_NAME(schema_id) AS SchemaName,OBJECT_NAME(parent_object_id) AS TableName,type_desc AS ConstraintTypeFROM sys.objectsWHERE type_desc LIKE '%CONSTRAINT'GO

Page 74: 9 Jan 01, 2007-431 Dec 31, 2007

SQLAuthority News – Book Review – Pro T-SQL 2005 Programmer’s Guide (Paperback)

September 15, 2007 by pinaldave

Pro T-SQL 2005 Programmer’s Guide (Paperback)by Michael Coles (Author)

Link to Amazon (This is not affiliate Link)

Short Summary:Pro T-SQL 2005 Programmer’s Guide book examines SQL Server 2005 T-SQL from a developer’s perspective. It covers a wide range of developer-specific topics in SQL Server 2005. This book covers many newly introduced topics in depth. This book is written as a practical and useful guide to help database developers who mainly deals with T-SQL. This book is really hit the spot with appropriate .NET code at few places where needed. This book assumes a basic knowledge of SQL but it is really easy for new beginners developers to understand and advanced developers to enjoy further reading.

Detailed Summary:One thing I really liked about this book is that it can be either read cover to cover, or it can be used as a reference guide for one particular topic. Index of this book is extremely well organized and aids to find the right topic very quickly. Books is structure is many chapters and each chapter justifies the chapters with good details and proper amount of examples.

Each chapter has excellent advice and knowledge and filled with sample code (available online). The book is targeted specifically at SQL Server 2005 and the innovative ways to code T-SQL, new functions and commands. If is very easy to get started with this book and it immerses in comprehensive reading in no time. This book addresses many details and comparisons with T-SQL in very organized way. The examples are in very accurate and useful as well sufficient to targeted topics. This book addresses many of the real world issues with examples, discussions and solutions.

This book start with providing a brief history of T-SQL and the ANSI SQL standards. SQLCMD and SQL Server Management Studio are new tools to explore SQL Server 2005 and are covered in depth in beginning of the book. Chapters which covers Common Table Expressions (CTEs), new datatypes, operators, keywords, functions, and control of flows are really interesting and with necessary explanation. Readers of my blog are very well aware of my interests in Error handling and debugging. Interesting enough for me there is one whole chapter dedicated to that. The regular T-SQL concepts which I write a lot

Page 75: 9 Jan 01, 2007-431 Dec 31, 2007

about Stored Procedure, Triggers and Dynamic SQL each have their own chapter. One thing many T-SQL book does not cover in depth is XML, XQuery and XPath which are properly discussed and their importance is explained properly. Last three chapter of the book which covers SQLCLR, .NET Client Programming and HTTP Endpoints requires the Microsoft .NET FrameWork 2.0, as it contains some code which are written in VB and C#.

One thing which I always liked in any database book is, use of sample database AdventureWorks. I strongly believe that all the example should be independent from previous examples and should use default database. If you have not installed default database AdventureWorks, you can get its latest location by searching in my blog SQLAuthority.com. All the script of examples are available to download online. No book is free from the errors and website for this book have errata list, which is surprisingly very small.

I will list few tips from book which interested me. This will give brief idea how good this book is.

“TABLESAMPLE always returns an approximate number of rows because of the way it samples data. The required percentage is the number of data pages SQL Server retreves in full to fulfill your TABLESAMPLE request. The number of rows returned by TABLESAMPLE will often be slightly less, or greater, than the specified amount.”

“Anytime you use dynamic SQL, make sure that you take precautions against SQL injection, that is, malicious SQL Code being inserted into your SQL statements. In this instance we’re using the QUOTENAME function to quote the column names being dynamically generated to help avoid SQL injection problems.”

Following one example really caught my eyes while reading the book. It seems Author accurately described the situation and put his suggestion regarding syntax.“The ANSI SQL:2003 standard includes a MERGE statement that performs the same function as the upsert type of SP. The prerelease versions of SQL Server 2005 included the MERGE statement. Though it was well-publicized during the prerelease period, the MERGE statement was unceremoniously dropped from the production version. We can only hope that Microsoft brings it back sometime in the near future.”Good news is Microsoft have included the Authors request in future version of SQL Server. SQL Server 2008 CTP 4 has included MERGE Keyword.

Rating: 4 and 1/2 stars

In Summary, A book for every developer who want to take full advantage of the power of T-SQL on SQL Server 2005.

Pinal DavePrincipal Database Administrator

SQLAuthority News – Random Article from SQLAuthority Blog

September 14, 2007 by pinaldave

It has been wonderful writing on this blog. Many times I visit my older articles and read them. One of my favorite feature on WordPress.com (where I host my blog) is Random Article Feature. I use it quite often to land on random page on my blog. It is really good to read articles written previously because there are so many new things to learn as well keep previously learned knowledge refreshed.

I have added link to random article in the side bar of this blog. User can click on it to visit random article as well click in the link at the end of this article to view Random Article of SQLAuthority.com

Page 76: 9 Jan 01, 2007-431 Dec 31, 2007

View SQLAuthority.com Random Article

SQLAuthority News – Book Review – SQL Server 2005 DBA Street Smarts: A Real World Guide to SQL Server 2005 Certification Skills

September 11, 2007 by pinaldave

SQL Server 2005 DBA Street Smarts: A Real World Guide to SQL Server 2005 Certification Skills (Paperback)by Joseph L. Jorden

Link to Amazon – This is not affiliation link.

Short Review:Microsoft’s new generation of certifications is design not only to emphasize your proficiency with a specific technology but also to prove you have the skills needed to perform a specific role. This book is developed based on the exam objective of the 70-431, although its purpose is to server more as a reference than just an exam preparation book.

Detail Review:This book is designed to give DBAs some insight into the world of typical database administrator by walking through some of the daily tasks user can expect on the job. However, serious reader can derive much value from simply reading thorough the tasks without performing the steps on live equipment.

This book is organized into four phases of database administration. Each phase is separated into individual tasks. The phases represent broad categories under which related responsibilities are grouped. Phases are listed here:

Phase 1 : Installing and Configuring Microsoft SQL Server 2005Phase 2 : Implementing High Availability and Disaster RecoveryPhase 3: Maintaining and Automating SQL ServerPhase 4: Monitoring and Troubleshooting SQL Server

Each task in this book is organized into sections aimed at giving user what to do when need it. Descriptions of sections are divided in four parts i.e. The Scenario, The Scope of Task, The procedure and The Criteria of Completion.

I am including one example of above procedure to get clear idea how the book is organized.

Page 77: 9 Jan 01, 2007-431 Dec 31, 2007

Task : Selecting and Setting a Recovery ModelThis task starts with the basic requirement of the recovery model. It clearly indicates the need of this specific task as before DBA can start backing up databases and transaction logs, user need to configure the database to use the right recovery model. This task continues further explaining all the three recovery model. It explains the scenario, which is just a problem statement. Scope of Task follows scenario with additional information and procedures. The solution is explained with necessary SQL Script (if needed) and diagram (if possible).

This book is not an expert level book. It is very simple and almost for the beginners. This book teaches reader how to implement the basic working solution for all the complex database concepts like replication, mirroring, database backup etc. This book is not long manual but sometimes it gives feeling that I am reading Book On Line. This is good in one way as it is provides the details and information with easy and familiar medium, however sometime that lacks the freshness. I really enjoy the approach author for this, it is very familiar “how to do anything with database in 10 mins” approach.

I highly recommend this book for all those who are looking for quick start and wants to get working solution in very little time. Those who are looking for in-depth analysis of the subject matter, this book’s focus in not in that direction.

Rating: 4 and 1/2 stars

In Summary, A smooth read and great in breadth learning experience for beginners.

SQL SERVER – Frequency of SQL Server Reboot and Restart

September 11, 2007 by pinaldave

This is very interesting question. I will keep the answer of this question very simple. First of all there is no scientific research or white paper I can backup my results with. Answer contains part simple observation and part experience.

There is no need to reboot SQL Server. Once it is on it is ON!

However, I have heard that frequent reboot improves performance.

In my company our network administration department has policy to reboot all the servers every 15 days. We reboot all the servers at every 15 days. Regarding performance improvement, our servers are always up and running as great as they can.

SQLAuthority News – Scrum: Agile Software Development for Project Management

September 12, 2007 by pinaldave

This is something I have learned while working for so many years as Project Manager. It is not as important to know how things are done but it is important to know how to get things done. Scrum isan Agile Software Development system which helps developers to get project done in reasonable time and with superior quality.

Scrum is organized around the following roles:

Product Owner – Determines what functionality is needed ScrumMaster – Leads the Scrum and is primarily responsible for making sure the Scrum process

is followed and removing impediments that keep the Team from working The Team – Those who do the actual work that translates what the Product Owner has requested

into usable functionality

The following is a synopsis of the Scrum process:

The Product Owner creates the Product Backlog (List of Desired Functionality in the System) A meeting is held with the Product Owner, the ScrumMaster and the Team

Page 78: 9 Jan 01, 2007-431 Dec 31, 2007

The Team commits to getting x number of items from the Product Backlog done in 30 days. This 30 day block is known as the Sprint

The Team makes a Sprint Backlog (List of items that must be done to turn the Product Backlog items into shippable items during the Sprint)

The ScrumMaster meets with the Team daily and asks each member three questions:o What have you completed for the Sprint in the last day?o What will you complete for the Sprint tomorrow?o Is anything impeding you from getting your work done?

The Daily Scrum causes the Team to reveal exactly where it is, or where it isn’t The ScrumMaster keeps distractions away from the Team The Team self-organizes and keeps the Sprint Backlog up-to-date An item on the Sprint Backlog is done when code is well-written, well-structured and thoroughly

tested At the end of the Sprint, a Sprint Review meeting is held Items not completed during a Sprint are allocated to a future Sprint

Other important notes to keep in mind when utilizing the Scrum process:

Scrum makes a project’s progress and problems constantly visible Every Sprint produces an increment of potentially shippable functionality Scrum must be put into place before it can be fully understood Scrum focuses on what can be done

o It instills the “art of the possible” and allows work to go forward before things are “perfect”

o You will never achieve perfection, no matter how much planning you doo Sprints are time-boxed to keep the team from searching too much for perfectiono Focus efforts on a small set of pressing problemso Define work that will allow concrete resultso Planning doesn’t have to be extensive for a Scrum project to get goingo The minimum is a vision and a Product Backlog

Scrum is anti-sequentialo Get going on what can be doneo Help each other outo Collaborateo Sequential tasks divide a team

In Scrum, an estimate is not a contracto Scrum expects exceptions to the plan and doesn’t fear themo Adaptation is a normal part of the process

SQL SERVER – Difference Between EXEC and EXECUTE vs EXEC() – Use EXEC/EXECUTE for SP always

September 13, 2007 by pinaldave

What is the difference between EXEC and EXECUTE?

They are the same. Both of them executes stored procedure when called asEXEC sp_helpGOEXECUTE sp_helpGO

I have seen enough times developer getting confused between EXEC and EXEC(). EXEC command executes stored procedure where as EXEC() function takes dynamic string as input and executes them.EXEC('EXEC sp_help')GO

Another common mistakes I have seen is not using EXEC before stored procedure. It is always good practice to use EXEC before stored procedure name even though SQL Server assumes any command as stored procedure when it does not recognize the first statement. Developer learns while working with Query Editor in SSMS that EXEC is not necessary before running any stored procedure. However, consider

Page 79: 9 Jan 01, 2007-431 Dec 31, 2007

following two test and you will see why EXEC or EXECUTE is necessary in many cases and good practice to use it.

TEST 1 : No ErrorsUSE AdventureWorks;GO----Try this first independently this will throw an errorsp_helptext 'dbo.uspPrintError'GO----Try this second independently this will work fineEXEC sp_helptext 'dbo.uspPrintError'GO

TEST 2 : EXEC prevents errorUSE AdventureWorks;GO----Try this first independently this will throw an errorSELECT *FROM Sales.Individualsp_helptext 'dbo.uspPrintError'GO----Try this second independently this will work fineSELECT *FROM Sales.IndividualEXEC sp_helptext 'dbo.uspPrintError'GO

Test 2 indicates that using EXEC or EXECUTE is good practice as it always executes the stored procedure, when not using EXEC can confuse SQL SERVER to misinterpret commands and may create errors.

SQL SERVER – 2005 – White Paper – Integrating Visio 2007 and Microsoft SQL Server 2005

September 10, 2007 by pinaldave

This article focuses on integration techniques specific to Microsoft Office Visio 2007 and Microsoft SQL Server 2005. Using Visio 2007, you can connect Visio shapes to data that was generated outside Visio. A large amount of data can be captured in a SQL Analysis Services database. Being able to analyze that data in a visual way enhances the value of the data. In the following example, sales data stored in an Analysis Services cube is used to generate a Visio PivotDiagram so that the data can be explored and graphically enhanced.

View Integrating Visio 2007 and Microsoft SQL Server 2005

SQLAuthority News – Job Opportunity in Ahmedabad, India to Work with Technology Leaders Worldwide

September 10, 2007 by pinaldave

If you have one or more years of experience in any web based programming language (.NET, ColdFusion, PHP) and interested in SQL Server as well willing to locate Ahmadabad, India. Please send me your resume, if selected you may get chance to work with one of the most progressing industry in world as well some smartest technology leaders worldwide. Salary depends on Experience.

If selected for interview I suggest you go over SQL Server Interview Questions and Answers Complete List Download, as there is great chance I may be participating in interview.

Please send your resume at pinaldave “at” yahoo.com and pinal “at” sqlauthority.com with subject line as Job Opportunity with SQLAuthority.

SQL SERVER – 2005 – Start Stop Restart SQL Server From Command Prompt

September 9, 2007 by pinaldave

Page 80: 9 Jan 01, 2007-431 Dec 31, 2007

Very frequently I use following command prompt script to start and stop default instance of SQL Server. Our network admin loves this commands as this is very easy.

Click Start >> Run >> type cmd to start command prompt.

Start default instance of SQL Servernet start mssqlserver

Stop default instance of SQL Servernet stop mssqlserver

Page 81: 9 Jan 01, 2007-431 Dec 31, 2007

Start and Stop default instance of SQL Server.You can create batch file to execute both the commands together.

SQL SERVER – UDF – User Defined Function – Get Number of Days in Month

September 8, 2007 by pinaldave

Following User Defined Function (UDF) returns the numbers of days in month. It is very simple yet very powerful and full proof UDF.CREATE FUNCTION [dbo].[udf_GetNumDaysInMonth] ( @myDateTime DATETIME )RETURNS INTASBEGINDECLARE @rtDate INTSET @rtDate = CASE WHEN MONTH(@myDateTime)IN (1, 3, 5, 7, 8, 10, 12) THEN 31WHEN MONTH(@myDateTime) IN (4, 6, 9, 11) THEN 30ELSE CASE WHEN (YEAR(@myDateTime) % 4 = 0ANDYEAR(@myDateTime) % 100 != 0)OR(YEAR(@myDateTime) % 400 = 0)THEN 29ELSE 28 ENDENDRETURN @rtDateENDGO

Run following script in Query Editor:SELECT dbo.udf_GetNumDaysInMonth(GETDATE()) NumDaysInMonthGO

ResultSet:NumDaysInMonth———————–31

SQL SERVER – Correlated and Noncorrelated – SubQuery Introduction, Explanation and Example

September 7, 2007 by pinaldave

Page 82: 9 Jan 01, 2007-431 Dec 31, 2007

A correlated subquery is an inner subquery which is referenced by the main outer query such that the inner query is considered as being executed repeatedly.

Example:----Example of Correlated SubqueriesUSE AdventureWorks;GOSELECT e.EmployeeIDFROM HumanResources.Employee eWHERE e.ContactID IN(SELECT c.ContactIDFROM Person.Contact cWHERE MONTH(c.ModifiedDate) = MONTH(e.ModifiedDate))GO

A noncorrelated subquery is subquery that is independent of the outer query and it can executed on its own without relying on main outer query.

Example:----Example of Noncorrelated SubqueriesUSE AdventureWorks;GOSELECT e.EmployeeIDFROM HumanResources.Employee eWHERE e.ContactID IN(SELECT c.ContactIDFROM Person.Contact cWHERE c.Title = 'Mr.')GO

Both of above subqueries can be written using Joins, Exists, In clauses. However, I have tried to demonstrate two different kind of subquery examples. Let me know if you have any questions or wants me to elaborate on this subject.

SQL SERVER – 2005 – Introduction and Explanation to sqlcmd

September 6, 2007 by pinaldave

I decided to write this article to respond to request of one of usergroup, which requested that they would like to learn sqlcmd 101.

SQL Server 2005 has introduced new utility sqlcmd to run ad hoc Transact-SQL statements and scripts from command prompt. T-SQL commands are entered in command prompt window and result is displayed in the same window, unless result set are sent to output files. sqlcmd can execute single T-SQL statement as well as batch file. sqlcmd utility can connect to earlier versions of SQL Server as well. The sqlcmd utility uses the OLE DB provider to execute T-SQL commands, whereas SQL ServerManagement studio uses .NET sqlclient to execute sqlcmd script, this can lead to different results in certain cases. (If you have example of this please let me know, I will post it here)

sqlcmd is enhenced version of the isql and osql and it provides way more functionality than other two options. In other words sqlcmd is better replacement of isql (which will be deprecated eventually) and osql (not included in SQL Server 2005 RTM). sqlcmd can work two modes – i) BATCH and ii) interactive modes.

Let us go over simple example of sqlcmd.

1) Step 1 : Go to Start >> Run >> Type “cmd” and press enter.

Page 83: 9 Jan 01, 2007-431 Dec 31, 2007

2) Step 2 : Type in command “sqlcmd” and press enter

3) Step 3 : Type following “USE AdventureWorks” command to switch database context to Adventureworks. Type “GO” after the batch to change the code. It will display the success message as “Changed database context to AdventureWorks”.

Page 84: 9 Jan 01, 2007-431 Dec 31, 2007

4) Step 4 : Now run any same query. Refer following image to see the query and its result.

5) Step 5 : Similar result we will get if the same query is ran in Query Editor in SSMS.

Page 85: 9 Jan 01, 2007-431 Dec 31, 2007

6) Type “exit” at any point if you do not want to continue working with sqlcmd.

The use of sqlcmd syntax is very easy however it this command can perform many powerful tasks. We will see that in future articles.

SQLAuthority News – SQL SERVER 2008 CTP 4 Released

September 6, 2007 by pinaldave

SQL Server 2008 CTP 4 is released as a pre-configured VHD. This allows you to trial SQL Server 2008 CTP 4 in a virtual environment.

Download SQL Server 2008 CTP 4

SQL SERVER – SQL Joke, SQL Humor, SQL Laugh – Valid SQL Error

September 5, 2007 by pinaldave

Yesterday I had posted my 300th post and I missed the announcement. One of my reader sent me following Image in email congratulating SQLAuthority blog for completing 300th post and also informing me that it has been long time I have posted something funny. I have written few articles about frequent SQL Server Errors on this blog. He suggested that this humorous images goes along with it.

Page 86: 9 Jan 01, 2007-431 Dec 31, 2007

If you know source of this image please let me know I would like to include that. Visit more SQL Server Humors.

Reference : Pinal Dave (http://blog.SQLAuthority.com) , Need original reference for image.

SQLAuthority News – Interesting Read – Using A SQL JOIN In A SQL UPDATE/Delete Statement – Ben Nadel

September 5, 2007 by pinaldave

As everybody know SQL is what I like most. Before I was into SQL Server, I was very much into ColdFusion. ColdFusion is still my most favorite programming language. I still program in ColdFusion, infect my personal website http://www.pinaldave.com is in ColdFusion. I regularly read ColdFusion blog and latest updates in ColdFusion. Recently at company where I work, we upgraded to ColdFusion 8 and .NET 2.0 (C# is our preferred language in .NET technology). Both of this languags work with SQL Server 2005 very well in my company.

My favorite blog for ColdFusion technology is blog of BEN NADEL . Ben writes excellent articles in ColdFusion and have absolutely control over his technical thought process – a true genius. Recently he wrote two articles about how SQL JOINS can be used in UPDATE and DELETE queries. When I read them I felt I should have wrote similar articles for this blog.

Please visit both the articles to get the proper understanding how JOIN can be used. The code is SQL with great amount of explanation.

Using A SQL JOIN In A SQL UPDATE StatementThis example is explained with UPDATE and INNER JOIN.

Using A SQL JOIN In A SQL DELETE StatementThis example is explained with DELETE and LEFT OUTER JOIN. Very good example.

Page 87: 9 Jan 01, 2007-431 Dec 31, 2007

If you on the site of Ben Nadel, checkout the Free ColdFusion Calender System.

Let me know what you think about these articles.

SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database

September 4, 2007 by pinaldave

My article SQL SERVER – 2005 Find Table without Clustered Index – Find Table with no Primary Key has received following question many times. I have deleted similar questions and kept only latest comment there.

In SQL Server 2005 How to Find Tables With Primary Key Constraint in Database?

Script to find all the primary key constraint in database:USE AdventureWorks;GOSELECT i.name AS IndexName,OBJECT_NAME(ic.OBJECT_ID) AS TableName,COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnNameFROM sys.indexes AS iINNER JOIN sys.index_columns AS icON i.OBJECT_ID = ic.OBJECT_IDAND i.index_id = ic.index_idWHERE i.is_primary_key = 1In SQL Server 2005 How to Find Tables With Foreign Key Constraint in Database?SQL SERVER – 2005 – Find Tables With Foreign Key Constraint in Database

SQL SERVER – 2005 – Find Tables With Foreign Key Constraint in Database

September 4, 2007 by pinaldave

While writing article based on my SQL SERVER – 2005 Find Table without Clustered Index – Find Table with no Primary Key I got idea about writing this article. I was thinking if you can find primary key for any table in database you can sure find foreign keys for any table in database as well.

In SQL Server 2005 How to Find Tables With Foreign Key Constraint in Database?

Script to find all the primary key constraint in database:USE AdventureWorks;GOSELECT f.name AS ForeignKey,OBJECT_NAME(f.parent_object_id) AS TableName,COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnNameFROM sys.foreign_keys AS fINNER JOIN sys.foreign_key_columns AS fcON f.OBJECT_ID = fc.constraint_object_id

In SQL Server 2005 How to Find Tables With Primary Key Constraint in Database?SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database

SQL SERVER – 2005 – Search Stored Procedure Code – Search Stored Procedure Text

September 3, 2007 by pinaldave

I receive following question many times by my team members.

Page 88: 9 Jan 01, 2007-431 Dec 31, 2007

How can I find if particular table is being used in the stored procedure?How to search in stored procedures?How can I do dependency check for objects in stored procedure without using sp_depends?

I have previously wrote article about this SQL SERVER – Find Stored Procedure Related to Table in Database – Search in All Stored procedure.

The same feature can be implemented using following script in SQL Server 2005.USE AdventureWorksGO--Searching for Empoloyee tableSELECT NameFROM sys.proceduresWHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Employee%'GO--Searching for Empoloyee table and RateChangeDate column togetherSELECT NameFROM sys.proceduresWHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Employee%'AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%RateChangeDate%'GOResultSet:Name———————————–uspGetEmployeeManagersuspGetManagerEmployeesuspUpdateEmployeeHireInfouspUpdateEmployeeLoginuspUpdateEmployeePersonalInfo

Name———————————–uspUpdateEmployeeHireInfo

SQL SERVER – Fix : Error : Msg 3117, Level 16, State 4 The log or differential backup cannot be restored because no files are ready to rollforward

September 2, 2007 by pinaldave

Following error occurs when tried to restored the differential backup.

Fix : Error : Msg 3117, Level 16, State 4 The log or differential backup cannot be restored because no files are ready to rollforward

Fix/WorkAround/Solution:This error happens when Full back up is not restored before attempting to restore differential backup or full backup is restored with WITH RECOVERY option. Make sure database is not in operational conditional when differential backup is attempted to be restored.

Example of restoring differential backup successfully after restoring full backup.RESTORE DATABASE AdventureWorksFROM DISK = 'C:\AdventureWorksFull.bak'WITH NORECOVERY;RESTORE DATABASE AdventureWorksFROM DISK = 'C:\AdventureWorksDiff.bak'WITH RECOVERY;

SQL SERVER – 2005 – Find Database Status Using sys.databases or DATABASEPROPERTYEX

August 31, 2007 by pinaldave

While writing article about database collation, I came across sys.databases and DATABASEPROPERTYEX. It was very interesting to me that this two can tell user so much about database properties.

Page 89: 9 Jan 01, 2007-431 Dec 31, 2007

Following are main database status: (Reference: BOL Database Status)

ONLINEDatabase is available for access.

OFFLINEDatabase is unavailable.

RESTORINGOne or more files of the primary filegroup are being restored, or one or more secondary files are being restored offline.

RECOVERINGDatabase is being recovered.

RECOVERY PENDINGSQL Server has encountered a resource-related error during recovery.

SUSPECTAt least the primary filegroup is suspect and may be damaged.

EMERGENCYUser has changed the database and set the status to EMERGENCY.

Let us see how we can find out database status using this sys.databases and DATABASEPROPERTYEX.

1) Using T-SQL (My Recommendation)

Example:SELECT DATABASEPROPERTYEX('AdventureWorks', 'Status')DatabaseStatus_DATABASEPROPERTYEXGOSELECT state_desc DatabaseStatus_sysDatabaseFROM sys.databasesWHERE name = 'AdventureWorks'GO

ResultSet:DatabaseStatus_DATABASEPROPERTYEX——————————————————ONLINE

DatabaseStatus_sysDatabase——————————————————ONLINE

2) Using SQL Server Management Studio

Page 90: 9 Jan 01, 2007-431 Dec 31, 2007
Page 91: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 – Find Database Collation Using T-SQL and SSMS

August 30, 2007 by pinaldave

This article is written based on feedback I have received on SQL SERVER – Cannot resolve collation conflict for equal to operation. Many reader asked me how to find collation of current database. There are two different ways to find out SQL Server database collation.

1) Using T-SQL (My Recommendation)

Run following Script in Query EditorSELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;ResultSet:SQLCollation————————————SQL_Latin1_General_CP1_CI_AS

Page 92: 9 Jan 01, 2007-431 Dec 31, 2007

2) Using SQL Server Management Studio

Refer the following two diagram to find out the SQL Collation.Write Click on Database

Page 93: 9 Jan 01, 2007-431 Dec 31, 2007

Click on Properties

SQL SERVER – Difference and Explanation among DECIMAL, FLOAT and NUMERIC

August 29, 2007 by pinaldave

The basic difference between Decimal and Numeric :They are the exactly same. Same thing different name.

The basic difference between Decimal/Numeric and Float :Float is Approximate-number data type, which means that not all values in the data type range can be represented exactly.Decimal/Numeric is Fixed-Precision data type, which means that all the values in the data type reane can be represented exactly with precision and scale.

Converting from Decimal or Numeric to float can cause some loss of precision. For the Decimal or Numeric data types, SQL Server considers each specific combination of precision and scale as a different data type. DECIMAL(2,2) and DECIMAL(2,4) are different data types. This means that 11.22 and 11.2222 are different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222 are same data types.

SQL SERVER – Actual Execution Plan vs. Estimated Execution Plan

August 28, 2007 by pinaldave

I was recently invited to participate in big discussion on one of the online forum, the topic was Actual Execution Plan vs. Estimated Execution Plan. I refused to participate in that particular discussion as I have very simple but strong opinion about this topic. I always use Actual Execution Plan as it is accurate.

Page 94: 9 Jan 01, 2007-431 Dec 31, 2007

Why not Estimated Execution Plan? It is not accurate. Sometime it is easier or useful to to know the plan without running query. I just run query and have correct and accurate Execution Plan.

Shortcut for Display Estimated Execution Plan : CTRL + L Shortcut for Include Actual Execution Plan : CTRL + M

You can use SSMS to include the execution plan as well.

SQL SERVER – 2005 – Use Always Outer Join Clause instead of (*= and =*)

August 27, 2007 by pinaldave

Yesterday I wrote about how SQL Server 2005 does not support named pipes. Today, my friend called me asking some of his query does not work. I asked him to send me the queries. I asked him to send me query. I noticed in his queries something, I have never practiced before and I never had any issue therefore.

Instead of using LEFT OUTER JOIN clause he was using *= and similarly instead of using RIGHT OUTER JOIN clause he was using =*. Once I replaced did necessary modification, queries run just fine.

I wish I can give you example of *= or =*, however, I had decided to not to add any more SQL Server 2000 code to this blog few months ago.

SQL SERVER – 2005 – No Backup Support For Named Pipes

August 26, 2007 by pinaldave

While helping one of my DBA friend (who works in big company in LA) to upgrade SQL Server 2000 to SQL Server 2005 I just found one thing, which I have not paid attention before.

Page 95: 9 Jan 01, 2007-431 Dec 31, 2007

SQL Server 2000 supported named pipe backup device. SQL Server 2005 does not support named pipe backup device, however SQL Server 2005 supports disk and tape devices.

I receive following question many times, I have answered this question earlier on this blog. I will still answer it again.

What is my preferred method of backup? We use SAN with RAID 10 configuration. Some industry experts suggested we are overprotecting our database backup. Well, Better safe than sorrow.

SQL SERVER – FIX : Error : msg 2540 – The system cannot self repair this error

August 25, 2007 by pinaldave

SQL SERVER – FIX : Error : msg 2540 – The system cannot self repair this error

This is most annoying error. I have only faced this error twice so far. I solved this error restoring the database back up. Read here for additional help on SQL Backup And Restore. This error is occurs when database is in state when it can not be heal itself, i.e. corrupted metadata or corrupted important system database files.

Fix/WorkAround/Solution:

My prefered order to fix the problem.

1) Restored database from backup.

2) Run DBCC with repair option, which will not bring much favorable answer.

3) Check if there is any hard ware problem with hard disk or Raid control.

SQL SERVER – 2005 – T-SQL Script to Attach and Detach Database

August 24, 2007 by pinaldave

Following script can be used to detach or attach database. If database is to be from one database to another database following script can be used detach from old server and attach to new server.

Process to move database :----Step 1 : Detach Database using following scriptUSE [master]GOEXEC master.dbo.sp_detach_db @dbname = N'AdventureWorks',@keepfulltextindexfile = N'true'GO----Step 2 : Move Data files and Log files to new location

–—Step 3 : Attach Database using following scriptUSE [master]GOCREATE DATABASE [AdventureWorks] ON( FILENAME = N’C:\Data\AdventureWorks_Data.mdf’ ),( FILENAME = N’C:\Data\AdventureWorks_Log.ldf’ )FOR ATTACHGOIF EXISTS ( SELECT nameFROM master.sys.databases sdWHERE name = N’AdventureWorks’AND SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() )EXEC [AdventureWorks].dbo.sp_changedbowner @loginame=N’sa’,

Page 96: 9 Jan 01, 2007-431 Dec 31, 2007

@map=falseGO

SQL SERVER – 2005 – Use of Non-deterministic Function in UDF – Find Day Difference Between Any Date and Today

August 23, 2007 by pinaldave

While writing few articles about SQL Server DataTime I accidentally wrote User Defined Function (UDF), which I would have not wrote usually. Once I wrote this function, I did not find it very interesting and decided to discard it. However, I suddenly noticed use of Non-Deterministic function in the UDF.

I always thought that use of Non-Deterministic function is prohibited in UDF. I even wrote about it earlier SQL SERVER – User Defined Functions (UDF) Limitations. It seems like SQL Server 2005 either have removed this restriction or it is bug. I think I will not say this is bug but I will categorized it as feature.

GETDATE() is Non-Deterministic function and it can be used in User Defined Function in SQL Server 2005.

T-SQL Script to create UDF:CREATE FUNCTION dbo.udf_DateDifference (@dtBeginDate datetime)RETURNS VARCHAR(100)ASBEGINDECLARE @rtMessage VARCHAR(100)SET @rtMessage = 'Different between ' + CAST(@dtBeginDate AS VARCHAR(11)) + ' and ' +CAST(GETDATE() AS VARCHAR(11)) + 'is' +CAST(DATEDIFF(DAY,@dtBeginDate,GETDATE()) AS VARCHAR(11))RETURN @rtMessageENDGO

Execute above function running following script:SELECT dbo.udf_DateDifference('8/1/2007') AS DayDifferenceResultSet:DayDifference—————————————————————————————————-Different between Aug 1 2007 and Aug 23 2007 is 23

SQL SERVER – T-SQL Script to Insert Carriage Return and New Line Feed in Code

August 22, 2007 by pinaldave

Very simple and very effective. We use all the time for many reasons – formatting, while creating dynamically generated SQL to separate GO command from other T-SQL, saving some user input text to database etc.DECLARE @strPrint VARCHAR(100);SET @strPrint = 'Example of carriage return';SET @strPrint = @strPrint + CHAR(13);SET @strPrint = @strPrint + 'SQLAuthority.com';PRINT @strPrint;GOPRINT '---------------------------------'DECLARE @strPrint VARCHAR(100);SET @strPrint = 'Example of new line feed';SET @strPrint = @strPrint + CHAR(10);SET @strPrint = @strPrint + 'SQLAuthority.com';PRINT @strPrint;GO

ResultSet:Example of carriage returnSQLAuthority.com———————————

Page 97: 9 Jan 01, 2007-431 Dec 31, 2007

Example of new line feedSQLAuthority.com

SQL SERVER – 2005 – Create Script to Copy Database Schema and All The Objects – Stored Procedure, Functions, Triggers, Tables, Views, Constraints and All Other Database Objects

August 21, 2007 by pinaldave

Following quick tutorial demonstrates how to create T-SQL script to copy complete database schema and all of its objects such as Stored Procedure, Functions, Triggers, Tables, Views, Constraints etc. You can review your schema, backup for reference or use it to compare with previous backup.

Step 1 : Start

Step 2 : Welcome Screen

Page 98: 9 Jan 01, 2007-431 Dec 31, 2007

Step 3 : Select One or Multiple DatabaseIf Script all objects in the selected database checkbox is not selected it will give options to selected individual objects on respective screen. (e.g. Stored Procedure, Triggers and all other object will have their own screen where they can be selected)

Page 99: 9 Jan 01, 2007-431 Dec 31, 2007

Step 4 : Select database options

Page 100: 9 Jan 01, 2007-431 Dec 31, 2007

Step 5 : Select output option

Page 101: 9 Jan 01, 2007-431 Dec 31, 2007

Step 6 : Review Summary

Page 102: 9 Jan 01, 2007-431 Dec 31, 2007

Step 7 : Observe script generation process

Page 103: 9 Jan 01, 2007-431 Dec 31, 2007

Step 8 : Database object script generation completed in new query window

Page 104: 9 Jan 01, 2007-431 Dec 31, 2007

SQLAuthority News – Principles of Simplicity

August 20, 2007 by pinaldave

Yesterday I came across Principles of Simplicity by Mads Kristensen. I think this is good write up and I enjoyed reading it. This are very generic and applies to all programming language and databases applications.

Principles of Simplicity by Mads Kristensen

1. Simplicity or not at allSome developers tend to over-complicate a task and ends up writing too many classes to solve a simple problem.

2. Don’t build submarinesIt’s a common fact that IT projects take longer than scheduled even if you schedule for delays.

3. Test when appropriateTesting is one very important factor of the development cycle and there are many different tests to perform.

4. Be precise when naming methodsA method must have a name that tells exactly what it does.

Page 105: 9 Jan 01, 2007-431 Dec 31, 2007

5. Comment your code the simple wayCode commenting can be done in a myriad of ways, but there really is only one that keeps your code simple at the same time.

6. Steal borrow and simplifyWe all use code pieces found on the Internet all the time.

7. It’s not a question of fewer code linesApparently it is a common misunderstanding that simplicity is a question of writing fewer lines of code.

8. Don’t be a rock starKnow your limitations and don’t be afraid to ask for help to solve a problem.

9. Learn much about muchTo be able to find the simple solution to any problem, you need diversity.

10. Don’t trust your simplicity instinctThis might be the single most important rule of simplicity.

ConclusionSimplicity is an implementation philosophy and it’s a very important one.

SQL SERVER – Find Monday of the Current Week

August 20, 2007 by pinaldave

Very Simple Script which find Monday of the Current Week

SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) MondayOfCurrentWeek

SQLAuthority News – Book Review – Sams Teach Yourself Microsoft SQL Server T-SQL in 10 Minutes

August 19, 2007 by pinaldave

Sams Teach Yourself Microsoft SQL Server T-SQL in 10 Minutes (Sams Teach Yourself)by Ben Forta

Page 106: 9 Jan 01, 2007-431 Dec 31, 2007

Link to Amazon – This is not affiliation link.

Short Review: If T-SQL (Transact-Structured Query Language) is foreign tongue to you, after reading this book, you will speak T-SQL. This book is SQL Server version of best-selling book Sams Teach Yourself SQL in 10 Minutes. This book teaches what a SQL developer must know methodically, systematically, and exactly. Anybody who are new to SQL Server and wants to learn most of T-SQL which can be implemented in short time in their application – BUY this book immediately.

Detail Review:This is the one book I was awaiting eagerly. I claim that I am very experience Database Administrator and Database Developer, however, I have learned something new from this book of acclaimed author Ben Forta.

This book is focused on T-SQL only. It begins with simple data retrieval and continues to develop complex topics. It addresses various topics that are enough to get some work done with SQL Server as well explains concept in depth. SQL Server 2005 is a very complex, feature rich product. This book does a wonderful job of explaining the various features with out going to too many details that majority of the users will not need anyway. This book covers all of the important aspects of SQL Server 2005 without clouding the information with tons of examples that are not for every user.

Author has divided the book into short comprehensible chapters along with to the point examples and explanations of the concepts. If you see “Table of Contents” of this book, you will find that this book covers many areas. I will talk about few of my personal favorite chapters of this book here to demonstrate, what this book does is best at.

Chapter 5: Sorting Retrieved DataIf you want to sort in descending order on multiple columns, be sure each column has its own DESC keyword.

When you are sorting textual data, is A the same as a? And does a come before B or after Z? In dictionary sort order, A is treated the same as a. If you need an alternate sort order, you can not accomplish it with a simple ORDER BY clause.

It is not required, and it is perfectly legal to sort data by a column that is not retrieved.

Page 107: 9 Jan 01, 2007-431 Dec 31, 2007

Chapter 10: Using Data Manipulation FunctionsIt is far safer to always use a full four digit year so that SQL Server does not have to make any assumptions for you.

When comparing dates, always use DATEDIFF(), and do not make assumptions about how dates are stored.

Chapter 15: Creating Advanced JoinsIt is worth noting that table aliases are only used during query execution. Unlike column aliases, table aliases are never returned to the client.

Self joins are often used to replace statements using subqueries that retrieve data from the same table as the outer statement. Sometimes these joins execute far more quickly than do subqueries.

Chapter 22: Programming with T-SQLThis is my most favorite chapter. Experienced programmers will find this chapter most interesting.

To discover the secret of SQL, this is the book you need to read, extremely well written, easy to follow and most importantly to the point. This has got to be the smallest SQL book in existence with highest amount of quality content. A really MUST have book.

Rating: 5 stars

In Summary, A MUST read.

Pinal DavePrincipal Database Administrator

SQL SERVER – Find Last Day of Any Month – Current Previous Next

August 18, 2007 by pinaldave

Few questions are always popular. They keep on coming up through email, comments or from co-workers. Finding Last Day of Any Month is similar question. I have received it many times and I enjoy answering it as well.

I have answered this question twice before here:

SQL SERVER – Script/Function to Find Last Day of MonthSQL SERVER – Query to Find First and Last Day of Current Month

Today, we will see the same solution again. Please use the method you find appropriate to your requirement.

Following script demonstrates the script to find last day of previous, current and next month.----Last Day of Previous MonthSELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))LastDay_PreviousMonth----Last Day of Current MonthSELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))LastDay_CurrentMonth----Last Day of Next MonthSELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))LastDay_NextMonthResultSet:LastDay_PreviousMonth———————–2007-07-31 23:59:59.000

Page 108: 9 Jan 01, 2007-431 Dec 31, 2007

LastDay_CurrentMonth———————–2007-08-31 23:59:59.000

LastDay_NextMonth———————–2007-09-30 23:59:59.000

If you want to find last day of month of any day specified use following script.--Last Day of Any Month and YearDECLARE @dtDate DATETIMESET @dtDate = '8/18/2007'SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))LastDay_AnyMonthResultSet:LastDay_AnyMonth———————–2007-08-31 23:59:59.000

SQL SERVER – 2005 – Explanation and Script for Online Index Operations – Create, Rebuild, Drop

August 17, 2007 by pinaldave

SQL Server 2005 Enterprise Edition supports online index operations. Index operations are creating, rebuilding and dropping indexes.

The question which I receive quite often – what is online operation? Is online operation is related to web, internet or local network?Online operation means when online operations are happening the database are in normal operational condition, the processes which are participating in online operations does not require exclusive access to database. In case of Online Indexing Operations, when Index operations (create, rebuild, dropping) are occuring they do not require exclusive access to database, they do not lock any database tables. This is major important upgrade in SQL Server from previous versions.

Previous versions of SQL Server required exclusive access to database, and database table were not accessible by other normal processes. This is the reason of time-outs and lock-outs when index operations are performed on SQL Server. I have seen many times major performance issues with larger databases, as due to business requirement and rules it has to be online all the time and index operations were not performed on them due to this concurrent accesses (normal processes vs prioritized index operations) conflict issues. This requirement of highly-availability application is very well addressed in SQL Server 2005 by adding new feature of Online Index Operations.

Syntax of Online Index is very simple. When the index on database is created, ONLINE = ON clause is added to enable online operations on index. ONLINE = ON must be specified to have this feature enabled. The default value of ONLINE option is OFF. The example is taken from BOL.

USE AdventureWorks;GOALTER INDEX ALL ON Production.ProductREBUILD WITH (ONLINE = ON);

Online index operations occurs in three steps.

1) Preparation – Snapshot of original index structure, known as source index, is taken and copied at other place. (concurrent activity suspended for the moment)

2) Build – New operations are executed on this copy, which generates new required index known as target index.

3) Final – Original source index is replaced by new target index. (concurrent activity suspended for the moment)

Page 109: 9 Jan 01, 2007-431 Dec 31, 2007

ALTER INDEX REORGANIZE statement is always performed online, so it is highly recommended to use this new feature over DBCC INDEXDEFRAG of previous version. (Read Complete Article : SQL SERVER – Comparison Index Fragmentation, Index De-Fragmentation, Index Rebuild – SQL SERVER 2000 and SQL SERVER 2005) DBCC INDEXDEFRAG may be deprecated in future versions of SQL Server so not recommended to use it. Creating partition index online is possible but altering partition index is not possible online.

Additional Notes:If any of the column in Included Index (Read Complete Article : SQL SERVER – Understanding new Index Type of SQL Server 2005 Included Column Index along with Clustered Index and Non-clustered Index) are VARCHAR(MAX), NVARCHAR(MAX), or VARBINARY(MAX), they must be created with ONLINE = OFF options.XML datatypes index can not be build online.Initial clustered index on view and disabled clustered index can not be build online.

SQLAuthority News – Subscribed to SQLAuthority Emails

August 16, 2007 by pinaldave

I have got many request about alert system when new post is published on this blog. I use feedburner email service, which sends email whenever new post is published on my blog. Many times, I update my post based on feedback from comments or news. If you want updated information, visit the blog.

Subscribe to SQLAuthority.com Email

SQL SERVER – 2008 – Book On-Line Link

August 16, 2007 by pinaldave

I am researching SQL Server 2008. Those who are asking me questions about SQL Server 2008, please refer following link. I will post my tutorials and articles very soon.

Here is SQL Server 2008 Book Online link.

SQL SERVER – 2005 – Difference and Similarity Between NEWSEQUENTIALID() and NEWID()

August 16, 2007 by pinaldave

NEWSEQUENTIALID() and NEWID() both generates the GUID of datatype of uniqueidentifier. NEWID() generates the GUID in random order whereas NEWSEQUENTIALID() generates the GUID in sequential order.

Let us see example first demonstrating both of the function.USE AdventureWorks;GO----Create Test Table for with default columns valuesCREATE TABLE TestTable(NewIDCol uniqueidentifier DEFAULT NEWID(),NewSeqCol uniqueidentifier DEFAULT NewSequentialID())----Inserting five default values in tableINSERT INTO TestTable DEFAULTVALUESINSERT INTO TestTable DEFAULTVALUESINSERT INTO TestTable DEFAULTVALUES

Page 110: 9 Jan 01, 2007-431 Dec 31, 2007

INSERT INTO TestTable DEFAULTVALUESINSERT INTO TestTable DEFAULTVALUES----Test Table to see NewID() is random----Test Table to see NewSequentialID() is Incremental SequenceSELECT *FROM TestTable----Clean up database with droping columnDROP TABLE TestTableGO

ResultSet:NewIDCol NewSeqCol———————————— ————————————DC896759-8B6B-4A62-8EC8-970BE2F0F04C 3D540550-2138-DC11-BF85-00123FD0986A71129CD4-3A25-470A-AE8E-9475379EC6A7 3E540550-2138-DC11-BF85-00123FD0986AB915CCDB-F480-4D89-ADD7-40D5DDE4FD52 3F540550-2138-DC11-BF85-00123FD0986A5920DA2E-6CC2-4FE3-9C13-F5155B1923A0 40540550-2138-DC11-BF85-00123FD0986A6C60BFD9-ACE1-4F74-BB74-99343A3A707D 41540550-2138-DC11-BF85-00123FD0986AIt is clear from example of that NEWSEQUENTIALID() generates GUID in hexadecimal incremental interval. The hexadecimal number can be any placed in GUID. In the example above first two digits are incrementing sequential.

Function NEWSEQUENTIALID() can not be used in SQL queries and it can be only used in DEFAULT clause of table. NEWSEQUENTIALID() are predictable, in case of privacy or security use NEWID() instead of NEWSEQUENTIALID(). If tried to use in QUERY it will thrown an error. NEWID() will work perfectly fine when used in queries.

Example:----This will thrown an errorSELECT NEWSEQUENTIALID()GO

ResultSet:Msg 302, Level 16, State 0, Line 1The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type ‘uniqueidentifier’ in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression.----This will return GUIDSELECT NEWID()GO

ResultSet:————————————26CE6817-B138-413A-92AD-A2F2BBF7E0B8

Additional Information from Book On-Line

The GUIDs generated by NEWSEQUENTIALID() are unique only within a particular computer if the computer does not have a network card.

You can use NEWSEQUENTIALID() to generate GUIDs to reduce page contention at the leaf level of indexes.

The value returned by NEWID is different for each computer.

SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE

August 15, 2007 by pinaldave

Following three questions are many time asked on this blog.

Page 111: 9 Jan 01, 2007-431 Dec 31, 2007

How to insert data from one table to another table efficiently?How to insert data from one table using where condition to anther table?How can I stop using cursor to move data from one table to another table?

There are two different ways to implement inserting data from one table to another table. I strongly suggest to use either of the method over cursor. Performance of following two methods is far superior over cursor. I prefer to use Method 1 always as I works in all the case.

Method 1 : INSERT INTO SELECTThis method is used when table is already created in the database earlier and data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are are not required to list them. I always list them for readability and scalability purpose.USE AdventureWorksGO----Create TestTableCREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))----INSERT INTO TestTable using SELECTINSERT INTO TestTable (FirstName, LastName)SELECT FirstName, LastNameFROM Person.ContactWHERE EmailPromotion = 2----Verify that Data in TestTableSELECT FirstName, LastNameFROM TestTable----Clean Up DatabaseDROP TABLE TestTableGO

Method 2 : SELECT INTO This method is used when table is not created earlier and needs to be created when data from one table is to be inserted into newly created table from another table. New table is created with same data types as selected columns.USE AdventureWorksGO----Create new table and insert into table using SELECT INSERTSELECT FirstName, LastNameINTO TestTableFROM Person.ContactWHERE EmailPromotion = 2----Verify that Data in TestTableSELECT FirstName, LastNameFROM TestTable----Clean Up DatabaseDROP TABLE TestTableGO

Both of the above method works with database temporary tables (global, local). If you want to insert multiple rows using only one insert statement refer article SQL SERVER – Insert Multiple Records Using One Insert Statement – Use of UNION ALL.

SQLAuthority News – Book Review – Learning SQL on SQL Server 2005 (Learning)

August 14, 2007 by pinaldave

SQLAuthority.com Book Review :Learning SQL on SQL Server 2005 (Learning) [ILLUSTRATED] (Paperback) by Sikha Bagui, Richard Earp

Page 112: 9 Jan 01, 2007-431 Dec 31, 2007

Link to book on Amazon – (This is not affiliate link)

Short Review:This books covers simple and complex concept in very easy language with lots of examples. Every beginner can learn a great amount of tips from experienced authors. Whether you are a self-learner, new to databases or in need of SQL refresher, this is good read.

Detail Review: This book is written by two conceptual strong SQL Server Gurus. SQL Server is growing extremely popular in the area of high-performance data applications. It is very important to learn about new features of SQL Server.

This book truly represents the concept and the motive authors holds while writing the book. The book is written as systematic guide to learning SQL using SQL Server 2005 – a relational and multi-user database.

This book starts with simple SQL concepts of management studio, simple select clauses, creating database and tables from scratch. It starts getting more involving and building difficult concepts on previously addressed easy concepts. Chapters about joins, sub queries, constraints are written with conceptual depth as well as lucid and simple language.

Authors suggest that this book is expected to be used by schools and SQL training organizations. I will add to that this book is for everyone who just wants to enjoy reading about SQL. This book should be read with hands on SQL Server practice. Reader will get most out of this book while doing exercise at the end of the book.

Review questions and exercise at the end of each chapter kept me occupied for long time. Few of them are very simple and few of them I have learned from this book. If you are experienced SQL programmer, I still suggest that you will enjoy reading the review questions. I will list few of those questions here.

When would you use the ROWCOUNT function versus using the WHERE clause?If you are going to have too many nulls in a column, what would be data type to use?What is the maximum number of the rows that a self join can produce?Which function can the WITH TIES option be used with?Is SELECT INTO allowed in a view? Why or why not?

Not always all the time, everybody wants to learn about difficult subject and in depth analysis. There are few times, when even experienced DBA and developers want to read back to basic concepts. I enjoy reading this book, if you are reader of my blog (www.sqlauthority.com) you will enjoy this book as this book is in agreement of my views of looking at SQL with simple logic but strong concepts.

There are few errors in the book but they are very minor and I was able to catch them easily. Authors seem to have good understanding about ORACLE in addition to SQL Server. That introduced some errors but on good side they are able to unleash few ideas which are not easy for SQL Server DBA to think of.

Page 113: 9 Jan 01, 2007-431 Dec 31, 2007

The chapter I enjoyed most is Joins Versus Subquery. Authors very easily explained their needs and differences. This statement shows the strength of chapter; If information from a table is needed in a result set, then that table can not be buried in a subquery- it must be in the outer query; simple but effective.

I highly recommend this book, if you are interested in learning about SQL in easy way. This book is PERFECT book for beginners and great reference for experience developers.

Rating : 4 and 1/2 stars

In Summary, This is must have book for every SQL student.

Pinal DavePrincipal Database Administrator

SQL SERVER – Fix : ERROR : Msg 1033, Level 15, State 1 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

August 12, 2007 by pinaldave

Following error is encountered when view is attempted to created with ORDER BY clause in it. ORDER BY clause is not allowed in views in SQL Server 2005. This solution also displays the workaround to use ORDER BY in VIEW. I really do not prefer to use views. My views on SQL Views read it SQL SERVER – Restrictions of Views – T SQL View Limitations.

Msg 1033, Level 15, State 1The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

This is error interested me as workaround of this involves some programming changes how the view is called in T-SQL query.

Fix/Solution/WorkAround:Do not use ORDER BY clause in View when not using TOP or FOR XML in SELECT clause. If you have to use ORDER BY use it in SELECT clause where view is used.

Let us understand using simple example on AdventureWorks database.

Following script will generate error in Query Editor.CREATE VIEW vTestContactViewASSELECT FirstName, LastNameFROM Person.ContactORDER BY FirstName DESCGO

Msg 1033, LEVEL 15, State 1, PROCEDURE vTestContactID, Line 5The ORDER BY clause IS invalid IN views, inline functions, derived tables,subqueries, AND common TABLE expressions, unless TOP OR FOR XML IS also specified.Now there is are two ways to fix the error.

Method 1: The Smart One and works all the time.If you do not want to change your all query which is using this view do following changes in view. It will return the same result without much (or none in most cases) performance loss. This is really helpful when ORDER BY Clause uses column which is not in SELECT clause(second example).----First exampleCREATE VIEW vTestContactViewASSELECT TOP 100 PERCENT FirstName, LastNameFROM Person.ContactORDER BY FirstName DESCGO

Page 114: 9 Jan 01, 2007-431 Dec 31, 2007

----Second exampleCREATE VIEW vTestContactIDViewASSELECT TOP 100 PERCENT FirstName, LastNameFROM Person.ContactORDER BY ContactID DESCGO

Method 2: The Technically Correct but only works when you have to ORDER BY on clause which is used in SELECT of view.First create view changing without using ORDER BY clause.CREATE VIEW vTestContactIDASSELECT FirstName, LastNameFROM Person.ContactGOCall the VIEW usingORDER BY clause.SELECT *FROM vTestContactIDORDER BY FirstName DESCI really enjoyed writing the solution for this problem.

SQLAuthority News – Author Visit – Database Architecture and Implementation Discussion – New York, New Jersey Details

August 13, 2007 by pinaldave

Last weekend I visited New York City (NY) and Edison (NJ) to attend database architecture meeting with a big environmental technology firm. It was very interesting to meet CEO and few of the lead database administrators. Lots of database related things were discussed.

I will list few of the points discussed in the meeting here, due to privacy policy I will be not able to write many of the interesting details I have learned there. Please let me know if you are interested in any of the particular topic. I can elaborate more on the topic which interests everybody.

1) Database Backupa. Schedule Backup Routinesb. Backup medium and redundancyc. SQL Server 2005 T-SQL improvement with regards to backup

2) Index Optimizationa. Implementing Primary Key on non-standard columns for improving performance in certain casesb. Index statistic optimization

3) Maintenance Tasksa. Index Re-buildingb. Database Consistency Check alerts

4) Replicationa. Snapshot replication optimization (use of new copy database feature)b. Log-shipping failover set up

5) Architecture Designsa. Setup Replications over database mirroringb. Database Normalization advantages and performancec. TempDB optimizationd. Datafile (.mdf) and Logfile (.ldf) filegroup placemente. Foreign key relationsf. Re-factoring database schemas based on statistics collected from profilerg. Analysis of hardware (disk, CPU, connections etc)f. Security of Database

Page 115: 9 Jan 01, 2007-431 Dec 31, 2007

6) System Tablesa. Use of system tables and views to retrieve system related information

It was really interesting to meet all prominent personality of biggest technology firm in one room. I was provided tour of their laboratory and was provided admin privileges to their complete database farm (yes it is really farm, not few computers) for the days, I was in their facility. CEO invited me to their home and I had most delicious home made food in US.

I just received email from CEO that they see performance improvement after implementing few suggestions and their backup is safe on redundant disks. They also restored them with point in the time restoration of logs.

I wonder how many companies have proper backup system (tested with restoring data frequently).

SQL SERVER – What is SQL? How to pronounce SQL?

August 14, 2007 by pinaldave

SQL is abbreviation of Structured Query Language.

SQL is pronounced as S.Q.L. (ess-que-ell or ess-cue-ell) not sequel.

QLAuthority News – Book Review – Learning SQL on SQL Server 2005 (Learning)

August 14, 2007 by pinaldave

SQLAuthority.com Book Review :Learning SQL on SQL Server 2005 (Learning) [ILLUSTRATED] (Paperback) by Sikha Bagui, Richard Earp

Link to book on Amazon – (This is not affiliate link)

Short Review:This books covers simple and complex concept in very easy language with lots of examples. Every beginner can learn a great amount of tips from experienced authors. Whether you are a self-learner, new to databases or in need of SQL refresher, this is good read.

Detail Review: This book is written by two conceptual strong SQL Server Gurus. SQL Server is growing extremely popular

Page 116: 9 Jan 01, 2007-431 Dec 31, 2007

in the area of high-performance data applications. It is very important to learn about new features of SQL Server.

This book truly represents the concept and the motive authors holds while writing the book. The book is written as systematic guide to learning SQL using SQL Server 2005 – a relational and multi-user database.

This book starts with simple SQL concepts of management studio, simple select clauses, creating database and tables from scratch. It starts getting more involving and building difficult concepts on previously addressed easy concepts. Chapters about joins, sub queries, constraints are written with conceptual depth as well as lucid and simple language.

Authors suggest that this book is expected to be used by schools and SQL training organizations. I will add to that this book is for everyone who just wants to enjoy reading about SQL. This book should be read with hands on SQL Server practice. Reader will get most out of this book while doing exercise at the end of the book.

Review questions and exercise at the end of each chapter kept me occupied for long time. Few of them are very simple and few of them I have learned from this book. If you are experienced SQL programmer, I still suggest that you will enjoy reading the review questions. I will list few of those questions here.

When would you use the ROWCOUNT function versus using the WHERE clause?If you are going to have too many nulls in a column, what would be data type to use?What is the maximum number of the rows that a self join can produce?Which function can the WITH TIES option be used with?Is SELECT INTO allowed in a view? Why or why not?

Not always all the time, everybody wants to learn about difficult subject and in depth analysis. There are few times, when even experienced DBA and developers want to read back to basic concepts. I enjoy reading this book, if you are reader of my blog (www.sqlauthority.com) you will enjoy this book as this book is in agreement of my views of looking at SQL with simple logic but strong concepts.

There are few errors in the book but they are very minor and I was able to catch them easily. Authors seem to have good understanding about ORACLE in addition to SQL Server. That introduced some errors but on good side they are able to unleash few ideas which are not easy for SQL Server DBA to think of.

The chapter I enjoyed most is Joins Versus Subquery. Authors very easily explained their needs and differences. This statement shows the strength of chapter; If information from a table is needed in a result set, then that table can not be buried in a subquery- it must be in the outer query; simple but effective.

I highly recommend this book, if you are interested in learning about SQL in easy way. This book is PERFECT book for beginners and great reference for experience developers.

Rating : 4 and 1/2 stars

In Summary, This is must have book for every SQL student.

Pinal DavePrincipal Database Administrator

SQL SERVER – UDF – Validate Integer Function

August 11, 2007 by pinaldave

I received quite a good feedback about my post about SQL SERVER – Validate Field For DATE datatype using function ISDATE()

One of the most interesting comment I received from my reader from Canada. I was suggested just like ISDATE() to write about ISNUMERIC() which can be used to validate numeric values.

As per BOL:ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it

Page 117: 9 Jan 01, 2007-431 Dec 31, 2007

returns 0. ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($).

Now this is issue with ISNUMERIC() function. It even suggest variable as numeric when it is not. I use following function to validate instead of ISNUMERIC() to validate if number is numeric or not.

Code:CREATE FUNCTION dbo.udf_IsNumeric(@Number VARCHAR(100))RETURNS BITBEGINDECLARE @Ret BITIF LEFT(@Number, 1) = '-'SET @Number = SUBSTRING(@Number, 2, LEN(@Number))IF (PATINDEX('%[^0-9-]%’, @Number) = 0AND CHARINDEX(’-', @Number) <= 1AND @Number NOT IN ('.', '-', '+', '^')AND LEN(@Number)>0AND @Number NOT LIKE '%-%')SET @Ret = 1ELSESET @Ret = 0RETURN @RetENDGO

Example:SELECT '999' TestValue,dbo.udf_IsNumeric('999') NumericTest;SELECT 'abc' TestValue,dbo.udf_IsNumeric('abc') NumericTest;SELECT '9+9' TestValue,dbo.udf_IsNumeric('9+9') NumericTest;SELECT '$9.9' TestValue,dbo.udf_IsNumeric('$9.9') NumericTest;SELECT 'SQLAuthority' TestValue,dbo.udf_IsNumeric('SQLAuthority') NumericTest;ResultSet:TestValue NumericTest——— ———–999 1

TestValue NumericTest——— ———–abc 0

TestValue NumericTest——— ———–9+9 0

TestValue NumericTest——— ———–$9.9 0

TestValue NumericTest———— ———–SQLAuthority 0This function is part of my personal script library and source of this function was not listed with it. I searched online and found similar function online here. There is in-depth analysis of ISNUMERIC() function and its test. I encourage my readers to read that article as well.

SQL SERVER – 2005 – Find Stored Procedure Create Date and Modified Date

August 10, 2007 by pinaldave

This post is second part of my previous post about SQL SERVER – 2005 – List All Stored Procedure Modified in Last N Days

Page 118: 9 Jan 01, 2007-431 Dec 31, 2007

This post demonstrates the script which displays create date and modify date for any specific stored procedure in SQL Server.USE AdventureWorks;GOSELECT name, create_date, modify_dateFROM sys.objectsWHERE type = 'P'AND name = 'uspUpdateEmployeeHireInfo'GO

SQL SERVER – 2005 – List All The Column With Specific Data Types

August 9, 2007 by pinaldave

Since we upgraded to SQL Server 2005 from SQL Server 2000, we have used following script to find out columns with specific datatypes many times. It is very handy small script.

SQL Server 2005 has new datatype of VARCHAR(MAX), we decided to change all our TEXT datatype columns to VARCHAR(MAX). The reason to do that as TEXT datatype will be deprecated in future version of SQL Server and VARCHAR(MAX) is superior to TEXT datatype in features. We run following script to identify all the columns which are TEXT datatype and developer converts them to VARCHAR(MAX)

Script 1 : Simple script to identify all the columns with datatype TEXT in specific databaseSELECT OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnNameFROM sys.columns AS cJOIN sys.types AS t ON c.user_type_id=t.user_type_idWHERE t.name = 'text' --you can change text to other datatypesORDER BY c.OBJECT_ID;GO

Script 2 : Extended script to identify all the columns datatype and other information in specific databaseSELECTOBJECT_NAME(c.OBJECT_ID) TableName,c.name AS ColumnName,SCHEMA_NAME(t.schema_id) AS SchemaName,t.name AS TypeName,t.is_user_defined,t.is_assembly_type,c.max_length,c.PRECISION,c.scaleFROM sys.columns AS cJOIN sys.types AS t ON c.user_type_id=t.user_type_idORDER BY c.OBJECT_ID;

SQL SERVER – 2005 – SSMS – Enable Autogrowth Database Property

August 8, 2007 by pinaldave

We can use SSMS to Enable Autogrowth property of the Database.

Right-click on Database click on Properties and click on Files. There will be column of Autogrowth, click on small box with three (…) dots.

Page 119: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 – List Tables in Database Without Primary Key

August 7, 2007 by pinaldave

This is very simple but effective script. It list all the table without primary keys.USE DatabaseName;GOSELECT SCHEMA_NAME(schema_id) AS SchemaName,name AS TableNameFROM sys.tablesWHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0ORDER BY SchemaName, TableName;GO

SQL SERVER – Fix : Error 2596 The repair statement was not processed. The database cannot be in read-only mode

August 6, 2007 by pinaldave

ERROR 2596 : The repair statement was not processed. The database cannot be in read-only mode.

This error is described little confusing. I have received quite a few email asking why this error happens when the database is already in read-only mode.

Page 120: 9 Jan 01, 2007-431 Dec 31, 2007

Fix/Solution/Workaround :Yes, This error happens when the database is in read only mode. To repair the database using DBCC command it should not be in repair mode. It should be in read-write mode before it is repaired.USE MASTER;GOALTER DATABASE AdventureWorksSET SINGLE_USERWITHROLLBACK IMMEDIATE;GOALTER DATABASE AdventureWorksSET READ_WRITE;GOALTER DATABASE AdventureWorksSET MULTI_USER;GO

SQL SERVER – Stop SQL Server Immediately Using T-SQL

August 5, 2007 by pinaldave

This question has came up many quite a few times with our development team as well as emails I have received about how to stop SQL Server immediately (due to accidentally ran t-sql, business logic or just need of to stop SQL Server using T-SQL).

Answer is very simple, run following command in SQL Editor.

SHUTDOWN

If you want to shutdown the system without performing checkpoints in every database and without attempting to terminate all user processes use following command.

SHUTDOWN WITH NOWAIT

Server can be turned off using windows services as well. SHUTDOWN permissions are assigned to members of the sysadmin and serveradmin fixed server roles.

SQL SERVER – One Thing All DBA Must Know

August 4, 2007 by pinaldave

FULLY BACKUP DATABASE.

Update : I posted this post with only line. However I received many comments and questions asking different questions related to it. I have compiled all of them and modified this post.

Most asked Question : What is the best time when database should be backed up?Answer : When everything is running perfect. This is the time when backup should be taken because in troubled time this is the backup required to be restored. The best backup is when system was running PERFECT.

Question : I am experienced DBA, what should be the frequency of backup when I am upgrading the system or modifying the database?Answer : I am sure you already know answer as experienced DBA. Adding my 2 cents, just like any other DBA. Errors, mistakes and accidents do not discrimination based on experience of DBA.

Question : I am new to this area. Which is the best medium of the taking backup?Answer : Every System Admin has their opinion based on company policy. We use SAN with RAID 10 configuration. In meeting with some senior architects of other prominent companies two weeks ago, they suggested we are overprotecting our database backup. Well, that is how I like my Database backup. Better safe than sorrow.

Page 121: 9 Jan 01, 2007-431 Dec 31, 2007

Question : Help! I did something wrong. I do not know what to do.Answer : Take full backup of the database and pray.

Question : I want to learn more about database backup. Do you have any other suggestions?Answer : Sure. Please visit Additional Articles to see more articles related to this articles. Additional Articles .

SQLAuthority News – Download SQL Server 2005 Samples and Sample Databases

August 4, 2007 by pinaldave

SQL Server code samples and sample databases are now hosted on CodePlex. Codeplex is the project hosting site for Microsoft SQL Server Samples and Community Projects. The portal page for SQL Server on Codeplex catalogs samples included with Product Releases, samples from the community, and independent SQL Server Community projects.

Visit the SQL Server Samples and Community Projects page on CodePlex.

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

SQLAuthority News – Author Visit – Database Architecture and Implementation Discussion – New York, New Jersey

August 4, 2007 by pinaldave

I will be traveling for next two days to New York and New Jersey for Database Architecture and Implementation Discussion with one of the largest software technology company. The major focus of this firm is environmental product analysis. I will be not able to answer any questions, comments and emails

Page 122: 9 Jan 01, 2007-431 Dec 31, 2007

during next two days 8/5 Saturday and 8/6 Sunday. I will post all the interesting details (which I can disclose safely without violating privacy policy) once I am come back to my city – Las Vegas.

I am looking forward to meet industry giants and prominent personalities for next two days.

SQLAuthority News – Microsoft SQL Server Compact 3.5 Server Tools Beta 2 Released

August 3, 2007 by pinaldave

SQL Server Compact 3.5 Server Tools installs replication components on the IIS server enabling merge replication and remote data access (RDA) between SQL Server Compact 3.5 database on a Windows Desktop & Mobile devices and database servers running SQL Server 2005 and later versions of SQL Server 2005.

Download SQL Server Compact 3.5

For more information please see the SQL Server Compact 3.5 Books Online

SQL SERVER – Two Different Ways to Comment Code – Explanation and Example

August 3, 2007 by pinaldave

SQL Server has two different ways to comment code.

1) Line comments

Line comments starts with two dashes(–) and ends with carriage returns. Everything between two dashes(–) and carriage returns is considered as comment. This comments can be placed anywhere in the code. This comment can be placed after code in the same line and everything before two dashes (–) will execute like normal T-SQL and after two dashes(–) will not be executed and considered as comment.

Example:SELECT *–---This table nameFROM Sales.ProductsWHERE ProductID > 10 –---This is filter condition

2) Block comments

Block comments starts with a forward-slash and asterisk (/*) and ends with asterisk and forward-slash (*/). Everything between forward-slash and asterisk (/*) and ends with asterisk and forward-slash (*/) is considered as comments. This comment are usually placed before or after big chunk of code, however it can be placed anywhere in the code. This comment can span more than one line.

Example:

/*This is example of blog commentFollowing table is example of same retrieveand filter condition*/SELECT *FROM Sales.ProductsWHERE ProductID > 10

Additional Notes:There is no limit for the length of the comment.Comments can be nested.GO Command is not allowed anywhere in commented text.

SQLAuthority News – Book Review – SQL Server 2005 Practical Troubleshooting: The Database Engine

Page 123: 9 Jan 01, 2007-431 Dec 31, 2007

August 2, 2007 by pinaldave

SQLAuthority.com Book Review :SQL Server 2005 Practical Troubleshooting: The Database Engine (SQL Server Series) (Paperback) by Ken Henderson

Link to book on Amazon – (This is not affiliate link)

Short Review : Database Administrators can use this book on a daily basis in SQL Server 2005 troubleshooting and problem solving. Answers to SQL issues can be swiftly located using the index of this book.This book covers the topics and subjects which any other books, blogs or websites (including MSDN, BOL) do not cover. This book provides DBAs with solutions which can be used by user in highly dynamic environments to resolve common and specialized problems. This book tells user what to do when something goes wrong with SQL Server 2005. This book is an edge case, but is something that can make the difference between a SQL Server application meeting customer needs and it going down in flames. This book is a good place to begin troubleshooting expedition.

Detail Review : This book will not teach you basic T-SQL from basic and it is not easy and interesting training text book. This book is more like guide to save the troubled time. This book must be read by all the DBA before hand to know what kind of bad (worst!) situation can arise and how this book can be used to prevent the situation or fix it if it has already happened. The authors obviously knows the product very well from inside out, many of the authors are working for Microsoft or MVP. The authors communicate the the topic very well, many places there is lots of code dump, however that is appropriately justified looking at the content covered in the book and direction of the topic taken in the book. The Authors unveils the secretes of SQL Server 2005 internals. We can easily understand how the SQL Server 2005 is working, which helps when something goes wrong.

This book contains many interesting topics. Regular readers of my blog knows that my favorite subject is data corruption and recovery and server crashes and other critical failures. I enjoy writing and researching SQL Server errors and their resolution. It is extremely important to know the common errors and their solution. This book covers errors in depth and in detail. This book tries to cover many subjects in 480 pages, which makes sometime book little heavy to read.

The book covers complex subject very easily and in simple words. For example,“Last Known Good – When was the last time DBCC CHECKDB reported no errors for this database? SQL Server 2005 saves in the database information about the last time a DBCC CHECKDB was run without errors on the database.”“Run DBCC FREEPROCCACHE. This clears the procedure cache of any cached plans that are not currently in use.”“No matter how accurate the planning or estimate is, you might still run out of space in production. The

Page 124: 9 Jan 01, 2007-431 Dec 31, 2007

best practice here is to set up the SQLDiag service to constantly monitor the production system and take action before you run out of space.”

This book comes up with CD which contains some useful software (SQL Nexus, TraceBuster, DataDemon) and sample code of the book. I have yet to try the software myself.

Rating : 4 and 1/2 stars

In Summary, This should be a standard book on most DBA’s desktops.

Pinal DavePrincipal Database Administrator(http://www.SQLAuthority.com)

SQL SERVER – FIX : Error 945 Database cannot be opened due to inaccessible files or insufficient memory or disk space. See the SQL Server error log for details

August 2, 2007 by pinaldave

SQL SERVER – FIX : Error 945 Database cannot be opened due to inaccessible files or insufficient memory or disk space. See the SQL Server error log for details

This error is very common and many times, I have seen affect of this error as Suspected Database, Database Operation Ceased, Database Stopped transactions. Solution to this error is simple but very important.

Fix/Solution/WorkAround:

1) If possible add more hard drive space either by removing of unnecessary files from hard drive or add new hard drive with larger size.

2) Check if the database is set to Autogrow on.

3) Check if the account which is trying to access the database has enough permission to perform operation.

4) Make sure that .mdf and .ldf file are not marked as read only on operating system file system level.

SQL SERVER – 2008 – July CTP Released

August 1, 2007 by pinaldave

SQL Server 2008 July Community Technology Preview has been released. With SQL Server 2008 July CTP release, customers can immediately utilize new capabilities that support their mission-critical platform and enable pervasive insight across the enterprise. SQL Server 2008 lays the groundwork for innovative policy-based management that enables administrators to reduce their time spent on maintenance tasks. SQL Server 2008 provides enhancements in the SQL Server BI platform by enabling customers to provide up-to-date information with Change Data Capture and MERGE features, and develop highly scalable analysis services cubes with new development environments.

Download SQL Server 2008 CTP from here.

Read SQL Server 2008 Improvement Pillars here.

Page 125: 9 Jan 01, 2007-431 Dec 31, 2007

(Reference : Microsoft Connect)

SQLAuthority News – My Favorite Articles of This Blog

July 31, 2007 by pinaldave

The question I receive very often is I have more than 250 articles so far on this blog, which are my most favorite articles so far? Yesterday while talking with my parents on occasion of my birthday, they asked the same question to me. Answer is I keep running list of the my personal favorite articles on my personal website. I update it very frequently.

Visit Author’s Personal Favorite Best Articles List

SQLAuthority News – Birthday of SQL Authority Author

July 30, 2007 by pinaldave

Today is Birthday of SQL Authority Author.

Thought of the day : Family is everything.

http://www.pinaldave.comhttp://www.SQLAuthority.com

SQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

July 29, 2007 by pinaldave

Download Data Warehousing Interview Questions and Answers Complete List

It was great pleasure to write latest series about Data Warehousing Interview Questions and Answers. Just like always again I received lost of suggestion and follow up questions. I have tried to accommodate all of

Page 126: 9 Jan 01, 2007-431 Dec 31, 2007

them in last post in the series. I hope this series is helpful to all candidates who are seeking job as well interviewers. I have combined all the questions and answers in the one PDF which is available to download and refer at convenience.

Download Data Warehousing Interview Questions and Answers Complete List

Complete Series of SQL Server Interview Questions and AnswersSQL SERVER – Data Warehousing Interview Questions and Answers – IntroductionSQL SERVER – Data Warehousing Interview Questions and Answers – Part 1SQL SERVER – Data Warehousing Interview Questions and Answers – Part 2SQL SERVER – Data Warehousing Interview Questions and Answers – Part 3SQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

Additional Series List Available to DownloadSQL Server Interview Questions and Answers Complete List DownloadSQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – Data Warehousing Interview Questions and Answers – Part 3

July 28, 2007 by pinaldave

What are slowly changing dimensions (SCD)?SCD is abbreviation of Slowly changing dimensions. SCD applies to cases where the attribute for a record varies over time.There are three different types of SCD.1) SCD1 : The new record replaces the original record. Only one record exist in database – current data.2) SCD2 : A new record is added into the customer dimension table. Two records exist in database – current data and previous history data.3) SCD3 : The original data is modified to include new data. One record exist in database – new information are attached with old information in same row.

What is hybrid slowly changing dimension?Hybrid SCDs are combination of both SCD 1 and SCD 2. It may happen that in a table, some columns are important and we need to track changes for them i.e capture the historical data for them whereas in some columns even if the data changes, we don’t care.

What is BUS Schema?BUS Schema is composed of a master suite of confirmed dimension and standardized definition if facts.

What is a Star Schema?Star schema is a type of organizing the tables such that we can retrieve the result from the database quickly in the warehouse environment.

What Snow Flake Schema?Snowflake Schema, each dimension has a primary dimension table, to which one or more additional dimensions can join. The primary dimension table is the only table that can join to the fact table.

Differences between star and snowflake schema?Star schema – A single fact table with N number of Dimension, all dimensions will be linked directly with a fact table. This schema is de-normalized and results in simple join and less complex query as well as faster results.Snow schema – Any dimensions with extended dimensions are know as snowflake schema, dimensions maybe interlinked or may have one to many relationship with other tables. This schema is normalized and results in complex join and very complex query as well as slower results.

What is Difference between ER Modeling and Dimensional Modeling?ER modeling is used for normalizing the OLTP database design. Dimensional modeling is used for de-normalizing the ROLAP/MOLAP design.

What is degenerate dimension table?If a table contains the values, which are neither dimension nor measures is called degenerate dimensions.

Why is Data Modeling Important?Data modeling is probably the most labor intensive and time consuming part of the development process.

Page 127: 9 Jan 01, 2007-431 Dec 31, 2007

The goal of the data model is to make sure that the all data objects required by the database are completely and accurately represented. Because the data model uses easily understood notations and natural language , it can be reviewed and verified as correct by the end-users.In computer science, data modeling is the process of creating a data model by applying a data model theory to create a data model instance. A data model theory is a formal data model description. When data modelling, we are structuring and organizing data. These data structures are then typically implemented in a database management system. In addition to defining and organizing the data, data modeling will impose (implicitly or explicitly) constraints or limitations on the data placed within the structure.

Managing large quantities of structured and unstructured data is a primary function of information systems. Data models describe structured data for storage in data management systems such as relational databases. They typically do not describe unstructured data, such as word processing documents, email messages, pictures, digital audio, and video. (Reference : Wikipedia)

What is surrogate key?Surrogate key is a substitution for the natural primary key. It is just a unique identifier or number for each row that can be used for the primary key to the table. The only requirement for a surrogate primary key is that it is unique for each row in the table. It is useful because the natural primary key can change and this makes updates more difficult.Surrogated keys are always integer or numeric.

What is Data Mart?A data mart (DM) is a specialized version of a data warehouse (DW). Like data warehouses, data marts contain a snapshot of operational data that helps business people to strategize based on analyses of past trends and experiences. The key difference is that the creation of a data mart is predicated on a specific, predefined need for a certain grouping and configuration of select data. A data mart configuration emphasizes easy access to relevant information (Reference : Wiki). Data Marts are designed to help manager make strategic decisions about their business.

What is the difference between OLAP and data warehouse?Datawarehouse is the place where the data is stored for analyzing where as OLAP is the process of analyzing the data,managing aggregations, partitioning information into cubes for in depth visualization.

What is a Cube and Linked Cube with reference to data warehouse?Cubes are logical representation of multidimensional data.The edge of the cube contains dimension members and the body of the cube contains data values. The linking in cube ensures that the data in the cubes remain consistent.

What is junk dimension?A number of very small dimensions might be lumped together to form a single dimension, a junk dimension – the attributes are not closely related. Grouping of Random flags and text Attributes in a dimension and moving them to a separate sub dimension is known as junk dimension.

What is snapshot with reference to data warehouse?You can disconnect the report from the catalog to which it is attached by saving the report with a snapshot of the data.

What is active data warehousing?An active data warehouse provides information that enables decision-makers within an organization to manage customer relationships nimbly, efficiently and proactively.

What is the difference between data warehousing and business intelligence?Data warehousing deals with all aspects of managing the development, implementation and operation of a data warehouse or data mart including meta data management, data acquisition, data cleansing, data transformation, storage management, data distribution, data archiving, operational reporting, analytical reporting, security management, backup/recovery planning, etc. Business intelligence, on the other hand, is a set of software tools that enable an organization to analyze measurable aspects of their business such as sales performance, profitability, operational efficiency, effectiveness of marketing campaigns, market penetration among certain customer groups, cost trends, anomalies and exceptions, etc. Typically, the term “business intelligence” is used to encompass OLAP, data visualization, data mining and query/reporting tools. (Reference : Les Barbusinski)

Explain paradigm of Bill Inmon and Ralph Kimball.Bill Inmon’s paradigm: Data warehouse is one part of the overall business intelligence system. An enterprise has one data warehouse, and data marts source their information from the data warehouse. In the data warehouse, information is stored in 3rd normal form.

Page 128: 9 Jan 01, 2007-431 Dec 31, 2007

Ralph Kimball’s paradigm: Data warehouse is the conglomerate of all data marts within the enterprise. Information is always stored in the dimensional model.

Complete Series of SQL Server Interview Questions and AnswersSQL SERVER – Data Warehousing Interview Questions and Answers – IntroductionSQL SERVER – Data Warehousing Interview Questions and Answers – Part 1SQL SERVER – Data Warehousing Interview Questions and Answers – Part 2SQL SERVER – Data Warehousing Interview Questions and Answers – Part 3SQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

Additional Series List Available to DownloadSQL Server Interview Questions and Answers Complete List DownloadSQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – Data Warehousing Interview Questions and Answers – Part 2

July 27, 2007 by pinaldave

What are normalization forms?Please visit this article.

Describes the foreign key columns in fact table and dimension table?Foreign keys of dimension tables are primary keys of entity tables.Foreign keys of facts tables are primary keys of Dimension tables.

What is Data Mining?Data Mining is the process of analyzing data from different perspectives and summarizing it into useful information.

What is the difference between view and materialized view?A view takes the output of a query and makes it appear like a virtual table and it can be used in place of tables.A materialized view provides indirect access to table data by storing the results of a query in a separate schema object.

What is ER Diagram?Entity Relationship Diagrams are a major data modelling tool and will help organize the data in your project into entities and define the relationships between the entities. This process has proved to enable the analyst to produce a good database structure so that the data can be stored and retrieved in a most efficient manner.An entity-relationship (ER) diagram is a specialized graphic that illustrates the interrelationships between entities in a database. A type of diagram used in data modeling for relational data bases. These diagrams show the structure of each table and the links between tables.

What is ODS?ODS is abbreviation of Operational Data Store. A database structure that is a repository for near real-time operational data rather than long term trend data. The ODS may further become the enterprise shared operational database, allowing operational systems that are being re-engineered to use the ODS as there operation databases.

What is ETL?ETL is abbreviation of extract, transform, and load. ETL is software that enables businesses to consolidate their disparate data while moving it from place to place, and it doesn’t really matter that that data is in different forms or formats. The data can come from any source.ETL is powerful enough to handle such data disparities. First, the extract function reads data from a specified source database and extracts a desired subset of data. Next, the transform function works with the acquired data – using rules orlookup tables, or creating combinations with other data – to convert it to the desired state. Finally, the load function is used to write the resulting data to a target database.

What is VLDB?VLDB is abbreviation of Very Large DataBase. A one terabyte database would normally be considered to be a VLDB. Typically, these are decision support systems or transaction processing applications serving large numbers of users.

Page 129: 9 Jan 01, 2007-431 Dec 31, 2007

Is OLTP database is design optimal for Data Warehouse?No. OLTP database tables are normalized and it will add additional time to queries to return results. Additionally OLTP database is smaller and it does not contain longer period (many years) data, which needs to be analyzed. A OLTP system is basically ER model and not Dimensional Model. If a complex query is executed on a OLTP system, it may cause a heavy overhead on the OLTP server that will affect the normal business processes.

If de-normalized is improves data warehouse processes, why fact table is in normal form?Foreign keys of facts tables are primary keys of Dimension tables. It is clear that fact table contains columns which are primary key to other table that itself make normal form table.

What are lookup tables?A lookup table is the table placed on the target table based upon the primary key of the target, it just updates the table by allowing only modified (new or updated) records based on thelookup condition.

What are Aggregate tables?Aggregate table contains the summary of existing warehouse data which is grouped to certain levels of dimensions. It is always easy to retrieve data from aggregated tables than visiting original table which has million records. Aggregate tables reduces the load in the database server and increases the performance of the query and can retrieve the result quickly.

What is real time data-warehousing?Data warehousing captures business activity data. Real-time data warehousing captures business activity data as it occurs. As soon as the business activity is complete and there is data about it, the completed activity data flows into the data warehouse and becomes available instantly.

What are conformed dimensions?Conformed dimensions mean the exact same thing with every possible fact table to which they are joined. They are common to the cubes.

What is conformed fact?Conformed dimensions are the dimensions which can be used across multiple Data Marts in combination with multiple facts tables accordingly.

How do you load the time dimension?Time dimensions are usually loaded by a program that loops through all possible dates that may appear in the data. 100 years may be represented in a time dimension, with one row per day.

What is a level of Granularity of a fact table?Level of granularity means level of detail that you put into the fact table in a data warehouse. Level of granularity would mean what detail are you willing to put for each transactional fact.

What are non-additive facts?Non-additive facts are facts that cannot be summed up for any of the dimensions present in the fact table. However they are not considered as useless. If there is changes in dimensions the same facts can be useful.

What is factless facts table?A fact table which does not contain numeric fact columns it is called factless facts table.

Complete Series of SQL Server Interview Questions and AnswersSQL SERVER – Data Warehousing Interview Questions and Answers – IntroductionSQL SERVER – Data Warehousing Interview Questions and Answers – Part 1SQL SERVER – Data Warehousing Interview Questions and Answers – Part 2SQL SERVER – Data Warehousing Interview Questions and Answers – Part 3SQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

Additional Series List Available to DownloadSQL Server Interview Questions and Answers Complete List DownloadSQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – Data Warehousing Interview Questions and Answers – Part 1

July 26, 2007 by pinaldave

Page 130: 9 Jan 01, 2007-431 Dec 31, 2007

What is Data Warehousing?A data warehouse is the main repository of an organization’s historical data, its corporate memory. It contains the raw material for management’s decision support system. The critical factor leading to the use of a data warehouse is that a data analyst can perform complex queries and analysis, such as data mining, on the information without slowing down the operational systems (Ref:Wikipedia). Data warehousing collection of data designed to support management decision making. Data warehouses contain a wide variety of data that present a coherent picture of business conditions at a single point in time. It is a repository of integrated information, available for queries and analysis.

What are fundamental stages of Data Warehousing?Offline Operational Databases – Data warehouses in this initial stage are developed by simply copying the database of an operational system to an off-line server where the processing load of reporting does not impact on the operational system’s performance.Offline Data Warehouse – Data warehouses in this stage of evolution are updated on a regular time cycle (usually daily, weekly or monthly) from the operational systems and the data is stored in an integrated reporting-oriented data structure.Real Time Data Warehouse – Data warehouses at this stage are updated on a transaction or event basis, every time an operational system performs a transaction (e.g. an order or a delivery or a booking etc.)Integrated Data Warehouse – Data warehouses at this stage are used to generate activity or transactions that are passed back into the operational systems for use in the daily activity of the organization.(Reference Wikipedia)

What is Dimensional Modeling?Dimensional data model concept involves two types of tables and it is different from the 3rd normal form. This concepts uses Facts table which contains the measurements of the business and Dimension table which contains the context(dimension of calculation) of the measurements.

What is Fact table?Fact table contains measurements of business processes also fact table contains the foreign keys for the dimension tables. For example, if your business process is “paper production” then “average production of paper by one machine” or “weekly production of paper” would be considered as measurement of business process.

What is Dimension table?Dimensional table contains textual attributes of measurements stored in the facts tables. Dimensional table is a collection of hierarchies, categories and logic which can be used for user to traverse in hierarchy nodes.

What are the Different methods of loading Dimension tables?There are two different ways to load data in dimension tables.Conventional (Slow) :All the constraints and keys are validated against the data before, it is loaded, this way data integrity is maintained.Direct (Fast) :All the constraints and keys are disabled before the data is loaded. Once data is loaded, it is validated against all the constraints and keys. If data is found invalid or dirty it is not included in index and all future processes are skipped on this data.

What is OLTP?OLTP is abbreviation of On-Line Transaction Processing. This system is an application that modifies data the instance it receives and has a large number of concurrent users.

What is OLAP?OLAP is abbreviation of Online Analytical Processing. This system is an application that collects, manages, processes and presents multidimensional data for analysis and management purposes.

What is the difference between OLTP and OLAP? Data SourceOLTP: Operational data is from original data source of the dataOLAP: Consolidation data is from various source.

Process GoalOLTP: Snapshot of business processes which does fundamental business tasksOLAP: Multi-dimensional views of business activities of planning and decision making

Page 131: 9 Jan 01, 2007-431 Dec 31, 2007

Queries and Process ScriptsOLTP: Simple quick running queries ran by users.OLAP: Complex long running queries by system to update the aggregated data.

Database DesignOLTP: Normalized small database. Speed will be not an issue due to smaller database and normalization will not degrade performance. This adopts entity relationship(ER) model and an application-oriented database design.OLAP: De-normalized large database. Speed is issue due to larger database and de-normalizing will improve performance as there will be lesser tables to scan while performing tasks. This adopts star, snowflake or fact constellation mode of subject-oriented database design.

Complete Series of SQL Server Interview Questions and AnswersSQL SERVER – Data Warehousing Interview Questions and Answers – IntroductionSQL SERVER – Data Warehousing Interview Questions and Answers – Part 1SQL SERVER – Data Warehousing Interview Questions and Answers – Part 2SQL SERVER – Data Warehousing Interview Questions and Answers – Part 3SQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

Additional Series List Available to DownloadSQL Server Interview Questions and Answers Complete List DownloadSQL SERVER Database Coding Standards and Guidelines Complete List Download

SQLAuthority News – Interesting Read – Programming Concepts, Structured Thinking Language (STL) and Relationary

July 25, 2007 by pinaldave

I have always enjoyed reading articles and blogs which are different then others. There many be thousands of technology and programming blogs, only few makes difference in the tech world. One of the high quality blog, I enjoy reading is relationary by Grant Czerepak. Grant Czerepak is an IT professional with over 20 years experience in relational database technology specifically in the areas of design, development and administration.

As per Grant Czerepak “In this blog I will be mixing, matching, shifting and sifting paradigms that have come up in my work with relational databases and other concepts I’ve picked up while taking my time to explore the nooks and crannies of my university’s course calendar over seven years, studying the entire NIV version of the Bible over three years, travelling in southeast asia, reading broadly and having several good friends to exchange ideas with over coffee and across the internet. I hope to make entries daily and keep this blog interesting and stimulating.”

Grant Czerepak is also writing book from the posts and articles in his blog. I am really looking forward to read his book. I wish we all know the arrival date of his book.

A blog which is making difference in tech world : relationary

SQL SERVER – Data Warehousing Interview Questions and Answers – Introduction

July 25, 2007 by pinaldave

This series is in response to many of my reader’s continuous request to start Data Warehousing Interview Questions and Answers series. This series is written in the same spirit as previous two series which has received good response.

Samples Question from Interview Questions and Answer SeriesWhat is Data Warehousing?A data warehouse is the main repository of an organization’s historical data, its corporate memory. It contains the raw material for management’s decision support system. The critical factor leading to the use of a data warehouse is that a data analyst can perform complex queries and analysis, such as data mining, on the information without slowing down the operational systems (Ref:Wikipedia). Data warehousing collection of data designed to support management decision making. Data warehouses contain a wide variety of data that present a coherent picture of business conditions at a single point in time. It is a repository of integrated information, available for queries and analysis.

Page 132: 9 Jan 01, 2007-431 Dec 31, 2007

I will post complete series details here. Please watch this space for additional information.

Complete Series of SQL Server Interview Questions and AnswersSQL SERVER – Data Warehousing Interview Questions and Answers – IntroductionSQL SERVER – Data Warehousing Interview Questions and Answers – Part 1SQL SERVER – Data Warehousing Interview Questions and Answers – Part 2SQL SERVER – Data Warehousing Interview Questions and Answers – Part 3SQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

Additional Series List Available to DownloadSQL Server Interview Questions and Answers Complete List DownloadSQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – 2005 – Server and Database Level DDL Triggers Examples and Explanation

July 24, 2007 by pinaldave

I was asked following questions when discussing security issues in meeting with off-shore team of large database consultancy company few days ago. I will only discuss one of the security issue was discussed accidental data modification by developers and DBAs themselves.

How to alter modification in database by system admin himself?

How to prevent accidents due to fat fingers? (Accidental execution of code)

How to display message to contact another developers when another developer tries to modify object another developer working on?

It was interesting conversation. Answer to all the questions is correct assignment of permissions and (when permissions are not an issue) Server and Database Level DDL Triggers. If developers have their own login to SQL Server and it does not have permissions to drop or create objects this will not be issue at all. However, there are still risk of System Admin himself making accidental mistakes. The solution to this will be use Server and Database Level DDL Triggers.

DDL is abbreviation of Data Definition Level. DDL contains schema of the database object. It was always dream of all DBA, when change in mission critical schema of the database or server is attempted it is prevented immediately informing DBA and users automatically. DDL Trigger can now make this dream true. Definition of DDL Trigger (from BOL) is DDL Triggers are a special kind of trigger that fire in response to Data Definition Language (DDL) statements. They can be used to perform administrative tasks in the database such as auditing and regulating database operations.

DML is abbreviation of Data Manipulation Level. DML contains the actual data which is stored in the database schema. UPDATE, INSERT, DELETE, SELECT are clause are used to manipulate database. There is following different between DML and DDL triggers.

DDL triggers do not support INSTEAD OF feature DML triggers. DDL triggers do not have feature of inserted and deleted tables like DML triggers as it does not

participate in database manipulations.

Following example demonstrates how DDL trigger can be used to prevent dropping stored procedure.

Step 1 :

First create any sample stored procedure.USE AdventureWorks;

GO

CREATE PROCEDURE TestSP

AS

Page 133: 9 Jan 01, 2007-431 Dec 31, 2007

SELECT 1 test;

GO

Step 2 :

Create DDL trigger which will prevent dropping the stored procedure.

USE AdventureWorks

GO

CREATE TRIGGER PreventDropSP

ON DATABASE

FOR DROP_PROCEDURE

AS

PRINT 'Dropping Procedure is not allowed.

DDL Trigger is preventing this from happening.

To drop stored procedure run following script.

Script :

DISABLE TRIGGER PreventDropSP ON DATABASE;

<Run your DROP SP>;

ENABLE TRIGGER PreventDropSP ON DATABASE;'

ROLLBACK;

GO

Step 3 :

Now test above trigger by attempting to drop the stored procedure.

USE AdventureWorks

GO

DROP PROCEDURE TestSP;

GO

This should throw following message along with error code 3609 :

Dropping Procedure is not allowed.

DDL Trigger is preventing this from happening.

To drop stored procedure run following script.

Script :

Page 134: 9 Jan 01, 2007-431 Dec 31, 2007

DISABLE TRIGGER PreventDropSP ON DATABASE;

<Run your DROP SP>;

ENABLE TRIGGER PreventDropSP ON DATABASE;

Msg 3609, Level 16, State 2, Line 1

The transaction ended in the trigger. The batch has been aborted.

Step 4 :

Now DISABLE above trigger and it will let you successfully drop the stored procedure previously attempted to drop. Once it is dropped enable trigger again to prevent future accidents.

USE AdventureWorks

GO

DISABLE TRIGGER PreventDropSP ON DATABASE;

DROP PROCEDURE TestSP;

ENABLE TRIGGER PreventDropSP ON DATABASE;

GO

List of all the DDL events (DROP_PROCEDURE in example above) to use with DDL Trigger are listed on MSDN.

If you want to download local copy click here.

SQL SERVER – UDF – Function to Get Previous And Next Work Day – Exclude Saturday and Sunday

July 23, 2007 by pinaldave

While reading ColdFusion blog of Ben Nadel Getting the Previous Day In ColdFusion, Excluding Saturday And Sunday, I realize that I use similar function on my SQL Server Database. This function excludes the Weekends (Saturday and Sunday), and it gets previous as well as next work day.

Script to create function to get previous and next working day.CREATE FUNCTION dbo.udf_GetPrevNextWorkDay (@dtDate DATETIME, @strPrevNext VARCHAR(10))RETURNS DATETIMEASBEGINDECLARE @intDay INTDECLARE @rtResult DATETIMESET @intDay = DATEPART(weekday,@dtDate)--To find Previous working dayIF @strPrevNext = 'Previous'IF @intDay = 1SET @rtResult = DATEADD(d,-2,@dtDate)ELSEIF @intDay = 2SET @rtResult = DATEADD(d,-3,@dtDate)ELSESET @rtResult = DATEADD(d,-1,@dtDate)--To find Next working dayELSEIF @strPrevNext = 'Next'IF @intDay = 6

Page 135: 9 Jan 01, 2007-431 Dec 31, 2007

SET @rtResult = DATEADD(d,3,@dtDate)ELSEIF @intDay = 7SET @rtResult = DATEADD(d,2,@dtDate)ELSESET @rtResult = DATEADD(d,1,@dtDate)--Default case returns date passed to functionELSESET @rtResult = @dtDateRETURN @rtResultENDGO

Following examples will execute above function and provide desired results.SELECT dbo.udf_GetPrevNextWorkDay('1/1/2007','Previous')SELECT dbo.udf_GetPrevNextWorkDay('1/1/2007','Next')SELECT dbo.udf_GetPrevNextWorkDay('12/31/2007','Previous')SELECT dbo.udf_GetPrevNextWorkDay('12/31/2007','Next')

SQL SERVER – UDF – Get the Day of the Week Function

July 23, 2007 by pinaldave

The day of the week can be retrieved in SQL Server by using the DatePart function. The value returned by function is between 1 (Sunday) and 7 (Saturday). To convert this to a string representing the day of the week, use a CASE statement.

Method 1:

Create function running following script: CREATE FUNCTION dbo.udf_DayOfWeek(@dtDate DATETIME)RETURNS VARCHAR(10)ASBEGINDECLARE @rtDayofWeek VARCHAR(10)SELECT @rtDayofWeek = CASE DATEPART(weekday,@dtDate)WHEN 1 THEN 'Sunday'WHEN 2 THEN 'Monday'WHEN 3 THEN 'Tuesday'WHEN 4 THEN 'Wednesday'WHEN 5 THEN 'Thursday'WHEN 6 THEN 'Friday'WHEN 7 THEN 'Saturday'ENDRETURN (@rtDayofWeek)ENDGO

Call this function like this:SELECT dbo.udf_DayOfWeek(GETDATE()) AS DayOfWeekResultSet:DayOfWeek———-Monday

Method 2: (This is update from comments I received below)SELECT DATENAME(dw, GETDATE())

SQLAuthority News – FQL – Facebook Query Language

July 22, 2007 by pinaldave

I was exploring the new hype (promoted by Robert Scoble heavily) today, I found Facebook Developers Documentation very interesting. Facebook API can be queries using FQL – Faceboook Query Language, which is similar to SQL.

Page 136: 9 Jan 01, 2007-431 Dec 31, 2007

Facebook list following advantages of FQL:

Condensed XML reduces bandwidth and parsing costs. More complex requests can reduce the number of requests necessary. Provides a single consistent, unified interface for all of your data. It’s fun!

A sample query in FQL looks likeSELECT concat(first_name, substr(last_name, 0, 1), " is from "UPPER(hometown_location.city), ", yo", statusFROM USERWHERE uid IN (SELECT uid2FROM friendWHERE uid1 = [uid])AND strlen(hometown_location.city) > 0AND status.time > now() - 3600*6

Refer the FQL documentation for table list which can be used in FROM clause for query as well functions and operators allowed in FQL. FQL does not support complex tables joins yet. I am quite impressed with the new attempt to have SQL like query in facebook.

SQL SERVER – Fix : Error Msg 1813, Level 16, State 2, Line 1 Could not open new database ‘yourdatabasename’. CREATE DATABASE is aborted.

July 21, 2007 by pinaldave

Fix : Error Msg 1813, Level 16, State 2, Line 1Could not open new database ‘yourdatabasename’. CREATE DATABASE is aborted.

This errors happens when corrupt database log are attempted to attach to new server. Solution of this error is little long and it involves restart of the server. I recommend following all the steps below in order without skipping any of them.

Fix/Solution/Workaround:

SQL Server logs are corrupted and they need to be rebuilt to make the database operational.Follow all the steps in order. Replace the yourdatabasename name with real name of your database.1. Create a new database with same name which you are trying to recover or restore. (In our error message it is yourdatabasename). Make sure the name of the MDF file (primary data file) and LDF files (Log files) same as previous database data and log file.

2. Stop SQL Server. Move original MDF file from older server (or location) to new server (or location) by replacing just created MDF file. Delete the LDF file of new server just created.

3. Start SQL Server. Database will be marked as suspect, which is expected.

4. Make sure system tables of Master database allows to update the values.USE MASTERGOsp_CONFIGURE 'allow updates', 1RECONFIGURE WITH OVERRIDEGO5. Change database mode to emergency mode.–Following statement will return the current status of the databaseSELECT *FROM sysdatabasesWHERE name = 'yourdatabasename'

—-Following statement will update only one row in databaseBEGINUPDATE sysdatabasesSET status = 32768

Page 137: 9 Jan 01, 2007-431 Dec 31, 2007

WHERE name = 'yourdatabasename'COMMIT TRAN6. Restart SQL Server (This is must, if it is not done SQL Server will through an error)

7. Execute this DBCC command in query window of Management Studio, this will create new log file. Keep the name of this file same as LDF file just deleted from new server :DBCC TRACEON (3604)DBCC REBUILD_LOG(yourdatabasename,'c:\yourdatabasename_log.ldf')GO

DBCC accepts two parameters : first parameter is database name and second parameter is physical path of the log file. Make sure the path is physical, if you put logical file name it will return an error.

8. Reset the database status using following command.sp_RESETSTATUS yourdatabasenameGO

9. Turn off the update to system tables of Master database running following script.USE MASTERGOsp_CONFIGURE 'allow updates',0RECONFIGURE WITH OVERRIDEGOThis should be resolve the problem mentioned above. I always check consistence of the database as well as I reset the status of the database to original status.

10. Reset the database status to previous status–Following statement will update only one row in databaseBEGINUPDATE sysdatabasesSET status = (value retrieved IN first query OF STEP 5)WHERE name = 'yourdatabasename‘COMMIT TRANGO'Note : If during steps 8, 9 , 10 if there is error if database is in use.Set the database to status single user.sp_DBOPTION 'yourdatabasename', 'single user','true'Once the steps 8,9,10 are completed if database is not already in multi user mode run this script.sp_DBOPTION 'yourdatabasename', 'single user','false'If there is any issue while doing above process to fix the error let me know. Make sure that you have done all the steps in order and restarted SQL Server where it is mentioned.

SQL SERVER – Fix : Error Msg 4214 – Error Msg 3013 – BACKUP LOG cannot be performed because there is no current database backup

July 20, 2007 by pinaldave

This is very interesting error as I could not found any documentation on-line. It took me nearly 1 hour to figure out what was creating error.

Msg 4214, Level 16, State 1, Line 1BACKUP LOG cannot be performed because there is no current database backup.Msg 3013, Level 16, State 1, Line 1BACKUP LOG is terminating abnormally.

Reason :This error happened when we were truncating the logs before we take backup of the database.

Fix/Workaround/Solution :Do not truncate log if differential backup is set up. Truncating log before backup brakes continuity of the log and creates issues when they are to be restored. Disrupted continuity creates not useful back up. This errors warns user when backup are becoming worthless.

Transactional backup truncates the log itself so there is no need to truncate log to keep it maintained.

Page 138: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 – SSMS – View/Send Query Results to Text/Grid/Files

July 19, 2007 by pinaldave

Many times I have been asked how to change the result window from Text to Grid and vice versa. There are three different ways to do it.

Method 1 : Key-Board Short CutResults to Text – CTRL + TResults to Grid – CTRL + DResults to File – CTRL + SHIFT + F

Method 2 : Using Toolbar

Method 3 : Using Menubar

Reference

SQL SERVER – SPACE Function Example

Page 139: 9 Jan 01, 2007-431 Dec 31, 2007

July 19, 2007 by pinaldave

A month ago, I wrote about SQL SERVER – TRIM() Function – UDF TRIM() . I was asked in comment if SQL Server has space function?

Yes.SELECT SPACE(100)will generate 100 space characters. The use of SPACE() function is demonstrated in BOL very fine.

Example from BOL:USE AdventureWorks;GOSELECT RTRIM(LastName) + ',' + SPACE(2) + LTRIM(FirstName)FROM Person.ContactORDER BY LastName, FirstName;GO

SQL SERVER – Restore Database Without or With Backup – Everything About Restore and Backup

July 18, 2007 by pinaldave

The questions I received in last two weeks:

“I do not have backup, is it possible to restore database to previous state?”

“How can restore the database without using backup file?”

“I accidentally deleted tables in my database, how can I revert back?”

“How to revert the changes, I have only logs but no complete backup?”

“How to rollback the database changes, my backup file is corrupted?”

Answer:

You need complete backup to rollback your changes. If you do not have complete backup you can not revert back. Sorry.

To restore the database to previous stage if you have full backup:

1) Restore the full backup

2) Restore the latest differential backup.

3) Restore the second most latest (latest – 1) transaction back. Now restore the log to the point step by step.

Reference :

Pinal Dave (http://www.SQLAuthority.com)

SQL SERVER – Restore Database Backup using SQL Script (T-SQL)

SQL SERVER – Recovery Models and Selection

BOL – Full Restore

Page 140: 9 Jan 01, 2007-431 Dec 31, 2007

BOL – Restore (T-SQL)

Microsoft Backup and Restore Links:

Overview of Backup in SQL Server

Backup Under the Simple Recovery Model

Backup Under the Full Recovery Model

Backup Under the Bulk-Logged Recovery Model

Introduction to Backup and Restore Strategies in SQL Server

Creating Full and Differential Backups of a SQL Server Database

Working with Transaction Log Backups

Working with Backup Media in SQL Server

Security Considerations for Backup and Restore

Overview of Restore and Recovery in SQL Server

Implementing Restore Scenarios for SQL Server Databases

Working with Restore Sequences for SQL Server Databases

Backing Up and Restoring System Databases

Using Marked Transactions (Full Recovery Model)

Disaster Recovery

Optimizing Backup and Restore Performance in SQL Server

Understanding Recovery Performance in SQL Server

Backup and Restore in Large Mission-Critical Environments

Backup and Restore APIs for Independent Software Vendors

SQL SERVER – CASE Statement in ORDER BY Clause – ORDER BY using Variable

July 17, 2007 by pinaldave

This article is as per request from Application Development Team Leader of my company. His team encountered code where application was preparing string for ORDER BY clause of SELECT statement. Application was passing this string as variable to Stored Procedure (SP) and SP was using EXEC to execute the SQL string. This is not good for performance as Stored Procedure has to recompile every time due to EXEC. sp_executesql can do the same task but still not the best performance.

Previously:Application:Nesting logic to prepare variable OrderBy.Database:

Page 141: 9 Jan 01, 2007-431 Dec 31, 2007

Stored Procedure takes variable OrderBy as input parameter.SP uses EXEC (or sp_executesql) to execute dynamically build SQL.

This was taking big hit on performance. The issue was how to improve the performance as well as remove the logic of preparing OrderBy from application. The solution I came up was using multiple CASE statement. This solution is listed here in simple version using AdventureWorks sample database. Another challenge was to order by direction of ascending or descending direction. The solution of that issue is also displayed in following example. Test the example with different options for @OrderBy and @OrderByDirection.

Currently:Database only solution:USE AdventureWorksGODECLARE @OrderBy VARCHAR(10)DECLARE @OrderByDirection VARCHAR(1)SET @OrderBy = 'State' ----Other options Postal for PostalCode,---- State for StateProvinceID, City for CitySET @OrderByDirection = 'D' ----Other options A for ascending,---- D for descendingSELECT AddressID, City, StateProvinceID, PostalCodeFROM person.addressWHERE AddressID < 100ORDER BYCASE WHEN @OrderBy = 'Postal'AND @OrderByDirection = 'D'THEN PostalCode END DESC,CASE WHEN @OrderBy = 'Postal'AND @OrderByDirection != 'D'THEN PostalCode END,CASE WHEN @OrderBy = 'State'AND @OrderByDirection = 'D'THEN StateProvinceID END DESC,CASE WHEN @OrderBy = 'State'AND @OrderByDirection != 'D'THEN StateProvinceID END,CASE WHEN @OrderBy = 'City'AND @OrderByDirection = 'D'THEN City END DESC,CASE WHEN @OrderBy = 'City'AND @OrderByDirection != 'D'THEN City ENDGO

Above modified query has improved performance for our stored procedure very much. Let me know if you are implementing similar logic using any other method.

SQL SERVER – Microsoft White Papers – Analysis Services Query Best Practices – Partial Database Availability

July 16, 2007 by pinaldave

Microsoft TechNet frequently releases White Papers on SQL Server Technology. I have read the following two white papers recently. The summary of its content is here.

Analysis Services Query Performance Top 10 Best Practices

1. Optimize cube and measure group design2. Define effective aggregations3. Use partitions4. Write efficient MDX5. Use the query engine cache efficiently6. Ensure flexible aggregations are available to answer queries.7. Tune memory usage8. Tune processor usage9. Scale up where possible10. Scale out when you can no longer scale up

Page 142: 9 Jan 01, 2007-431 Dec 31, 2007

Partial Database Availability

Writer: Danny TambsDownload Word Document

As databases become larger and larger, the infrastructure assets and technology that provide availability become more and more important. The database filegroups feature introduced in previous versions of SQL Server enables the use of multiple database files in order to host very large databases (VLDB) and minimize backup time. In SQL Server 2005 specific files can be set to offline or online.

SQL SERVER – SQL Joke, SQL Humor, SQL Laugh – 15 Signs to Identify Bad DBA

July 15, 2007 by pinaldave

15 Signs to Identify Bad DBA

They think it is bug in SQL Server when two NULL values compared with each other but SQL Server does not say they equal to each other.They do not rename the trigger name thinking it will not work after it is rename.They are looking for difference between Index Scan or Table Scan on Google.They reinstall the SQL Server if they forget the password of SA login.They use model database for testing their script.They believe compiled stored procedure is production ready.They prefix all stored procedures with ’sp_’ to be consistent with MS naming convention.They believe it is best to use stored procedure to move million records across database.They index all the fields in database to improve the performance.They believe that adding a foreign key constraint with the ‘Enforce Relationship’ checkbox unchecked is best way to apply relationships as it ensures relationships with ‘constraint errors’ while modifying the data.They believe SELECT * is better than including all the columns name in SELECT as SQL has to read less syntax.They believe Rules are better than Constraints and try to convert all constraints to rules.They add new column in four steps : Create a new table, Copy all the data over, Drop the old table, Rename the new table.They believe there is bug with SQL Server that it auto creates Clustered Index every time Primary Key is created on table.They think this article is not funny or disagree with at least 5 of the points above.

Note: Please consider this post as humor, when I started to learn about SQL many years ago I disagreed with all of the above points.

SQL SERVER – 2005 Collation Explanation and Translation – Part 2

July 14, 2007 by pinaldave

Following function return all the available collation of SQL Server 2005. My previous article about the SQL SERVER – 2005 Collation Explanation and Translation.

SELECT *FROM sys.fn_HelpCollations()

Result Set: (only few of 1011 records)Name DescriptionLatin1_General_BIN Latin1-General, binary sortLatin1_General_BIN2 Latin1-General, binary code point comparison sortLatin1_General_CI_AI Latin1-General, case-insensitive, accent-insensitive, kanatype-insensitive, width-insensitiveLatin1_General_CI_AI_WS Latin1-General, case-insensitive, accent-insensitive, kanatype-insensitive, width-sensitiveLatin1_General_CI_AI_KS Latin1-General, case-insensitive, accent-insensitive, kanatype-sensitive, width-insensitiveLatin1_General_CI_AI_KS_WS Latin1-General, case-insensitive, accent-insensitive, kanatype-sensitive,

Page 143: 9 Jan 01, 2007-431 Dec 31, 2007

width-sensitiveLatin1_General_CI_AS Latin1-General, case-insensitive, accent-sensitive, kanatype-insensitive, width-insensitiveLatin1_General_CI_AS_WS Latin1-General, case-insensitive, accent-sensitive, kanatype-insensitive, width-sensitiveLatin1_General_CI_AS_KS Latin1-General, case-insensitive, accent-sensitive, kanatype-sensitive, width-insensitiveLatin1_General_CI_AS_KS_WS Latin1-General, case-insensitive, accent-sensitive, kanatype-sensitive, width-sensitiveLatin1_General_CS_AI Latin1-General, case-sensitive, accent-insensitive, kanatype-insensitive, width-insensitiveLatin1_General_CS_AI_WS Latin1-General, case-sensitive, accent-insensitive, kanatype-insensitive, width-sensitiveLatin1_General_CS_AI_KS Latin1-General, case-sensitive, accent-insensitive, kanatype-sensitive, width-insensitiveLatin1_General_CS_AI_KS_WS Latin1-General, case-sensitive, accent-insensitive, kanatype-sensitive, width-sensitiveLatin1_General_CS_AS Latin1-General, case-sensitive, accent-sensitive, kanatype-insensitive, width-insensitiveLatin1_General_CS_AS_WS Latin1-General, case-sensitive, accent-sensitive, kanatype-insensitive, width-sensitiveLatin1_General_CS_AS_KS Latin1-General, case-sensitive, accent-sensitive, kanatype-sensitive, width-insensitiveLatin1_General_CS_AS_KS_WS Latin1-General, case-sensitive, accent-sensitive, kanatype-sensitive, width-sensitive

SQL SERVER – 2005 – Use ALTER DATABASE MODIFY NAME Instead of sp_renameDB to rename

July 13, 2007 by pinaldave

To rename database it is very common to use for SQL Server 2000 user :EXEC sp_renameDB 'oldDB','newDB'sp_renameDB syntax will be deprecated in the future version of SQL Server. It is supported in SQL Server 2005 for backwards compatibility only. It is recommended to use ALTER DATABASE MODIFY NAME instead. New syntax of ALTER DATABASE MODIFY NAME is simple as well.

/* Create Test Database */CREATE DATABASE TestGO/* Rename the Database Test to NewTest */ALTER DATABASE Test MODIFY NAME = NewTestGO/* Cleanup NewTest DatabaseDo not run following command if you want to use the database.It is dropped here for sample database clean up. */DROP DATABASE NewTestGO

SQL SERVER – Validate Field For DATE datatype using function ISDATE()

July 12, 2007 by pinaldave

This article is based on the a question from Jr. Developer at my company. He works with the system, where we import CSV file in our database. One of the field in the database is DATETIME field. Due to architecture requirement we insert all the CSV fields in the temp table which has all the fields VARCHAR. We validate all the data first in temp table (check for inconsistency, malicious code, incorrect data type) and if passed validation we insert them in the final table in database.

We always checked DATETIME field for incorrect data type. One of the user input date as 30/2/2007. The date was sucessfully inserted in the temp table but while inserting from temp table to final table it crashed with error. We had now task to validate incorrect date value before we insert in final table. Jr. Developer asked me how can he do that? We check for incorrect data type (varchar, int, NULL) but this is incorrect date value. Regular expression works fine with them because of mm/dd/yyyy format.

Page 144: 9 Jan 01, 2007-431 Dec 31, 2007

After long history of the problem the solution is very simple. We now use ISDATE() function to validate if the date is valid.

Examples:

----Invalid dateSELECT ISDATE('30/2/2007')RETURNS : 0 (Zero)----Valid dateSELECT ISDATE('12/12/20007)'RETURNS : 1 (ONE)----Invalid DataTypeSELECT ISDATE('SQL')RETURNS : 0 (Zero)

SQLAuthority News – SQL Blog SQLAuthority.com Comment by Mr. Ben Forta

July 11, 2007 by pinaldave

Today is one of the most glorious day for SQLAuthority.com in history. Famous author of Sams Teach Yourself Microsoft SQL Server T-SQL In 10 Minutes, ColdFusion Guru, and well known evangelists Mr. Ben Forta has made comment on his blog about SQLAuthority.com. I encourage all my readers to visit comment link here. I am very thankful to Mr. Forta for finding time to visit my blog from his busy schedule.

I am attaching screen shot of the original post along with this post for reference. Mr. Forta said,

“Pinalkumar Dave is a DBA with extensive SQL Server (and ColdFusion) experience. I just stumbled upon his blog SQL Authority (via a link in a comment on my own blog) and am more than impressed by some of his SQL Server related posts. If you use SQL Server, then this is one blog you should add to your regular reading list.”

If you know me personally, you will know how much I respect Mr. Forta for his wisdom, advise and knowledge about latest technology.

Reference : Forta.com

Page 145: 9 Jan 01, 2007-431 Dec 31, 2007
Page 146: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 – Features Comparison Chart

July 11, 2007 by pinaldave

This post in the response to all the readers who have asked what are the differences between SQL Server 2005 editions.

The reason I have never posted article about this as Microsoft has wonderful comparison chart on Microsoft SQL Server web site. This chart explains the difference between features of Express, Workgroup, Standard, and Enterprise editions.

Visit Microsoft SQL Server 2005 Editions Features Comparison Chart

SQL SERVER – 2008 – Scheduled Launch at an Event in Los Angeles on Feb. 27, 2008

July 11, 2007 by pinaldave

SQL SERVER 2008 will be launched at an Event in Los Angeles on Feb. 27, 2008.

“In anticipation for the most significant Microsoft enterprise event in the next year, Turner announced that Windows Server® 2008, Visual Studio® 2008 and Microsoft SQL Server™ 2008 will launch together at an event in Los Angeles on Feb. 27, 2008, kicking off hundreds of launch events around the world.”

Read original article here.

SQL SERVER – Count Duplicate Records – Rows

July 11, 2007 by pinaldave

In my previous article SQL SERVER – Delete Duplicate Records – Rows, we have seen how we can delete all the duplicate records in one simple query. In this article we will see how to find count of all the duplicate records in the table. Following query demonstrates usage of GROUP BY, HAVING, ORDER BY in one query and returns the results with duplicate column and its count in descending order.

SELECT YourColumn, COUNT(*) TotalCountFROM YourTableGROUP BY YourColumnHAVING COUNT(*) > 1ORDER BY COUNT(*) DESC

SQL SERVER – 2005 – List All Stored Procedure Modified in Last N Days

July 10, 2007 by pinaldave

I usually run following script to check if any stored procedure was deployed on live server without proper authorization in last 7 days. If SQL Server suddenly start behaving in un-expectable behavior and if stored procedure were changed recently, following script can be used to check recently modified stored procedure. If stored procedure was created but never modified afterwards modified date and create date for that stored procedure are same.

SELECT nameFROM sys.objectsWHERE type = 'P'AND DATEDIFF(D,modify_date, GETDATE()) < 7----Change 7 to any other day value

Following script will provide name of all the stored procedure which were created in last 7 days, they may or may not be modified after that.

Page 147: 9 Jan 01, 2007-431 Dec 31, 2007

SELECT nameFROM sys.objectsWHERE type = 'P'AND DATEDIFF(D,create_date, GETDATE()) < 7----Change 7 to any other day value.

Date condition in above script can be adjusted to retrieve required data.

SQL SERVER – Result of EXP (Exponential) to the POWER of PI – Functions Explained

July 9, 2007 by pinaldave

SQL Server can do some intense Mathematical calculations. Following are three very basic and very necessary functions. All the three function does not need explanation. I will not introduce their definition but will demonstrate the usage of function.SELECT PI()GOSELECT POWER(2,5)GOSELECT POWER(8,-2)GOSELECT EXP(99)GOSELECT EXP(1)GO

Results Set :PI———————-3.14159265358979PowerEg1———–32PowerEg2———–0ExpEg1———————-9.88903031934695E+42ExpEg2———————-2.71828182845905Now the Questions asked in the Title of the Article – What is the result of EXP to the POWER of PISELECT POWER(EXP(1), PI())GO

Results———————-23.1406926327793

SQL SERVER – FIX : ERROR Msg 244, Level 16, State 1 – FIX : ERROR Msg 245, Level 16, State 1

July 8, 2007 by pinaldave

FIX : ERROR Msg 244, Level 16, State 1, Line 1FIX : ERROR Msg 245, Level 16, State 1, Line 1 This error can happen due to conversion of one data type to incompatible datatype.

Few examples are:VARCHAR to INT, INT to TINYINT etc.

I have spotted this error happening with CAST or ISNULL, please add comments if you have come across this error in other examples. Following scripts will create this error.SELECT CAST('111111' AS SMALLINT);

Page 148: 9 Jan 01, 2007-431 Dec 31, 2007

SELECT CAST('This is not smallint' AS SMALLINT);The errors received from above two scripts are :

Msg 244, Level 16, State 2, Line 1The conversion of the varchar value ‘111111′ overflowed an INT2 column. Use a larger integer column.Msg 245, Level 16, State 1, Line 2Conversion failed when converting the varchar value ‘This is not smallint’ to data type smallint.

Interesting detail about ISNULL(@var1, @var2) is that it always cast @var2 to @var1. ISNULL function can generate the same error demonstrated in following script.DECLARE @MyVal TINYINTSELECT ISNULL(@MyVal,'123456') AS MyValThe error received from above script is :Msg 245, Level 16, State 1, Line 3Conversion failed when converting the varchar value ‘LongString’ to data type tinyint.

Fix/Solution/WorkAround:Use CAST to convert to correct data type – change the data or change the data type.

Examples using workaround:SELECT CAST('111111' AS VARCHAR(6));SELECT CAST('111' AS SMALLINT);DECLARE @MyVal TINYINTSELECT ISNULL(@MyVal,'123') AS MyVal

SQL SERVER – SQL Joke, SQL Humor, SQL Laugh – Generic Quotes

July 8, 2007 by pinaldave

Few days ago, in meeting I was forced to answer one of the question from non-programmer was considered as funny quotes for long time.

“Yes it is latest year 2005 version of SQL Server – still it will not play your flash movie” — Pinal Dave (SQLAuthority.com)

Many of following quotes are well apply to SQL Server or any database and I find them humorous.

Software is Too Important to be Left to Programmers

– Meilir Page-Jones.

A clever person solves a problem. A wise person avoids it.

– Einstein

If you think good architecture is expensive, try bad architecture.

– Brian Foote and Joseph Yoder

Abraham Lincoln reportedly said that, given eight hours to chop down a tree, he’d spend six sharpening his axe.

– TidBITS 654, quoted by Derek K. Miller, via Art Evans

This saying is popular among scientists (doing experiments), but I believe it applies to software testing, particularly for real-time systems.

– Larry Zana

Page 149: 9 Jan 01, 2007-431 Dec 31, 2007

Q: How many QA testers does it take to change a lightbulb?

A: QA testers don’t change anything. They just report that it’s dark.

– Kerry Zallar

Q: How many software engineers does it take to change a lightbulb?

A: Just one. But the house falls down.

– Andrew Siwko

There’s no time to stop for gas, we’re already late

– Karin Donker

One test is worth a thousand opinions.

If you didn’t write it down, it didn’t happen.

If you’ve found 3 bugs in a program, best estimate is that there are 3 more.

60% of product cost comes after initial shipment.

Your problem is another’s solution;

Your solution will be his problem.

The schedule doesn’t have enough time for maintenance in it.

A lot of bugs get past the tests.

Most old code can’t be maintained.

“If you make a general statement, a programmer says, ‘Yes, but…’

while a designer says, ‘Yes, and…’”

SQL SERVER – Convert Text to Numbers (Integer) – CAST and CONVERT

July 7, 2007 by pinaldave

Few of the questions I receive very frequently. I have collect them in spreadsheet and try to answer them frequently.

How to convert text to integer in SQL? If table column is VARCHAR and has all the numeric values in it, it can be retrieved as Integer using CAST or CONVERT function.

How to use CAST or CONVERT?SELECT CAST(YourVarcharCol AS INT) FROM TableSELECT CONVERT(INT, YourVarcharCol) FROM Table

Will CAST or CONVERT thrown an error when column values converted from alpha-numeric characters to numeric?YES.

Page 150: 9 Jan 01, 2007-431 Dec 31, 2007

Will CAST or CONVERT retrieve only numbers when column values converted from alpha-numeric characters to numeric?NO.

How to parse/retrieve only numbers from column values contains alpha-numeric characters?SQL SERVER – UDF – Function to Parse AlphaNumeric Characters from String

What are the online references for CAST and CONVERT?CAST and CONVERT

SQL SERVER – FIX : Error : msg 8115, Level 16, State 2, Line 2 – Arithmetic overflow error converting expression to data type

July 6, 2007 by pinaldave

Following errors can happen when any field in the database is attempted to insert or update larger data of the same type or other data type.

Msg 8115, LEVEL 16, State 2, Line 2 Arithmetic overflow error converting expression TO data type <ANY DataType>

Example is if integer 111111 is attempted to insert in TINYINT data type it will throw above error, as well as if integer 11111 is attempted to insert in VARCHAR(2) data type it will throw above error.

Fix/Solution/Workaround:1) Verify the inserted/updated value that it is of correct length and data type.2) If inserted/updated value are correct modify the definition of the table to accommodated new data type length.

SQL SERVER – 2005 Best Practices Analyzer Tutorial – Sample Example

July 5, 2007 by pinaldave

Yesterday I posted small note about SQL SERVER – 2005 Best Practices Analyzer (July BPA). I received many request about how BPA is used. Some of readers has asked me to provide sample tutorial which can help start using BPA. This utility has many uses for best practice. I have created very simple and initial tutorial. I encourage to follow that and once used it create your own reports in your desired format. Do not hesitate to install this add-on as I have use this previously to tune our production servers.

Following tutorial about BPA is ran on one of my old laptop, which has SQL Server 2005 installed. The SQL Server had many issues and they all are displayed in the result. Please note this is not production server and all the errors are intentionally generated. This tutorial is explained using images, which are very easy to understand.

Tutorial : DOWNLOAD BPA and install it on your server.

Page 151: 9 Jan 01, 2007-431 Dec 31, 2007
Page 152: 9 Jan 01, 2007-431 Dec 31, 2007
Page 153: 9 Jan 01, 2007-431 Dec 31, 2007
Page 154: 9 Jan 01, 2007-431 Dec 31, 2007
Page 155: 9 Jan 01, 2007-431 Dec 31, 2007
Page 156: 9 Jan 01, 2007-431 Dec 31, 2007
Page 157: 9 Jan 01, 2007-431 Dec 31, 2007
Page 158: 9 Jan 01, 2007-431 Dec 31, 2007
Page 159: 9 Jan 01, 2007-431 Dec 31, 2007
Page 160: 9 Jan 01, 2007-431 Dec 31, 2007

I hope this initial tutorial will help DBA and Developer to start using SQL Server 2005 Best Practices Analyzer. Please play with different options and generate your own desired reports in your desired format.

SQL SERVER – 2005 Best Practices Analyzer (July BPA)

July 4, 2007 by pinaldave

The SQL Server 2005 Best Practices Analyzer (BPA) gathers data from Microsoft Windows and SQL Server configuration settings. BPA uses a predefined list of SQL Server 2005 recommendations and best practices to determine if there are potential issues in the database environment.

DOWNLOAD HERE

SQL SERVER – Definition, Comparison and Difference between HAVING and WHERE Clause

July 4, 2007 by pinaldave

In recent interview sessions in hiring process I asked this question to every prospect who said they know basic SQL. Surprisingly, none answered me correct. They knew lots of things in details but not this simple one. One prospect said he does not know cause it is not on this Blog. Well, here we are with same topic online.

Page 161: 9 Jan 01, 2007-431 Dec 31, 2007

Answer in one line is : HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.

HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.

A HAVING clause is like a WHERE clause, but applies only to groups as a whole, whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause. The WHERE clause is applied first to the individual rows in the tables . Only the rows that meet the conditions in the WHERE clause are grouped. The HAVING clause is then applied to the rows in the result set. Only the groups that meet the HAVING conditions appear in the query output. You can apply a HAVING clause only to columns that also appear in the GROUP BY clause or in an aggregate function. (Reference :BOL)

Example of HAVING and WHERE in one query:

SELECT titles.pub_id, AVG(titles.price)FROM titles INNER JOIN publishersON titles.pub_id = publishers.pub_idWHERE publishers.state = 'CA'GROUP BY titles.pub_idHAVING AVG(titles.price) > 10

Sometimes you can specify the same set of rows using either a WHERE clause or a HAVING clause. In such cases, one method is not more or less efficient than the other. The optimizer always automatically analyzes each statement you enter and selects an efficient means of executing it. It is best to use the syntax that most clearly describes the desired result. In general, that means eliminating undesired rows in earlier clauses.

SQL SERVER – Comparison : Similarity and Difference #TempTable vs @TempVariable

July 3, 2007 by pinaldave

#TempTable and @TempVariable are different things with different scope. Their purpose is different but highly overlapping. TempTables are originated for the storage and & storage & manipulation of temporal data. TempVariables are originated (SQL Server 2000 and onwards only) for returning date-sets from table-valued functions.

Common properties of #TempTable and @TempVariableThey are instantiated in tempdb.They are backed by physical disk.Changes to them are logged in the transaction log1. However, since tempdb always uses the simple recovery model, those transaction log records only last until the next tempdb checkpoint, at which time the tempdb log is truncated.

Discussion of #TempTable and @TempVariable relations with each other.A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch it is declared in. Within its scope, a table variable can be used like a regular table. Table variables are automatically cleaned up at the end of the function, stored procedure, or batch in which they are defined. Table variables require fewer locking and logging resources. If a temporary tables are used in stored procedure, it will create separate copy of the temporary table for each user in system who makes use of that stored procedure. SQL Server identifies the different temporary tables by internally adding a numerical suffix to the name.

Table variables used in stored procedures cause fewer recompilations of the stored procedures than when temporary tables are used. If the temporary tables referred to in a stored procedure are created outside the procedure, that will cause recompilation. Recompilation occurs when DECLARE CURSOR statements whose SELECT statements reference a temporary table, or DROP TABLE statements comes before other statements referencing a temporary table. In each of these cases, changing to a table variable rather than a temporary table will avoid the repeated recompilation.

Temp Tables supports non-clustered indexes and creates statistics on the query executed. This helps some query which needs stats and indexes to run faster. Temp Tables supports input or output parameters. Also they can be copied to another temp tables. Temp tables supports SELECT INTO or INSERT EXEC but Temp

Page 162: 9 Jan 01, 2007-431 Dec 31, 2007

variables does not. Temp Table definition can be changed after it is created. Temp table can be explicitly dropped as well.

My Recommendation: Which one to use? Simple : Choose a TempVariables as Default. If any of the following circumstances arises use TempTables.1) Transactions needs to rollback2) If query optimizer needs stats to run complex query3) If result sets of one tables needed for another stored procedure like SELECT INTO or INSERT EXEC4) Complex logic of dynamic SQL, which are not supported by TableVariables like creating Index or Constraints5) Results set is very large (greater than 100K rows)

The bottom line is that both temporary tables are table variables are invaluable tools in your SQL Server toolbox, and you really should become familiar with both.

SQL SERVER – 2005 Comparison SP_EXECUTESQL vs EXECUTE/EXEC

July 2, 2007 by pinaldave

Common Properties of SP_EXECUTESQL and EXECUTE/EXEC

The Transact-SQL statements in the sp_executesql or EXECUTE string are not compiled into an execution plan until sp_executesql or the EXECUTE statement are executed. The strings are not parsed or checked for errors until they are executed. The names referenced in the strings are not resolved until they are executed.

The Transact-SQL statements in the executed string do not have access to any of the variables declared in the batch that contains thesp_executesql or EXECUTE statement. The batch containing the sp_executesql or EXECUTE statement does not have access to variables or local cursors defined in the executed string.

If the executed string has a USE statement that changes the database context, the change to the database context only lasts untilsp_executesql or the EXECUTE statement completes.

Comparison SP_EXECUTESQL vs EXECUTE/EXEC

sp_executesql gives you the possibility to use parameterised statements, EXECUTE does not. Parameterised statements gives no risk to SQL injection and also gives advantage of cached query plan. The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve readability of your code when there are many parameters are used. When you use thesp_executesql stored procedure to executes a Transact-SQL statements that will be reused many times, the SQL Server query optimizer will reuse the execution plan it generates for the first execution when the change in parameter values to the statement is the only variation.

sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement a number of times when the change in parameter values to the statement is the only variation. Because the Transact-SQL statement itself remains constant and only the parameter values change, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution.

Use SP_EXECUTESQL rather than EXEC(), it has better performance and improved security.

The syntax for sp_executesql for SQL Server 2005 issp_executesql [ @stmt = ] stmt[{, [@params=] N'@parameter_name data_type [ OUT | OUTPUT ][,...n]' }{, [ @param1 = ] 'value1' [ ,...n ] }]The size of the string is limited only by available database server memory. On 64-bit servers, the size of the string is limited to 2 GB, the maximum size of nvarchar(max).

SQL SERVER – Explanation of WITH ENCRYPTION clause for Stored Procedure and User Defined Functions

Page 163: 9 Jan 01, 2007-431 Dec 31, 2007

July 1, 2007 by pinaldave

This article is written to answer following two questions I have received in last one week.

Questions 1) How to hide code of my Stored Procedure that no one can see it? 2) Our DBA has left the job and one of the function which retrieves important information is encrypted, how can we decrypt it and find original code?

Answers 1) Use WITH ENCRYPTION while creating Stored Procedure or User Defined Function. 2) Sorry, unfortunately there is no simple way to decrypt the code. Hard way is too hard to even attempt.

Explanations of WITH ENCRYPTION clause If SP or UDF are created WITH ENCRYPTION it is one way street and it is not possible to decrypt it using SQL Server commands. It is always advised to save a copy of the script used to create the SP or UDF on other media than SQL Server. There is no way to get the original source code once it is executed on Server. Only privileged users who can access system tables over the DAC port or directly access database files as well as can attach a debugger to the server process can retrieve the decrypted procedure from memory at runtime.

CLR SP and UDF can not be encrypted. SQL Server replication can not replicate encrypted SP or UDF.

I believe in fair programming techniques and strongly recommend against encryption. There should be no need to encrypt any code. If there is need to hide any code from certain users in that case user should be restricted using user login permissions.

SQL SERVER – Fix : Error : Server: Msg 131, Level 15, State 3, Line 1 The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

June 30, 2007 by pinaldave

Error:Server: Msg 131, Level 15, State 3, Line 1 The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

When the the length is specified in declaring a VARCHAR variable or column, the maximum length allowed is still 8000.

Fix/WorkAround/Solution: Use either VARCHAR(8000) or VARCHAR(MAX) . VARCHAR(MAX) of SQL Server 2005 is replacement of TEXT of SQL Server 2000.

SQL SERVER – Recompile All The Stored Procedure on Specific Table

June 29, 2007 by pinaldave

I have noticed that after inserting many rows in one table many times the stored procedure on that table executes slower or degrades. This happens quite often after BCP or DTS. I prefer to recompile all the stored procedure on the table, which has faced mass insert or update. sp_recompiles marks stored procedures to recompile when they execute next time.

Example:

----Following script will recompile all the stored procedure on table Sales.Customer in AdventureWorks database.USE AdventureWorks;GOEXEC sp_recompile N'Sales.Customer';GO----Following script will recompile specific stored procedure uspGetBillOfMaterials only.USE AdventureWorks;GOEXEC sp_recompile 'uspGetBillOfMaterials';GO

Page 164: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 Improvements in TempDB

June 28, 2007 by pinaldave

Following are some important improvements in tempdb in SQL Server 2005 over SQL Server 2000Input/Output traffic to TempDB is reduced as logging is improved. In SQL Server 2005 TempDB does not log “after value” everytime. E.g. For INSERT it does not log after value on log as that will be any way logged in the TempTable. Similar for DELETE as It does not have to log After value as it is not there. This is big improvement in performance in SQL Server 2005 for TempDB.

Some other improvement in File System of operating system. (I am not listing them as it does not apply to SQL concepts).

Improvement in UP latch contention. Each file in TempDB is filled up with proportion with the free spaces it reduces the latch contention in TempDB while many users are accessing TempDB.

Worktable caching is improved along with memory management and pre-allocation resources. SQL Sever 2005 caches all the temporary objects (table variables, local tables). If table is smaller than 8 MB it is cached in the TempDB system Catalog, so when it is created again it is there and reduces the work for TempDB. If it is bigger than 8 MB TempDB uses background differed drop. When large object(temporary table) is dropped in TempDB, background process drops it, so main process does not have to wait for this to execute and complete. This improves performance for the application time.

TempDB is used by following feature of SQL Server 2005:

Query Triggers Snapshot isolation and read committed snapshot (RCSI) MARS Online index creation Temporary tables, table variables, and table-valued functions DBCC CHECK LOB parameters Cursors Service Broker and event notification XML and LOB variable Query notifications Database mail Index creation User-defined functions

Best Practices and Recommendations for TempDB in SQL Server.Analyze the existing workload and adjust the space for projected concurrent activities in SQL TempDB.SQL Server does not cache the temp table if it is created as part of dynamic SQL.Perform index maintenance and update statistics on TempDB as well, even thought objects in TempDB are not permanent.Set Auto Grow to ON for TempDB.Instant file initialization improves the performance of auto grow operations in TempDB.Create TempDB database on other disk drive than other database. This will improve performance for database as different disk controller will improve the performance for disk input/output.

SQL SERVER – Running Batch File Using T-SQL – xp_cmdshell bat file

June 27, 2007 by pinaldave

In last month I received few emails emails regarding SQL SERVER – Enable xp_cmdshell using sp_configure.The questions are1) What is the usage of xp_cmdshell and2) How to execute BAT file using T-SQL?

Page 165: 9 Jan 01, 2007-431 Dec 31, 2007

I really like the follow up questions of my posts/articles. Answer is xp_cmdshell can execute shell/system command, which includes batch file.

1) Example of running system command using xp_cmdshell is SQL SERVER – Script to find SQL Server on Network

EXEC master..xp_CMDShell 'ISQL -L'

2) Example of running batch file using T-SQLi) Running standalone batch file (without passed parameters)EXEC master..xp_CMDShell 'c:findword.bat'

ii) Running parameterized batch file

DECLARE @PassedVariable VARCHAR(100)DECLARE @CMDSQL VARCHAR(1000)SET @PassedVariable = 'SqlAuthority.com'SET @CMDSQL = 'c:findword.bat' + @PassedVariableEXEC master..xp_CMDShell @CMDSQL

Book Online has additional examples of xp_cmdshellA. Returning a list of executable filesB. Using Windows net commandsC. Returning no outputD. Using return statusE. Writing variable contents to a fileF. Capturing the result of a command to a file

SQL SERVER – 2005 List All Tables of Database

June 26, 2007 by pinaldave

This is very simple and can be achieved using system table sys.tables.

USE YourDBNameGO SELECT *FROM sys.TablesGO

This will return all the tables in the database which user have created.

SQL SERVER – Explanation and Example Four Part Name

June 26, 2007 by pinaldave

What is four part name?

Explanation : ServerName.DatabaseName.DatabaseOwner.TableName

Example : localhost.AdventureWorks.Person.Contact

SQL SERVER – Repeate String N Times Using String Function REPLICATE

June 25, 2007 by pinaldave

I came across this SQL String Function few days ago while searching for Database Replication. This is T-SQL Function and it repeats the string/character expression N number of times specified in the function.

Page 166: 9 Jan 01, 2007-431 Dec 31, 2007

SELECT REPLICATE( ' http://www.SQLAuthority.com ' , 9 )

This repeats the string http://www.SQLAuthority.com to 9 times in result window. I think it is fun utility to generate repeated text if ever required.

Result Set:http://www.SQLAuthority.com http://www.SQLAuthority.com http://www.SQLAuthority.com http://www.SQLAuthority.com http://www.SQLAuthority.com http://www.SQLAuthority.com http://www.SQLAuthority.com http://www.SQLAuthority.com http://www.SQLAuthority.com

(1 row(s) affected)

SQLAuthority News – Book Review – Microsoft(R) SQL Server 2005 Unleashed (Paperback)

June 24, 2007 by pinaldave

SQLAuthority.com Book Review :

Microsoft(R) SQL Server 2005 Unleashed (Paperback)

by Ray Rankins, Paul Bertucci, Chris Gallelli, Alex T. Silverstein

Link to book on Amazon – (This is not affiliate link)

Short Review :

SQL Server 2005 Unleashed is focused on Database Administration and day-to-day administrative management aspects of SQL Server. All the chapters of this book are heavily based on Book On-line (BOL) and it continue discussing the topics, where BOL leaves off. This makes this book a good reference for those who are looking for additional information, tricks & tips, and behind the scene details. I recommend this book as a wonderful read and hands-on guide for quick reference for Database Administrators.

Detail Review :

Every database book is either for Database Administrators or Database Developers/Architecture. This book covers many details about Database Administration in depth, however there is enough information for Database Developer to satisfy their expectation. This book is more than just a syntax reference, as it continues the topic where Book On-line leaves off. This book provides a behind-the-scenes look into SQL Server, this is very important for experienced DBA. Many DBA does the same job everyday to maintain the SQL Server in optimal condition, there are many task which can be automated to save time and make Database Administration easier. The book covers various methods automatic the routine task of database backup, recovery, database maintenance tasks etc.

Page 167: 9 Jan 01, 2007-431 Dec 31, 2007

There are few new features introduced in SQL Server 2005. This book successfully covers almost all of them. I have been using SQL Server 2005 for almost two years and SQL Server for more than 5 years, I found this book interesting and informative.The chapter about SQL Server Management Studio (SSMS) (replacement of SQL Server 2000 Query Analyzer, Enterprise Manager and Analysis Manager) is quite accurate for those who wants to learn from beginning and it is must read. This book provides very good introduction to SQL Server Business Intelligence (BI) features – Analysis Services, Integration Services, Reporting Services. Backup are most vital responsibility of DBA, which is in depth covered in this book. Managing maintenance plans, backup strategies, backup methods, snapshot backup (new 2005 feature), Mirrored database for backup are highly relevant to backup process.

Authors have done good job keeping each chapter independent. I find it always easy to read when I do not have to jump pages in book to refer the examples of other chapters. Each chapter contains lots of figures about topic which authors are discussing. Occasionally, I felt that I am reading the BOL documentation due to nature of few of the topics. As per my opinion, it is unavoidable to stay away from BOL when writing about SQL Server. Authors have done their best to avoid duplication of the code and have pointed few times to BOL to refer advanced syntax, while they continued discussing about additional information and tricks extending BOL.

Lots of figures and lots of syntax makes this book larger than few other an average book – 1752 pages and 5 lbs. Due to this reasons few additional chapters are included on accompanied CD. Do not forget to go over the CD, as it contains few interesting chapters – Transact-SQL Programming Guidelines, Tips, and Tricks, and SQL Server Full-Text Search. The index of book includes the chapters on the CD as well. I wish that all the chapters in CD were in book, just to have everything at one place. Few chapters in this book are very simple and placed on CD instead of the important and informative chapters, which are on CD currently.

Authors have explained T-SQL concept along with tips which makes this book interesting read. Some of the tips may be well known but still must read to understand the T-SQL completely.

Example : CHECK constraints allow insertions and updates to the table to proceed when the CHECK constraint expression does not evaluate to FALSE. A NULL value is considered to be unknown an does not evaluate to FALSE.

Book’s inclination towards database administration sometimes makes the T-SQL tips interesting to read.

Example : The REORGANIZE operation can generate a large number of transactions during its execution. Another reason for disabling a non-clustered index is to reduce the space requirements when rebuilding the index.

Chapters of this books can be read independent to each other. If you want to read it in order, I recommend following order to read them.

Recommend Order :

Part I Welcome to Microsoft SQL Server

Part III SQL Server Administration

Part II SQL Server Tools and Utilities

Part IV Database Administration

Part VI SQL Server Application Development

Part V SQL Server Performance and Optimization

Part VII SQL Server Business Intelligence Features

Bonus Chapters on the CD

Pros :

Page 168: 9 Jan 01, 2007-431 Dec 31, 2007

In depth coverage of most of the Database Administrative Tasks.

Good coverage of T-SQL.

Interesting approach towards Database Administrative tasks with T-SQL

Simple and precise introduction to Business Intelligence (BI)

Full coverage of backup technology

Bonus articles in CD

Safari books online enabled

Cons:

Lack of examples or quiz at the end of chapters (for those who like to check their knowledge after reading chapter)

Shallow summary at the end of chapter

Chapter organization (order they are listed in book) can be better. Articles in CD are good and should have been included in main book.

Heavy book with more than 1700 pages.

Rating : 4 and 1/2 stars

In Summary, Every DBA should have this book on their book-shelf.

SQL SERVER – Comparison Index Fragmentation, Index De-Fragmentation, Index Rebuild – SQL SERVER 2000 and SQL SERVER 2005

June 24, 2007 by pinaldave

Index Fragmentation:When a page of data fills to 100 percent and more data must be added to it, a page split occurs. To make room for the new data, SQL Server must move half of the data from the full page to a new page. The new page that is created is created after all the pages in database. Therefore, instead of going right from one page to the next when looking for data, SQL Server has to go one page to another page around the database looking for the next page it needs. This is Index Fragmentation. Severity of the Index fragmentation can be determined by querying sys.DM_DB_INDEX_PHYSICAL_STATS.

SQL SERVER 2000:DBCC SHOWCONTIG was used to find index fragmentation. In SQL SERVER 2005 it is deprecated and replaced by query to sys.DM_DB_INDEX_PHYSICAL_STATS.

SQL SERVER 2005:SELECT query to sys.DM_DB_INDEX_PHYSICAL_STATS displays all the Index Fragmentation related information.

Examples to determine Index Fragmentation in SQL SERVER 2005: To return the Index Information for only Sales.SalesOrderDetail Table:USE AdventureWorks;SELECT INDEX_ID, AVG_FRAGMENTATION_IN_PERCENTFROM sys.dm_db_index_physical_stats(DB_ID(),OBJECT_ID(N'Sales.SalesOrderDetail'), NULL, NULL, 'DETAILED')To return all the information for all the Indexes in Database:SELECT *FROM sys.dm_db_index_physical_stats (NULL, NULL, NULL, NULL, NULL);

Page 169: 9 Jan 01, 2007-431 Dec 31, 2007

Index De-Fragmentation and Index Rebuilding:Heavily fragmented indexes can degrade query performance and cause your application to respond slowly. I prefer Index Rebuilding is required if Index is fragmented more than 10%. Reorganizing an index de-fragments the leaf level of clustered and non-clustered indexes on tables and views by physically reordering the leaf-level pages to match the logical order (left to right) of the leaf nodes. Having the pages in order improves index-scanning performance.

SQL SERVER 2000:The DBCC INDEXDEFRAG and DBCC DBREINDEX statements are used to reduce table fragmentation.

SQL SERVER 2005:ALTER INDEX with the REBUILD clause. This statement replaces the DBCC DBREINDEX statement of SQL SERVER 2000. (DBCC DBREINDEX can still be used in SQL SERVER 2005 but will be sure deprecated in future version of SQL SERVER. I do not recommend to continue use of this in SQL SERVER 2005)CREATE INDEX with the DROP_EXISTING clause.Both the above method perform the same function.

Examples to rebuild Index in SQL SERVER 2005: To Rebuild only one Index:USE AdventureWorksGOALTER INDEX PK_ProductPhoto_ProductPhotoIDON Production.ProductPhotoREORGANIZEGO

TO Rebuild all the Indexes on Table with Specifying options:USE AdventureWorksGOALTER INDEX ALL ON Production.ProductREBUILD WITH (FILLFACTOR = 90, SORT_IN_TEMPDB = ON,STATISTICS_NORECOMPUTE = ON)GO

I have been asked following two questions many times:1) What is difference between FILLFACTOR = 0 AND FILLFACTOR = 100?They are SAME.2) What FILLFACTOR my own Database Servers have for Index? Why?90. It works great for me.

SQL SERVER – 2005 Row Overflow Data Explanation

June 23, 2007 by pinaldave

In SQL Server 2000 and SQL Server 2005 a table can have a maximum of 8060 bytes per row. One of my fellow DBA said believed that SQL Server 2000 had that restriction but SQL Server 2005 does not have that restriction and it can have row of 2GB. I totally agreed with me but after discussed in depth we realized that there are more than only 8060 bytes limit.

It is still true for SQL Server 2005 that a table can have maximum of 8060 bytes per row however the restriction has exclusions of few data types. CLR User Defined data-types as well as varchar, nvarchar, varbinary, sql_variants are not limited to bytes per row limitation. However, those data types have limitation that they can not be more than 8000 bytes individually. In SQL Server 2005 one table row can contain more than one varchar(8000) fields. One more thing, the exclusions have exclusions also the limit of each individual column max width of 8000 bytes does not apply to varchar(max), nvarchar(max), varbinary(max), text, image or xml data type columns. Though, sum of all other other kind of data type should be less than 8060 bytes. That means one table can not have three columns with char(4000) or 100K bit field columns.

In summary in SQL Server 2005

Table row can have more than 8060 bytes. (2GB Max) varchar, nvarchar, varbinary, sql_variant, or CLR user-defined type columns can have max 8000

bytes.

Page 170: 9 Jan 01, 2007-431 Dec 31, 2007

varchar(max), nvarchar(max), varbinary(max), text, image or xml data type columns have no restrictions.

All the other data type columns (other than mentioned in above three points) width addition must be still under 8060 byte row limit.

Index can only be created which falls with-in 8060 byte row limit.

SQL SERVER – Explanation and Comparison of NULLIF and ISNULL

June 22, 2007 by pinaldave

Explanation of NULLIFSyntax:NULLIF ( expression , expression )

Returns a null value if the two specified expressions are equal. NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression. NULLIF is equivalent to a searched CASE function in which the two expressions are equal and the resulting expression is NULL.

Following is good example of NULLIF and CASE from BOL:USE AdventureWorks;GOSELECT ProductID, MakeFlag, FinishedGoodsFlag,NULLIF(MakeFlag,FinishedGoodsFlag)AS 'Null if Equal'FROM Production.ProductWHERE ProductID < 10;GOSELECT ProductID, MakeFlag, FinishedGoodsFlag,'Null if Equal' =CASEWHEN MakeFlag = FinishedGoodsFlag THEN NULLELSE MakeFlagENDFROM Production.ProductWHERE ProductID < 10;GO

Explanation of ISNULLSyntax:ISNULL ( check_expression , replacement_value )

Replaces NULL with the specified replacement value. The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different.

Following is good example of ISNULL from BOL:USE AdventureWorks;GOSELECT AVG(ISNULL(Weight, 50))FROM Production.Product;GO

Observation:Interesting observation is NULLIF returns null if it comparison is successful, where as ISNULL returns not null if its comparison is successful. In one way they are opposite to each other.

Puzzle:How to create infinite loop using NULLIF and ISNULL? If this is even possible?

SQLAuthority.com News – iGoogle Gadget Published

June 21, 2007 by pinaldave

I have recently received many requests to add an iGoogle Gadget so it can be integrated on iGoogle home page so I’ve gone ahead and done so: Add iGoogle Gadget

Page 171: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Retrieve Current Date Time in SQL Server CURRENT_TIMESTAMP, GETDATE(), {fn NOW()}

June 21, 2007 by pinaldave

There are three ways to retrieve the current datetime in SQL SERVER.CURRENT_TIMESTAMP, GETDATE(), {fn NOW()}

CURRENT_TIMESTAMPCURRENT_TIMESTAMP is a nondeterministic function. Views and expressions that reference this column cannot be indexed. CURRENT_TIMESTAMP can be used to print the current date and time every time that the report is produced.

GETDATE()GETDATE is a nondeterministic function. Views and expressions that reference this column cannot be indexed. GETDATE can be used to print the current date and time every time that the report is produced.

{fn Now()}The {fn Now()} is an ODBC canonical function which can be used in T-SQL since the OLE DB provider for SQL Server supports them. {fn Now()} can be used to print the current date and time every time that the report is produced.

If you run following script in Query Analyzer. I will give you same results. If you see execution plan there is no performance difference. It is same for all the three select statement.SELECT CURRENT_TIMESTAMPGOSELECT {fn NOW()}GOSELECT GETDATE()GO

Performance:There is absolutely no difference in using any of them. As they are absolutely same.

My Preference:I like GETDATE(). Why? Why bother when they are same!!!

SQL SERVER – Find Length of Text Field

June 20, 2007 by pinaldave

To measure the length of VARCHAR fields the function LEN(varcharfield) is useful.

To measure the length of TEXT fields the function is DATALENGTH(textfield). Len will not work for text field.

Example:SELECT DATALENGTH(yourtextfield) AS TEXTFieldSize

SQLAuthority.com News – Journey to SQL Authority Milestone of SQL Server

June 19, 2007 by pinaldave

SQLAuthority.com News – Journey to SQL Authority Milestone of SQL Server

I am very glad to write this 200th post of this blog. I would like to express my gratitude to all of YOU – my readers for continuously reading this blog. I receive many comments and emails with feedback, questions and suggestion everyday. I enjoy meeting few of you during this journey as well. Please do send me feedback and your request to make this blog better. Following is milestone of Journey to SQL Authority.

SQL Server Interview Questions and Answers Complete List Download (PDF)

Page 172: 9 Jan 01, 2007-431 Dec 31, 2007

SQL Server Database Coding Standards and Guidelines Complete List Download (PDF)

Find SQL Server Job or Post SQL Server Job

Lighter Side of SQL – SQL Humor

Subscribe to SQLAuthority.com by Email for Regular Update

SQLAuthority Feed

New Personal Homepage of SQLAuthority Author Pinal Dave

Updated Resume of SQL Authority Author

List of All Articles of SQL Authority Blog for Easy Navigation

List of My Favorite SQL Articles on SQLAuthority

Search SQLAuthority.com for Quick Search of SQL Keywords

Thank you,

SQL SERVER – Delay Function – WAITFOR clause – Delay Execution of Commands

June 18, 2007 by pinaldave

Blocks the execution of a batch, stored procedure, or transaction until a specified time or time interval is reached, or a specified statement modifies or returns at least one row. This is very useful. Every day when I restore the database to backup server for reports post processing, I use WAITFOR clause.

While executing the WAITFOR statement, the transaction is running and no other requests can run under the same transaction. If the server is busy, the thread may not be immediately scheduled; therefore, the time delay may be longer than the specified time. WAITFOR can be used with query but not with UDF or cursors. WAITFOR wait till TIMEOUT is reached.

Examples of WAITFOR----Delay for 20 secondsWAITFOR DELAY '000:00:20'SELECT '20 Second Delay'GO----Delay till 7 AMWAITFOR TIME '7:00:00'SELECT 'Good Morning'GO

SQL SERVER – De-fragmentation of Database at Operating System to Improve Performance

June 17, 2007 by pinaldave

This issues was brought to me by our Sr. Network Engineer. While running operating system level de-fragmentation using either windows de-fragmentation or third party tool it always skip all the MDF file and never de-fragment them. He was wondering why this happens all the time.

The reason MDF file are skipped all the time in de-fragmentation because they are in use when SQL Server is running. Windows operating system de-fragmentation skips all the file in are currently in use.

After discovering this the real question was how to de-fragment when files are in use. Steps are Stop the Server, Re-start, keep the SQL Server services off and do de-fragmentation.

Page 173: 9 Jan 01, 2007-431 Dec 31, 2007

What if Server can not be taken off-line? In that case, nothing can be done. In my company SQL Server runs on redundant configuration – they are mirrored real time as well fail-over clustering is configured. We took one server down and system ran on safely on fail over server while we ran de-fragmentation on other server. We repeated the same order for all server. We see significant difference in our operating system performance as well as database response time.

One more thing to note, operating system needs more than 15% empty space to do optimal de-fragmentation.

Just for fun I will type my conversation with our Sr. Network Engineer. He is very smart person.

Sr. Network Engineer : Hey Pinal, MDF files does not de-fragment every night.Pinal : May be because they are in use. Needs to alternate and de-fragment on cluster, what do you think?Sr. Network Engineer : Yeah! Thanks. It will be good test for fail-over as well. Will do tonight.

SQL SERVER – 2005 – UDF – User Defined Function to Strip HTML – Parse HTML – No Regular Expression

June 16, 2007 by pinaldave

One of the developer at my company asked is it possible to parse HTML and retrieve only TEXT from it without using regular expression. He wanted to remove everything between < and > and keep only Text. I found question very interesting and quickly wrote UDF which does not use regular expression.

Following UDF takes input as HTML and returns TEXT only. If there is any single quotes in HTML they should be replaced with two single quotes (not double quote) before it is passed as input to function.

CREATE FUNCTION [dbo].[udf_StripHTML](@HTMLText VARCHAR(MAX))RETURNS VARCHAR(MAX)ASBEGINDECLARE @Start INTDECLARE @End INTDECLARE @Length INTSET @Start = CHARINDEX('<',@HTMLText)SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))SET @Length = (@End - @Start) + 1WHILE @Start > 0AND @End > 0AND @Length > 0BEGINSET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')SET @Start = CHARINDEX('<',@HTMLText)SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))SET @Length = (@End - @Start) + 1ENDRETURN LTRIM(RTRIM(@HTMLText))ENDGO

Test above function like this :

SELECT dbo.udf_StripHTML('<b>UDF at SQLAuthority.com </b><br><br><a href="http://www.SQLAuthority.com">SQLAuthority.com</a>')

Result Set:

UDF at SQLAuthority.com SQLAuthority.com

If you want to see this example in action click on Image. It will open large image.

Page 174: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – sp_HelpText for sp_HelpText – Puzzle

June 15, 2007 by pinaldave

It was interesting to me. I was using sp_HelpText to see the text of the stored procedure. Stored Procedure were different so I had copied sp_HelpText on my clipboard and was pasting it in Query Editor of Management Studio. In rush I typed twice sp_HelpText and hit F5.

Result was interesting. What are your guesses? My team mates and few of my readers suggested : SQL Server will be in recursive loop, SQL Server will be not responde, SQL Server will throw an error.

Try this:sp_HelpText sp_HelpText

Result was as expected. SQL Server did its job and displayed the text of sp_HelpText. Nothing unusual happened. This reminded me question I was asked in my high school exam : Write C program, which will print itself. sp_HelpText twice does the same thing. It prints itself.

SQL SERVER – 2005 NorthWind Database or AdventureWorks Database – Samples Databases – Part 2

June 15, 2007 by pinaldave

I have mentioned the history of NorthWind, Pubs and AdventureWorks in my previous post SQL SERVER – 2005 NorthWind Database or AdventureWorks Database – Samples Databases. I have been receiving very frequent request for NorthWind Database for SQL Server 2005 and installation method.

Follow the steps carefully and it will install Northwind and Pubs database in SQL Server without any issue. I have tested all the three method on my home computer and attached the screen shots as well.

Common Step for all the 3 methods

First, go to Microsoft Download Center and download SQL2000SampleDb.msi.Run SQL2000SampleDb.msi it will create “C:\SQL Server 2000 Sample Databases” folder.Now follow any of the following three method to install this databases. I have listed methods in order of my preference.

Page 175: 9 Jan 01, 2007-431 Dec 31, 2007

Method 1: Running SQLCMDNavigate to this folder using command prompt. Start >> Run >> C:\SQL Server 2000 Sample Databases.If you have installed SQL Server as named instance run following command.

c:\>sqlcmd -S .\InstanceName -i instpubs.sqlc:\>sqlcmd -S .\InstanceName -i instnwnd.sql

If you have installed SQL Server as default instance run following command.

c:\>sqlcmd -i instpubs.sqlc:\>sqlcmd -i instnwnd.sql

Verify that NorthWind and Pubs database are installed correctly.Method 2: Running SQL ScriptOpen SQL Server Management Studio. Go to File >> Open >> Navigate to “C:\SQL Server 2000 Sample Databases\instpubs.sql” and “C:\SQL Server 2000 Sample Databases\instnwnd.sql” and run those sql file in order. This will install the database.

Page 176: 9 Jan 01, 2007-431 Dec 31, 2007

Verify that NorthWind and Pubs database are installed correctly.

Method3: Attaching the DatabaseMove Northwind and Pubs database files (MDF and LDF files) to your default database file location (usually – C:\Program Files\Microsoft SQL Server\MSSQL\Data).Open SQL Server Management Studio. Expand the database node >> Right click on Databases >> Click on Attach >> Select NorthWind Database. It will automatically find MDF and LDF file. Click OK.

Page 177: 9 Jan 01, 2007-431 Dec 31, 2007

Repeat the process for Pubs and verify that NorthWind and Pubs database are installed correctly.

SQL SERVER – Easy Sequence of SELECT FROM JOIN WHERE GROUP BY HAVING ORDER BY

June 14, 2007 by pinaldave

I was called many times by Jr. Programmers in team to debug their SQL. I keep log of most of the problems and review them afterwards. This helps me to evaluate my team and identify most important next thing which I can do to improve the performance and productivity of it. Recently we have many new hires and they had almost similar questions. Since, I have send them following sequence of the SELECT clause I am not interrupted often, which helps me to focus on larger project architectural design.

SELECT yourcolumnsFROM tablenamesJOIN tablenamesWHERE conditionGROUP BY yourcolumns

Page 178: 9 Jan 01, 2007-431 Dec 31, 2007

HAVING aggregatecolumn conditionORDER BY yourcolumns

Once above order is memorized it guides the basic construction of SELECT statement. This article is written keeping in mind beginners in SQL Server language and presents very higher level outline of SELECT statement.

SQL SERVER – Explanation SQL SERVER Hash Join

June 14, 2007 by pinaldave

Hash Join works with large data set. I have seen this join used many times in data warehouses applications as well as data mining algorithms. While its characteristics are similar to merge join it does not required ordered result set to join. Hash join requiresequijoin predicate to join tables. Equijoin predicate is comparing values between one table to other table using “equals to” (“=”) operator. Hash join gives best performance when two more join tables are joined and at-least one of them have no index or is not sorted. It is also expected that smaller of the either of table can be read in memory completely (though not necessary).

Hash join is two phase process. 1) Build Phase 2) Probe Phase.

1) Build Phase : It reads rows of smaller table into the memory. It hashes the keys of the rows which will be used for join.

2) Probe Phase : It reads rows of other table and hashes the keys of the rows which will be used for join. While doing this it checks for the matching rows on hashed keys in the table build in Build phase. Smaller table in memory and larger table in disk is basic rule. If smaller table does not fit in memory it spits to hard drive. DBSPACETEMP configuration parameter is used to stored hashed table in probe phase.

In summary, instead of joining on the columns separate hash table is created and it is used to join tables for improved performance.

For further detail and in depth understanding refer Craig Freeman Blog.

There are three main kind of hash joins.1) In-memory hash join In build phase table fit completely in memory.

2) Grace hash join In build phase table does not fit completely in memory and spans to disk.

3) Recursive hash joinIn build phase table is very large and have to use many levels of merge joins.

Hash Bailout word is used for either grace hash join or recursive has join. Hash Bailout reduces the performance for queries to run. Trace inprofiler shows Hash Warning events when hash bailout reduces the performance. Update statistic on the columns used in join will improve the performance of the queries.

SQL SERVER – Fix : Error 8629 The query processor could not produce a query plan from the optimizer because a query cannot update a text, ntext, or image column and a clustering key at the same time.

June 13, 2007 by pinaldave

Error:

Error : 8629 The query processor could not produce a query plan from the optimizer because a query cannot update a text, ntext, or image column and a clustering key at the same time.

Fix/WorkAround/Solution:This error happens usually when multiple rows are updated and their clustering key is part of update. If

Page 179: 9 Jan 01, 2007-431 Dec 31, 2007

multiple row of which clustering keys are updated there is always possibility that they end up having same value, which will violate the clustering key requirements.

Update one row at the time in this situation. Use while loop or cursor (I do not recommend cursor usage)

SQL SERVER – Download 2005 Books Online (May 2007)

June 13, 2007 by pinaldave

Microsoft has merged SQL Server 2005 Expressed to SQL Server 2005 Books Online.

New Version of SQL Server 2005 Books Online is released on June 12, 2007.

Download SQL Server Books Online (BOL)

SQL SERVER – Recovery Models and Selection

June 13, 2007 by pinaldave

SQL Server offers three recovery models: full recovery, simple recovery and bulk-logged recovery. The recovery models determine how much data loss is acceptable and determines whether and how transaction logs can be backed up.

Select Simple Recovery Model if:* Your data is not critical.* Losing all transactions since the last full or differential backup is not an issue.* Data is derived from other data sources and is easily recreated.* Data is static and does not change often.

Select Bulk-Logged Recovery Model if:* Data is critical, but logging large data loads bogs down the system.* Most bulk operations are done off hours and do not interferewith normal transaction processing.* You need to be able to recover to a point in time.

Select Full Recovery Model if:* Data is critical and no data can be lost.* You always need the ability to do a point-in-time recovery.* Bulk-logged activities are intermixed with normal transaction processing.* You are using replication and need the ability to resynchronize alldatabases involved in replication to a specific point in time.

You can switch from any recovery model to another recovery model, but prior to or after the switch, you may need to issue additional transaction log or full backups to ensure you have a complete backup set.ALTER DATABASE Pubs SET RECOVERY FULLGO

Microsoft TechNet

SQL SERVER – LEN and DATALENGTH of NULL Simple Example

June 12, 2007 by pinaldave

Simple but interesting – In recent survey I found that many developers making this generic mistake. I have seen following code in periodic code review. (The code below is not actual code, it is simple sample code)DECLARE @MyVar VARCHAR(10)SET @MyVar = NULLIF (LEN(@MyVar) = 0)

…I decided to send following code to them. After running the following sample code it was clear that LEN of

Page 180: 9 Jan 01, 2007-431 Dec 31, 2007

NULL values is not 0 (Zero) but it is NULL. Similarly, the result for DATALENGTH function is the same. DATALENGTH of NULL is NULL.

Sample Test Version:DECLARE @MyVar VARCHAR(10)SET @MyVar = NULLIF (LEN(@MyVar) = 0)PRINT 'LEN of NULL is 0'ELSEPRINT 'LEN of NULL is NULL'Result Set:LEN of NULL is NULL

SQL SERVER – Cannot resolve collation conflict for equal to operation

June 11, 2007 by pinaldave

Cannot resolve collation conflict for equal to operation.

In MS SQL SERVER, the collation can be set in column level. When compared 2 different collation column in the query, this error comes up.

SELECT IDFROM ItemsTableINNER JOIN AccountsTableWHERE ItemsTable.Collation1Col = AccountsTable.Collation2Col

If columns ItemsTable.Collation1Col and AccountsTable.Collation2Col have different collation, it will generate the error “Cannot resolve collation conflict for equal to operation“.

To resolve the collation conflict add following keywords around “=” operator.

SELECT IDFROM ItemsTableINNER JOIN AccountsTableWHERE ItemsTable.Collation1Col COLLATE DATABASE_DEFAULT= AccountsTable.Collation2Col COLLATE DATABASE_DEFAULT

Collation can affect following areas:

1) Where clauses

2) Join predicates

3) Functions

4) Databases (e.g. TempDB may be in a different collation database_default than the other databases some times)

SQL SERVER – 2005 T-SQL Paging Query Technique Comparison (OVER and ROW_NUMBER()) – CTE vs. Derived Table

June 11, 2007 by pinaldave

I have received few emails and comments about my post SQL SERVER – T-SQL Paging Query Technique Comparison – SQL 2000 vs SQL 2005. The main question was is this can be done using CTE? Absolutely! What about Performance? It is same! Please refer above mentioned article for history of paging.

SQL 2005 Paging Method Using Derived TableUSE AdventureWorks

Page 181: 9 Jan 01, 2007-431 Dec 31, 2007

GODECLARE @StartRow INTDECLARE @EndRow INTSET @StartRow = 120SET @EndRow = 140SELECT FirstName, LastName, EmailAddressFROM (SELECT PC.FirstName, PC.LastName, PC.EmailAddress,ROW_NUMBER() OVER(ORDER BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumberFROM Person.Contact PC) PersonContactWHERE RowNumber > @StartRowAND RowNumber < @EndRowORDER BY FirstName, LastName, EmailAddressGO

SQL 2005 Paging Method Using CTEUSE AdventureWorksGODECLARE @StartRow INTDECLARE @EndRow INTSET @StartRow = 120;SET @EndRow = 140;WITH PersonContact AS(SELECT PC.FirstName, PC.LastName, PC.EmailAddress,ROW_NUMBER() OVER(ORDER BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumberFROM Person.Contact PC)SELECT FirstName, LastName, EmailAddressFROM PersonContactWHERE RowNumber > @StartRowAND RowNumber < @EndRowORDER BY FirstName, LastName, EmailAddressGO

Following Image of Execution Plan displays that the performance for both of them is same with regarding to each other in one batch. This MAY NOT be true when there is complex query in issue. For most of the time, it is will be same.

Page 182: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Retrieve – Select Only Date Part From DateTime – Best Practice

June 10, 2007 by pinaldave

Just a week ago my Database Team member asked me what is the best way to only select date part from datetime. When ran following command it also provide the time along with date.SELECT GETDATE()

ResuleSet:2007-06-10 7:00:56.107

The required outcome was only 2007/06/10.

I asked him to come up with solution by using date functions. The method he suggested was to useSELECT DATEADD(D, 0, DATEDIFF(D, 0, GETDATE()))

I approved his method though, I finally suggested my method using function CONVERT.SELECT CONVERT(VARCHAR(10),GETDATE(),111)

The reason I use this because it is very convenient as well as provides quick support to convert the date in any format. The table which suggest many format are displayed on MSDN.

Some claims that using CONVERT is slower then using DATE functions but it is extremely negligible. I prefer to use CONVERT.

SQL SERVER – Fix : Error : An error has occurred while establishing a connect to the server. Solution with Images.

June 10, 2007 by pinaldave

Page 183: 9 Jan 01, 2007-431 Dec 31, 2007

While reviewing my my blog search engine terms I find Error 40 is the most common error searched. I have previously wrote blog about how to fix this error here : SQL SERVER – Fix : Error : 40 – could not open a connection to SQL server.

Today I have added few screen shot of that error and their solution to help readers who need additional help to understand my post.

Error Screen:

Solution Part 1: Enable SQL Server Service

Solution Part 2: Enable TCP/IP Protocol

Page 184: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Fix : Error : Msg 9514, Level 16, State 1, Line 1 Xml data type is not supported in distributed queries. Remote object ‘OPENROWSET’ has xml column(s).

June 9, 2007 by pinaldave

Error:

Msg 9514, Level 16, State 1, Line 1Xml data type is not supported in distributed queries. Remote object ‘OPENROWSET’ has xml column(s).

This error happens when XML Data Type is queried using OPENROWSET. It was very interesting for me to find the workaround for this.

Fix/WorkAround/Soulution:I CAST the retrieved the XML data type to VARCHAR(MAX).

Example:SELECT a.*FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;','SELECT GroupName, Name, DepartmentID, CAST(MyXML as VARCHAR(MAX))FROM AdventureWorks.HumanResources.DepartmentORDER BY GroupName, Name') AS a;

SQL SERVER – Spatial Database Definition and Research Documents

June 9, 2007 by pinaldave

Recently I was asked in meeting of SQL SERVER user group, what my opinion about spatial database. I answered from my basic knowledge. Spatial database is like database of space (not the star wars or star trek kind space). SQL Server database can understand the numeric and string values. If we ask to SQL Server what is multiplication of 6 and 3 it will provide answer as 18. If we ask to SQL Server what is distance between two points in polygon, it will be not able to answer using native functions. Custom SQL code written by user can do similar coding. In short spatial database is about lines, points, polygons and their interesting features. SQL Server is not spatial database system.

After I came back from home I searched more about it and found some interesting research and documentation. I am posting here assuming it will be interesting to all of my readers.

Another example of spatial and non spatial query is here:Non-spatial: List the names of all company with more than 100 employees.Spatial: List the names of all company within 10 miles of Las Vegas.

Here is the definition from Wikipedia about spatial database :A spatial database is a database that is optimized to store and query data related to objects in space, including points, lines and polygons. While typical databases can understand various numeric and character types of data, additional functionality needs to be added for databases to process spatial data types.

Very interesting paper written by An Introduction to Spatial Database Systems by Ralf Hartmut Güting.Author defines Spatial Database as(1) A spatial database system is a database system.(2) It offers spatial data types (SDTs) in its data model and query language.(3) It supports spatial data types in its implementation, providing at least spatial indexing and efficient algorithms for spatial join.Tutorial in form of slide show can be found here.

Reference for books and slide shows can be found here.

SQL SERVER – UDF – Function to Display Current Week Date and Day – Weekly Calendar

June 8, 2007 by pinaldave

Page 185: 9 Jan 01, 2007-431 Dec 31, 2007

In analytics section of our product I frequently have to display the current week dates with days. Week starts from Sunday. We display the data considering days as column and date and other values in column. If today is Friday June 8, 2007. We need script which can provides days and dates for current week. Following script will generate the required script.

DECLARE @day INTDECLARE @today SMALLDATETIMESET @today = CAST(CONVERT(VARCHAR(10), GETDATE(), 101) AS SMALLDATETIME)SET @day = DATEPART(dw, @today)SELECT DATEADD(dd, 1 - @day, @today) Sunday,DATEADD(dd, 2 - @day, @today) Monday,DATEADD(dd, 3 - @day, @today) Tuesday,DATEADD(dd, 4 - @day, @today) Wednesday,DATEADD(dd, 5 - @day, @today) Thursday,DATEADD(dd, 6 - @day, @today) Friday,DATEADD(dd, 7 - @day, @today) Saturday

Above script can be converted in function.

CREATE FUNCTION dbo.udf_DisplayCurrentWeekDateDays(@today SMALLDATETIME)RETURNS @WeekDateDay TABLE(Sunday SMALLDATETIME,Monday SMALLDATETIME,Tuesday SMALLDATETIME,Wednesday SMALLDATETIME,Thursday SMALLDATETIME,Friday SMALLDATETIME,Saturday SMALLDATETIME)ASBEGINDECLARE @day INTSET @today = CAST(CONVERT(VARCHAR(10), @today, 101) AS SMALLDATETIME)SET @day = DATEPART(dw, @today)INSERT INTO @WeekDateDay (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)SELECT DATEADD(dd, 1 - @day, @today) Sunday,DATEADD(dd, 2 - @day, @today) Monday,DATEADD(dd, 3 - @day, @today) Tuesday,DATEADD(dd, 4 - @day, @today) Wednesday,DATEADD(dd, 5 - @day, @today) Thursday,DATEADD(dd, 6 - @day, @today) Friday,DATEADD(dd, 7 - @day, @today) SaturdayRETURNENDGO

The function can be execute for any day to return the week information for the week the day belongs.----Following will return previous week date and daysSELECT *FROM dbo.udf_DisplayCurrentWeekDateDays(DATEADD(d,-7,GETDATE()))GO

----Following will return current week date and daysSELECT *FROM dbo.udf_DisplayCurrentWeekDateDays(GETDATE())GO

----Following will return next week date and daysSELECT *FROM dbo.udf_DisplayCurrentWeekDateDays(DATEADD(d,7,GETDATE()))GO

Result Set: (Today)Sunday Monday Tuesday———————– ———————– ———————–2007-08-05 00:00:00.000 2007-08-06 00:00:00.000 2007-08-07 00:00:00.000

Page 186: 9 Jan 01, 2007-431 Dec 31, 2007

Wednesday Thursday Friday———————– ———————– ———————–2007-08-08 00:00:00.000 2007-08-09 00:00:00.000 2007-08-10 00:00:00.000Saturday———————–2007-08-11 00:00:00.000

SQL SERVER – Insert Multiple Records Using One Insert Statement – Use of UNION ALL

June 8, 2007 by pinaldave

Update: For SQL Server 2008 there is even better method of Row Construction, please read it here : SQL SERVER – 2008 – Insert Multiple Records Using One Insert Statement – Use of Row Constructor

This is very interesting question I have received from new developer. How can I insert multiple values in table using only one insert? Now this is interesting question. When there are multiple records are to be inserted in the table following is the common way using T-SQL.

USE YourDBGOINSERT INTO MyTable (FirstCol, SecondCol)VALUES ('First',1);INSERT INTO MyTable (FirstCol, SecondCol)VALUES ('Second',2);INSERT INTO MyTable (FirstCol, SecondCol)VALUES ('Third',3);INSERT INTO MyTable (FirstCol, SecondCol)VALUES ('Fourth',4);INSERT INTO MyTable (FirstCol, SecondCol)VALUES ('Fifth',5);GO

The clause INSERT INTO is repeated multiple times. Many times DBA copy and paste it to save time. There is another alternative to this, which I use frequently. I use UNION ALL and INSERT INTO … SELECT… clauses. Regarding performance there is not much difference. If there is performance difference it does not matter as I use this for one time insert script. I enjoy writing this way, as it keeps me focus on task, instead of copy paste. I have explained following script to new developer. He was quite pleased.

USE YourDBGOINSERT INTO MyTable (FirstCol, SecondCol)SELECT 'First' ,1UNION ALLSELECT 'Second' ,2UNION ALLSELECT 'Third' ,3UNION ALLSELECT 'Fourth' ,4UNION ALLSELECT 'Fifth' ,5GO

The effective result is same.

SQL SERVER – 2005 Download New Updated Book On Line (BOL)

June 7, 2007 by pinaldave

Book On Line the primary source for help for many developers has been updated. It now includes the updates till SP2 release. I use book on line for accuracy for my definition and information on this blog.

Download Book On Line (Update June 4th, 2007)

Page 187: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2008 (Katmai) June CTP Released – Improvement Pillars – Diagram

June 7, 2007 by pinaldave

I received quite a few emails in last three days for not mentioning on my blog about SQL Server 2008 (Katmai) CPT June is released. The reason I did not mentioned because I was busy with my mini series SQL SERVER – Database Coding Standards and Guidelines Complete List Download.

SQL Server 2008 (Katmai) June CTP (Community Technology Preview) is announced in TechNet 2007 and is available to download. SQL Server 2008 June CTP enables customers to immediately utilize new capabilities that support their mission-critical platform. The chart below explains important improvements coming online with each CTP. Please visit SQL Server 2008 Improvement Pillars to see interactive chart, which provides great amount of information.

Download SQL Server 2008 (Katmai) CPT June.

Review the white paper about SQL Server 2008 Product Overview.

SQL SERVER – Fix : Error : Error 15401: Windows NT user or group ‘username’ not found. Check the name again.

June 7, 2007 by pinaldave

Fix : Error : Error 15401: Windows NT user or group ‘username’ not found. Check the name again.

This is quite a famous error and I was asked to write about it by couple of readers. The reason I was not writing about this as the solution of this error is very well explained in Book On Line. All the potential causes and their solutions are explained well here. This post/article should be considered as book mark to solution.

Fix/WorkAround/Solution:Refere Microsoft Help and Support : How to troubleshoot error 15401

SQL SERVER Database Coding Standards and Guidelines Complete List Download

June 6, 2007 by pinaldave

Download SQL SERVER Database Coding Standards and Guidelines Complete List

Page 188: 9 Jan 01, 2007-431 Dec 31, 2007

Just like my previous series of SQL Server Interview Questions and Answers Complete List Download, I have received many comments and emails regarding this series. Once I go through all the emails and comments, I will make summary of them and integrate them with my series. I have also received emails asking me to create PDF for download. I have created that as well. Please feel free to download it and use it.

Please ask me any questions you might have. Contact me if you are interested in writing mini series with me.

Download SQL SERVER Database Coding Standards and Guidelines Complete List

Complete Series of Database Coding Standards and GuidelinesSQL SERVER Database Coding Standards and Guidelines – IntroductionSQL SERVER – Database Coding Standards and Guidelines – Part 1SQL SERVER – Database Coding Standards and Guidelines – Part 2SQL SERVER Database Coding Standards and Guidelines Complete List Download

Other popular SeriesSQL Server Interview Questions and Answers Complete List DownloadSQL SERVER – Data Warehousing Interview Questions and Answers Complete List Download

DIGG

SQL SERVER – Database Coding Standards and Guidelines – Part 2

June 5, 2007 by pinaldave

SQL Server Database Coding Standards and Guidelines – Part 2

Coding

Optimize queries using the tools provided by SQL Server5

Do not use SELECT * Return multiple result sets from one stored procedure to avoid trips from the application server to

SQL server Avoid unnecessary use of temporary tables

o Use ‘Derived tables’ or CTE (Common Table Expressions) wherever possible, as they perform better6

Avoid using <> as a comparison operatoro Use ID IN(1,3,4,5) instead of ID <> 2

Use SET NOCOUNT ON at the beginning of stored procedures7

Do not use cursors or application loops to do inserts8

o Instead, use INSERT INTO Fully qualify tables and column names in JOINs Fully qualify all stored procedure and table references in stored procedures. Do not define default values for parameters.

o If a default is needed, the front end will supply the value. Do not use the RECOMPILE option for stored procedures. Place all DECLARE statements before any other code in the procedure. Do not use column numbers in the ORDER BY clause. Do not use GOTO. Check the global variable @@ERROR immediately after executing a data manipulation statement

(like INSERT/UPDATE/DELETE), so that you can rollback the transaction if an error occurso Or use TRY/CATCH

Do basic validations in the front-end itself during data entry Off-load tasks, like string manipulations, concatenations, row numbering, case conversions, type

conversions etc., to the front-end applications if these operations are going to consume more CPU cycles on the database server

Always use a column list in your INSERT statements.

Page 189: 9 Jan 01, 2007-431 Dec 31, 2007

o This helps avoid problems when the table structure changes (like adding or dropping a column).

Minimize the use of NULLs, as they often confuse front-end applications, unless the applications are coded intelligently to eliminate NULLs or convert the NULLs into some other form.

o Any expression that deals with NULL results in a NULL output.o The ISNULL and COALESCE functions are helpful in dealing with NULL values.

Do not use the identitycol or rowguidcol. Avoid the use of cross joins, if possible. When executing an UPDATE or DELETE statement, use the primary key in the WHERE condition, if

possible. This reduces error possibilities. Avoid using TEXT or NTEXT datatypes for storing large textual data.9

o Use the maximum allowed characters of VARCHAR instead Avoid dynamic SQL statements as much as possible.10

Access tables in the same order in your stored procedures and triggers consistently.11

Do not call functions repeatedly within your stored procedures, triggers, functions and batches.12

Default constraints must be defined at the column level. Avoid wild-card characters at the beginning of a word while searching using the LIKE keyword, as

these results in an index scan, which defeats the purpose of an index. Define all constraints, other than defaults, at the table level. When a result set is not needed, use syntax that does not return a result set.13

Avoid rules, database level defaults that must be bound or user-defined data types. While these are legitimate database constructs, opt for constraints and column defaults to hold the database consistent for development and conversion coding.

Constraints that apply to more than one column must be defined at the table level. Use the CHAR data type for a column only when the column is non-nullable.14

Do not use white space in identifiers. The RETURN statement is meant for returning the execution status only, but not data.

Reference:5) Use the graphical execution plan in Query Analyzer or SHOWPLAN_TEXT or SHOWPLAN_ALL commands to analyze your queries. Make sure your queries do an “Index seek” instead of an “Index scan” or a “Table scan.” A table scan or an index scan is a highly undesirable and should be avoided where possible.

6) Consider the following query to find the second highest offer price from the Items table:

SELECT MAX(Price)FROM ProductsWHERE ID IN(SELECT TOP 2 IDFROM ProductsORDER BY Price DESC)

The same query can be re-written using a derived table, as shown below, and it performs generally twice as fast as the above query:

SELECT MAX(Price)FROM(SELECT TOP 2 PriceFROM ProductsORDER BY Price DESC)

7) This suppresses messages like ‘(1 row(s) affected)’ after executing INSERT, UPDATE, DELETE and SELECT statements. Performance is improved due to the reduction of network traffic.

8) Try to avoid server side cursors as much as possible. Always stick to a ’set-based approach’ instead of a ‘procedural approach’ for accessing and manipulating data. Cursors can often be avoided by using SELECT

Page 190: 9 Jan 01, 2007-431 Dec 31, 2007

statements instead. If a cursor is unavoidable, use a WHILE loop instead. For a WHILE loop to replace a cursor, however, you need a column (primary key or unique key) to identify each row uniquely.

9) You cannot directly write or update text data using the INSERT or UPDATE statements. Instead, you have to use special statements like READTEXT, WRITETEXT and UPDATETEXT. So, if you don’t have to store more than 8KB of text, use the CHAR(8000) or VARCHAR(8000) datatype instead.

10) Dynamic SQL tends to be slower than static SQL, as SQL Server must generate an execution plan at runtime. IF and CASE statements come in handy to avoid dynamic SQL.

11) This helps to avoid deadlocks. Other things to keep in mind to avoid deadlocks are:

Keep transactions as short as possible. Touch the minimum amount of data possible during a transaction. Never wait for user input in the middle of a transaction. Do not use higher level locking hints or restrictive isolation levels unless they are absolutely

needed.

12) You might need the length of a string variable in many places of your procedure, but don’t call the LEN function whenever it’s needed. Instead, call the LEN function once and store the result in a variable for later use.

13)

IF EXISTS (SELECT 1FROM ProductsWHERE ID = 50)

Instead Of:

IF EXISTS (SELECT COUNT(ID)FROM ProductsWHERE ID = 50)

14) CHAR(100), when NULL, will consume 100 bytes, resulting in space wastage. Preferably, use VARCHAR(100) in this situation. Variable-length columns have very little processing overhead compared with fixed-length columns.

Complete Series of Database Coding Standards and GuidelinesSQL SERVER Database Coding Standards and Guidelines – IntroductionSQL SERVER – Database Coding Standards and Guidelines – Part 1SQL SERVER – Database Coding Standards and Guidelines – Part 2SQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – Database Coding Standards and Guidelines – Part 1

June 4, 2007 by pinaldave

SQL Server Database Coding Standards and Guidelines – Part 1

Naming

Tables: Rules: Pascal notation; end with an ‘s’

Examples: Products, Customers Group related table names1

Page 191: 9 Jan 01, 2007-431 Dec 31, 2007

Stored Procs: Rules: sp<App Name>_[<Group Name >_]<Action><table/logical instance>

Examples: spOrders_GetNewOrders, spProducts_UpdateProduct

Triggers: Rules: TR_<TableName>_<action>

Examples: TR_Orders_UpdateProducts Notes: The use of triggers is discouraged

Indexes: Rules: IX_<TableName>_<columns separated by _>

Examples: IX_Products_ProductID

Primary Keys: Rules: PK_<TableName>

Examples: PK_Products

Foreign Keys: Rules: FK_<TableName1>_<TableName2>

Example: FK_Products_Orderss

Defaults: Rules: DF_<TableName>_<ColumnName>

Example: DF_Products_Quantity

Columns: If a column references another table’s column, name it <table name>ID

Example: The Customers table has an ID column The Orders table should have a CustomerID column

General Rules:

Do not use spaces in the name of database objectso Do not use SQL keywords as the name of database objectso In cases where this is necessary, surround the

object name with brackets, such as [Year] Do not prefix stored procedures with ‘sp_’2

Prefix table names with the owner name3

Structure

Each table must have a primary keyo In most cases it should be an IDENTITY column named ID

Normalize data to third normal formo Do not compromise on performance to reach third normal form. Sometimes, a little de-

normalization results in better performance. Do not use TEXT as a data type; use the maximum allowed characters of VARCHAR instead In VARCHAR data columns, do not default to NULL; use an empty string instead Columns with default values should not allow NULLs As much as possible, create stored procedures on the same database as the main tables they will

be accessing

Formatting

Use upper case for all SQL keywordso SELECT, INSERT, UPDATE, WHERE, AND, OR, LIKE, etc.

Page 192: 9 Jan 01, 2007-431 Dec 31, 2007

Indent code to improve readability Comment code blocks that are not easily understandable

o Use single-line comment markers(–)o Reserve multi-line comments (/*.. ..*/) for blocking out sections of code

Use single quote characters to delimit strings.o Nest single quotes to express a single quote or apostrophe within a string

For example, SET @sExample = ‘SQL’’s Authority’ Use parentheses to increase readability

o WHERE (color=’red’ AND (size = 1 OR size = 2)) Use BEGIN..END blocks only when multiple statements are present within a conditional code

segment. Use one blank line to separate code sections. Use spaces so that expressions read like sentences.

o fillfactor = 25, not fillfactor=25 Format JOIN operations using indents

o Also, use ANSI Joins instead of old style joins4

Place SET statements before any executing code in the procedure.

Reference:1) Group related table names:

Products_USAProducts_IndiaProducts_Mexico

2) The prefix sp_ is reserved for system stored procedures that ship with SQL Server. Whenever SQL Server encounters a procedure name starting with sp_, it first tries to locate the procedure in the master database, then it looks for any qualifiers (database, owner) provided, then it tries dbo as the owner. Time spent locating the stored procedure can be saved by avoiding the “sp_” prefix.

3) This improves readability and avoids unnecessary confusion. Microsoft SQL Server Books Online states that qualifying table names with owner names helps in execution plan reuse, further boosting performance.

4)False code:SELECT *FROM Table1, Table2WHERE Table1.d = Table2.c

True code:SELECT *FROM Table1INNER JOIN Table2 ON Table1.d = Table2.c

Complete Series of Database Coding Standards and GuidelinesSQL SERVER Database Coding Standards and Guidelines – IntroductionSQL SERVER – Database Coding Standards and Guidelines – Part 1SQL SERVER – Database Coding Standards and Guidelines – Part 2SQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER Database Coding Standards and Guidelines – Introduction

June 3, 2007 by pinaldave

I have received many many request to do another series since my series SQL Server Interview Questions and Answers Complete List Download. I have created small series of Coding Standards and Guidelines, as this is the second most request I have received from readers. This document can be extremely long but I have limited to very few pages as it is difficult to follow thousands of the rules. My experience says it is more productive developer and better code if coding standard has important fewer rules than lots of micro rules.

Page 193: 9 Jan 01, 2007-431 Dec 31, 2007

Next two days I will be posting Database Coding Standards and Guidelines. This are the coding standards which I use in my company. There is extra addendum also, which I will be not posting here as that is specific to our company only. Please let me know if you think I have missed any important coding standard rules, I will accommodate them.

Please feel free to contact me if any of you want to write mini series with me.

Complete Series of Database Coding Standards and GuidelinesSQL SERVER Database Coding Standards and Guidelines – IntroductionSQL SERVER – Database Coding Standards and Guidelines – Part 1SQL SERVER – Database Coding Standards and Guidelines – Part 2SQL SERVER Database Coding Standards and Guidelines Complete List Download

SQL SERVER – 2005 Explanation and Example – SELF JOIN

June 3, 2007 by pinaldave

A self-join is simply a normal SQL join that joins one table to itself. This is accomplished by using table name aliases to give each instance of the table a separate name. Joining a table to itself can be useful when you want to compare values in a column to other values in the same column. A join in which records from a table are combined with other records from the same table when there are matching values in the joined fields. A self-join can be an inner join or an outer join. A table is joined to itself based upon a field or combination of fields that have duplicate data in different records. The data-type of the inter-related columns must be of the same type or needs to cast them in same type.

When all of the data you require is contained within a single table, but data needed to extract is related to each other in the table itself. Examples of this type of data relate to Employee information, where the table may have both an Employee’s ID number for each record and also a field that displays the ID number of an Employee’s supervisor or manager. To retrieve the data tables are required to relate/join to itself.

Another example which can be tried on SQL SERVER 2005 sample database AdventureWorks is to find products that are supplied by more than one vendor. Please refer the sample database for table structure.

USE AdventureWorks;GOSELECT DISTINCT pv1.ProductID, pv1.VendorIDFROM Purchasing.ProductVendor pv1INNER JOIN Purchasing.ProductVendor pv2ON pv1.ProductID = pv2.ProductIDAND pv1.VendorID = pv2.VendorIDORDER BY pv1.ProductID

SQL SERVER – 2005 – Microsoft SQL Server Management Pack for Microsoft Operations Manager 2005 – Download SQL Server MOM 2005

June 2, 2007 by pinaldave

The Microsoft SQL Server Management Pack provides both proactive and reactive monitoring of SQL Server 2005 and SQL Server 2000 in an enterprise environment. Availability and configuration monitoring, performance data collection, and default thresholds are built for enterprise-level monitoring. Both local and remote connectivity checks help ensure database availability. Features description are available online.

Download SQL Server MOM 2005

SQLAuthority News – Dedicated Search Engine for SQLAuthority – Search SQL Solutions

June 1, 2007 by pinaldave

Visit search.SQLAuthority.com

Page 194: 9 Jan 01, 2007-431 Dec 31, 2007

I have been receiving many questions asking for tutorials, suggestions or questions about topics I already have wrote before but readers are have not found it or having difficulty to find them. I have almost around 200 articles on this blog so far and it is growing. One of the team member in my company keep on asking about search engine specific to SQLAuthority.com. He suggest that he always search in this blog first before he search on web. One of the loyal reader suggests that I should have search facilities in my SQL Interview Questions.

I have created specific search engine which is dedicated to SQLAuthority.com. This will only search in SQLAuthority.com if results returned are not satisfactory, user can search online using Google just right there.

SQL SERVER – 2005 Constraint on VARCHAR(MAX) Field To Limit It Certain Length

June 1, 2007 by pinaldave

One of the Jr. DBA at in my Team Member asked me question the other day when he was replacing TEXT field with VARCHAR(MAX) : How can I limit the VARCHAR(MAX) field with maximum length of 12500 characters only. His Question was valid as our application was allowing 12500 characters.

Traditionally thinking we only create the field as long as we need. SQL Server 2005 does support VARCHAR(MAX) but does not support VARCHAR(12500). If we try to create database field with VARCHAR(12500) it gives following error.

Server: Msg 131, Level 15, State 3, Line 1The size (12500) given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000).

The solution we came up was to put constraint on the VARCHAR(MAX). SQL SERVER 2005 supports VARCHAR(MAX) and Constraint.

CREATE TABLE [dbo].[MyTestTable] ( [VarChar12500] VARCHAR(MAX) )GOALTER TABLE [dbo].[MyTestTable]ADD CONSTRAINT [MaxLengthConstraint]

Page 195: 9 Jan 01, 2007-431 Dec 31, 2007

CHECK (DATALENGTH([VarChar12500]) <= 12500)GO

SQL SERVER – Retrieve Information of SQL Server Agent Jobs

May 31, 2007 by pinaldave

sp_help_job returns information about jobs that are used by SQLServerAgent service to perform automated activities in SQL Server. When executed sp_help_job procedure with no parameters to return the information for all of the jobs currently defined in the msdb database.

EXEC MSDB.DBO.sp_HELP_JOB

SQL SERVER – 2005 Change Database Compatible Level – Backward Compatibility – Part 2 – Management Studio

May 31, 2007 by pinaldave

I have received quite a few request about post I have two days ago SQL SERVER – 2005 Change Database Compatible Level – Backward Compatibility, if this can be done using SQL Server Management Studio. It is very simple to do this using Management Studio as well but I still prefer T-SQL way.

Following steps will display the method to change the compatible levels.

Write click on database.Click on Properties.Click on Options.Change the Compatibility level to desired compatibility. (See Attached image below)Click OK.

SQL SERVER – Primary Key Must Not Contain NULL – Primary Key are NOT NULL

May 31, 2007 by pinaldave

While reviewing the search engine log for this blog I found lots of search regarding Nullable Primary Key. It is not possible. This post is especially to clear the Not Nullable Primary Key Property. The Allow Nulls

Page 196: 9 Jan 01, 2007-431 Dec 31, 2007

property can’t be set on a column that is part of the primary key. All columns that are part of a table’s a primary key must contain aggregate unique values other than NULL.

SQLAuthority.com News – Best SQL Job Search – Best SQL Job List – Find SQL Jobs

May 30, 2007 by pinaldave

SQLAuthority.com News – Best SQL Job Search – Best SQL Job List – Find SQL Jobs

Visit : http://jobs.SQLAuthority.com

I have been receiving two kind of requests almost every day.

1) Recruiters and Employers asking where can they find good candidates who are truly dedicated to SQL Server?2) Job seeker asking where can they find only SQL related jobs?

There are hundreds of web site which have great resources for all kind of jobs. Monster and Dice are examples of them.Many sites are bit ocean of the jobs and it is hard to find only SQL Jobs from there, many job listing requires few other skills as primary skills. Recruiters have difficult time to get hold of right candidate as job seekers are skilled with variety of technologies. It is really good to find job which requires more than SQL or find candidate who knows more than SQL. The question I always had is what if someone just want ONLY SQL job or candidate truly dedicated to ONLY SQL.

http://jobs.SQLAuthority.com is humble attempt to facilitate philosophy of ONLY SQL. Though, few jobs will be still required various skills besides SQL, SQL will the primary requirement. I wish this will help everybody who visits SQLAuthority.com and looking for right job or right candidate.

Disclaimer:SQLAuthority.com uses third party tool to generate this job listing and not liable for any action taken by user. Employee and Job Seeker are responsible for all the action and decision taken by them. Please do not contact SQLAuthority.com for any help or support. Help is available on site jobs.sqlauthority.com on top right corner.

SQL SERVER – Trace Flags – DBCC TRACEON

May 30, 2007 by pinaldave

Trace flags are valuable tools as they allow DBA to enable or disable a database function temporarily. Once a trace flag is turned on, it remains on until either manually turned off or SQL Server restarted. Only users in the sysadmin fixed server role can turn on trace flags.

If you want to enable/disable Detailed Deadlock Information (1205), use Query Analyzer and DBCC TRACEON to turn it on.1205 trace flag sends detailed information about the deadlock to the error log.

Enable Trace at current connection level:DBCC TRACEON(1205)

Disable Trace:DBCC TRACEOFF(1205)

Enable Multiple Trace at same time separating each trace with a comma.DBCC TRACEON(1205,2528)

Disable Multiple Trace at same time separating each trace with a comma.DBCC TRACEOFF(1205,2528)

Page 197: 9 Jan 01, 2007-431 Dec 31, 2007

To set the trace using the DBCC TRACEON command at a server level, Pass second argument to the function as -1.DBCC TRACEON (1205, -1)

To enumerate a complete list of traces that are on run following command in query analyzer.DBCC TRACESTATUS(-1)

SQL Server 2005 Trace Flags.

SQL Server 2000 SP3 Trace Flags. (Undocumented trace flags are not included in document)

SQL SERVER – Fix : Error : Server: Msg 544, Level 16, State 1, Line 1 Cannot insert explicit value for identity column in table

May 30, 2007 by pinaldave

Error Message:

Server: Msg 544, Level 16, State 1, Line 1 Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF.

This error message appears when you try to insert a value into a column for which the IDENTITY property was declared, but without having set the IDENTITY_INSERT setting for the table to ON.

Fix/WorkAround/Solution:

/* Turn Identity Insert ON so records can be inserted in the Identity Column  */SET IDENTITY_INSERT [dbo].[TableName] ONGOINSERT INTO [dbo].[TableName] ( [ID], [Name] )VALUES ( 2, 'InsertName')GO/* Turn Identity Insert OFF  */SET IDENTITY_INSERT [dbo].[TableName] OFFGO

Setting the IDENTITY_INSERT to ON allows explicit values to be inserted into the identity column of a table. Execute permissions for the SET IDENTITY_INSERT default to the sysadmin fixed server role and the db_owner and db_ddladmin fixed database roles, and the object owner.

SQL SERVER – 2005 Change Database Compatible Level – Backward Compatibility

May 29, 2007 by pinaldave

sp_dbcmptlevelSets certain database behaviors to be compatible with the specified version of SQL Server.

Example:----SQL Server 2005 database compatible level to SQL Server 2000EXEC sp_dbcmptlevel AdventureWorks, 80;GO----SQL Server 2000 database compatible level to SQL Server 2005EXEC sp_dbcmptlevel AdventureWorks, 90;GO

Version of SQL Server database can be one of the following:

60 = SQL Server 6.0 65 = SQL Server 6.5 70 = SQL Server 7.0 80 = SQL Server 2000

Page 198: 9 Jan 01, 2007-431 Dec 31, 2007

90 = SQL Server 2005

The sp_dbcmptlevel stored procedure affects behaviors only for the specified database, not for the entire server. sp_dbcmptlevel provides only partial backward compatibility with earlier versions of SQL Server. A database containing an indexed view cannot be changed to a compatibility level lower than 80.

The best practice to change the compatibility level of database is in following three steps.

Set the database to single user access mode by usingALTER DATABASE SET SINGLE_USER

Change the compatibility level of the database. Put the database in multiuser access mode by using

ALTER DATABASE SET MULTI_USER

SQL SERVER – User Defined Functions (UDF) Limitations

May 29, 2007 by pinaldave

UDF have its own advantage and usage but in this article we will see the limitation of UDF. Things UDF can not do and why Stored Procedure are considered as more flexible then UDFs. Stored Procedure are more flexibility then User Defined Functions(UDF).

UDF has No Access to Structural and Permanent Tables.o UDF can call Extended Stored Procedure, which can have access to structural and

permanent tables. (No Access to Stored Procedure) UDF Accepts Lesser Numbers of Input Parameters.

o UDF can have upto 1023 input parameters, Stored Procedure can have upto 21000 input parameters.

UDF Prohibit Usage of Non-Deterministic Built-in Functionso Functions GETDATE() etc can not be used UDFs, but can be used in Stored Procedure

UDF Returns Only One Result Set or Output Parametero Due to this it can be used in SELECT statement but can not return multiple result set like

Stored Procedure UDF can not Call Stored Procedure

o Only access to Extended Stored Procedure. UDF can not Execute Dynamic SQL or Temporary Tables

o UDF can not run dynamic SQL which are dynamically build in UDF. Temporary Tables can not be used in UDF as well.

UDF can not Return XMLo FOR XML is not allowed in UDF

UDF does not support SET optionso SET options which can change Server level or transaction level settings are prohibited in

UDFs. (SET ROWCOUNT etc) UDF does not Support Error Handling

o RAISEERROR or @@ERROR are not allowed in UDFs.

As I said earlier this article is written to show Limitations of UDF. I use UDF for many reasons, the main reason I use it I can do repetitive task in SELECT statement as well as modularizing my frequently used code.

Reference : Pinal Dave (http://blog.SQLAuthority.com) , BOL and few other articles (Reference Missing)

SQLAuthority News – Author Visit – Meeting with Readers – Top Three Features of SQL SERVER 2005

May 28, 2007 by pinaldave

Page 199: 9 Jan 01, 2007-431 Dec 31, 2007

Lots of travelers are visiting to Las Vegas due to long weekend of Memorial Day. I was invited to dinner meeting by two of my readers. It was wonderful discussion with them. We primarily discussed about scalability and upgrading issues about SQL Server. I received feedback about SQLAuthority.com site. There were two primarily request for them. I have been working on both of them already as I have received quite a few request for them from other readers as well. Beta testing has been completed, I will announce them on 1st June.

While enjoying dinner I was asked interesting question and I would like to share it with all other readers.

Microsoft has published article about Top 30 Features of SQL Server 2005 in Nov 2005. If I have to pick TOP 3 features of them which I will pick and why? Now, all of those 30 features are important and I have to pick only 3. I answered top 3 from my memory. The comparable feature from original article are here.

SQL Server Management Studio

Most used feature of SQL Server, which has way more features than previous versions of Query Analyzer and SQL Management Studio combined.

Why?

Developers are most important factor in any programming language. This is the prominent and upgraded tool for Developers.

Security Enhancements

The security model in SQL Server 2005 separate users from objects, provides fine-grain access, and enables greater control of data access

Why?

Important of Security is self explaining.

Online Indexing Operations

While a clustered index is being rebuilt, you can continue to make updates to the underlying data and perform queries against the data.

Why?

In larger database, as time passes system keeps on getting slower. To improve the system performance Index operations are important. In larger database, SQL Server 2000 used to lock the files/tables when rebuilding the database and it was creating timeouts as well as deadlocks. In SQL Server 2005 this features resolves the issue. Improved performance with database operation un-interrupted is quite remarkable.

SQL SERVER – Download Feature Pack for Microsoft SQL Server 2005

May 27, 2007 by pinaldave

Feature Pack for Microsoft SQL Server 2005 – February 2007Download the February 2007 Feature Pack for Microsoft SQL Server 2005, a collection of standalone install packages that provide additional value for SQL Server 2005. I have listed all the stand alone packages here. Even though title says February 2007, publication day of this package is 5/25/2007. All DBA should go through following list and see if their organization is using any of the application/feature and update is required for them.

Microsoft ADOMD.NET Microsoft Core XML Services (MSXML) 6.0 Microsoft OLEDB Provider for DB2 Microsoft SQL Server Management Pack for MOM 2005

Page 200: 9 Jan 01, 2007-431 Dec 31, 2007

Microsoft SQL Server 2000 PivotTable Services Microsoft SQL Server 2000 DTS Designer Components Microsoft SQL Server Native Client Microsoft SQL Server 2005 Analysis Services 9.0 OLE DB Provider Microsoft SQL Server 2005 Backward Compatibility Components Microsoft SQL Server 2005 Command Line Query Utility Microsoft SQL Server 2005 Datamining Viewer Controls Microsoft SQL Server 2005 JDBC Driver Microsoft SQL Server 2005 Management Objects Collection Microsoft SQL Server 2005 Compact Edition Microsoft SQL Server 2005 Notification Services Client Components Microsoft SQL Server 2005 Upgrade Advisor Microsoft .NET Data Provider for mySAP Business Suite, Preview Version Reporting Add-In for Microsoft Visual Web Developer 2005 Express Microsoft Exception Message Box Data Mining Managed Plug-in Algorithm API for SQL Server 2005 Microsoft SQL Server 2005 Reporting Services Add-in for Microsoft SharePoint Technologies Microsoft SQL Server 2005 Data Mining Add-ins for Microsoft Office 2007 SQL Server 2005 Performance Dashboard Reports SQL Server 2005 Best Practices Analyzer

Download Feature Pack for Microsoft SQL Server 2005

SQL SERVER – 2005 Limiting Result Sets by Using TABLESAMPLE – Examples

May 27, 2007 by pinaldave

Introduced in SQL Server 2005, TABLESAMPLE allows you to extract a sampling of rows from a table in the FROM clause. The rows retrieved are random and they are are not in any order. This sampling can be based on a percentage of number of rows. You can use TABLESAMPLE when only a sampling of rows is necessary for the application instead of a full result set.

Example 1:SELECT FirstName,LastNameFROM Person.ContactTABLESAMPLE SYSTEM (10 PERCENT)Example 2:SELECT FirstName,LastNameFROM Person.ContactTABLESAMPLE SYSTEM (1000 ROWS)

If you run above script many times you will notice that different numbers of rows are returned everytime. Without any data changing, re-running the identical query keeps giving different results. This is non -deterministic factor of TABLESAMEPLE clause. If table is static and rows are not changed what could be the reason to return different numbers of the rows to return in each execution. The factor is 10 PERCENT is not the percentages of the table rows or tables records, it is percentages of the table’s data pages. Once the sample pages of data selected, all the rows from the selected pages are returned, it will not limit the number of rows sampled from that page. Fill factor of all the pages varies depends on the data of the table. This makes script to return different row count in result set everytime it is executed. The REPEATABLE option causes a selected sample to be returned again. When REPEATABLE is specified with the same repeat_seed value, SQL Server returns the same subset of rows, as long as no changes have been made to the table. When REPEATABLE is specified with a different repeat_seed value, SQL Server will typically return a different sample of the rows in the table. .

Following example is from BOL:The following example returns the same set of rows every time that it is executed. The seed value of 205 was chosen arbitrarily.

USE AdventureWorksGOSELECT FirstName, LastNameFROM Person.Contact

Page 201: 9 Jan 01, 2007-431 Dec 31, 2007

TABLESAMPLE (10 PERCENT)REPEATABLE (205) ;

SQL SERVER – 2005 Replace TEXT with VARCHAR(MAX) – Stop using TEXT, NTEXT, IMAGE Data Types

May 26, 2007 by pinaldave

Yesterday, in Friday Afternoon team meeting. I was asked question by one of application developer

“I am asked in new coding standards to use VARHCAR(MAX) instead of TEXT. Is VARCHAR(MAX) big enough to store TEXT field?”

Well, I realize that I was not clear enough in my coding standard. It is extremely important for coding standards to be clear and have a enough explanation that developer have no doubt about them. I updated coding standards after the meeting. The answer is

“Yes, VARCHAR(MAX) is big enough to accommodate TEXT field. TEXT, NTEXT and IMAGE data types of SQL Server 2000 will be deprecated in future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommanded to use new data types which are VARHCAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX).”

There are more reasons to use VARHCAR(MAX) though this was verbal answer to technical question in our general meeting where the focus was “Web Application Architecture and SQL Server”.

SQL SERVER – 2005 Find Table without Clustered Index – Find Table with no Primary Key

May 26, 2007 by pinaldave

One of the basic Database Rule I have is that all the table must Clustered Index. Clustered Index speeds up performance of the query ran on that table. Clustered Index are usually Primary Key but not necessarily. I frequently run following query to verify that all the Jr. DBAs are creating all the tables with Clustered Index.

USE AdventureWorks ----Replace AdventureWorks with your DBNameGOSELECT DISTINCT [TABLE] = OBJECT_NAME(OBJECT_ID)FROM SYS.INDEXESWHERE INDEX_ID = 0AND OBJECTPROPERTY(OBJECT_ID,'IsUserTable') = 1ORDER BY [TABLE]GO

Result set for AdventureWorks:TABLE——————————————————-DatabaseLogProductProductPhoto(2 row(s) affected)

Related Post:SQL SERVER – 2005 – Find Tables With Primary Key Constraint in DatabaseSQL SERVER – 2005 – Find Tables With Foreign Key Constraint in Database

SQL SERVER – Change Default Fill Factor For Index

May 25, 2007 by pinaldave

SQL Server has default value for fill factor is Zero (0). The fill factor is implemented only when the index is created; it is not maintained after the index is created as data is added, deleted, or updated in the table. When creating an index, you can specify a fill factor to leave extra gaps and reserve a percentage of free space on each leaf level page of the index to accommodate future expansion in the storage of the table’s data and reduce the potential for page splits.

Page 202: 9 Jan 01, 2007-431 Dec 31, 2007

I like my fill factor to 90 (Why? I like it!) I use sp_configure to change the default fill factor for the SQL Server.sp_configure 'show advanced options', 1GORECONFIGUREGOsp_configure 'fill factor', 90GORECONFIGUREGO

SQL SERVER – Stored Procedure to display code (text) of Stored Procedure, Trigger, View or Object

May 25, 2007 by pinaldave

This is another popular question I receive. How to see text/content/code of Stored Procedure. System stored procedure that prints the text of a rule, a default, or an unencrypted stored procedure, user-defined function, trigger, or view.

Syntaxsp_helptext @objname = 'name'

sp_helptext [ @objname = ] 'name' [ , [ @columnname = ] computed_column_name Displaying the definition of a trigger or stored proceduresp_helptext 'dbo.nameofsp'

SQL SERVER – Disadvantages (Problems) of Triggers

May 24, 2007 by pinaldave

One of my team member asked me should I use triggers or stored procedure. Both of them has its usage and needs. I just basically told him few issues with triggers. This is small note about our discussion.

Disadvantages(Problems) of Triggers

It is easy to view table relationships , constraints, indexes, stored procedure in database but triggers are difficult to view.

Triggers execute invisible to client-application application. They are not visible or can be traced in debugging code.

It is hard to follow their logic as it they can be fired before or after the database insert/update happens.

It is easy to forget about triggers and if there is no documentation it will be difficult to figure out for new developers for their existence.

Triggers run every time when the database fields are updated and it is overhead on system. It makes system run slower.

I do not use triggers. In my whole career I am able to get my work done using Stored Procedures instead of Triggers. (Implementation and Architecture changes are required if either of is to be used to support business logic).

SQL SERVER – 2005 Retrieve Configuration of Server

May 24, 2007 by pinaldave

Few days ago I was asked what is our SQL Server’s configuration. I provided way more information then they requested.

Run following script and it will provide all the information about SQL Server . SQL Server provides in detailed information if Advanced Options are turned on. It is very clear from this that maximum number of object SQL Server can have is 2,147,483,647. It is considerably very big number. I am not worried yet

Page 203: 9 Jan 01, 2007-431 Dec 31, 2007

about my database reaching its limit.EXEC sp_configure 'show advanced options', 1GORECONFIGUREGOEXEC sp_configureGOEXEC sp_configure 'show advanced options', 0GOTo change any configuration run following script using values from the NAME column of following result set. e.g. To change Resource Timeout run following script.sp_configure 'show advanced options', 1GORECONFIGUREGOsp_configure 'resource timeout', 100GORECONFIGUREGOResults Set:Configuration option ’show advanced options’ changed from 0 to 1. Run the RECONFIGURE statement to install.name minimum maximum config_value run_value———————————– ———– ———– ———— ———–Ad Hoc Distributed Queries 0 1 0 0affinity I/O mask -2147483648 2147483647 0 0affinity mask -2147483648 2147483647 0 0Agent XPs 0 1 1 1allow updates 0 1 0 0awe enabled 0 1 0 0blocked process threshold 0 86400 0 0c2 audit mode 0 1 0 0clr enabled 0 1 0 0common criteria compliance enabled 0 1 0 0cost threshold for parallelism 0 32767 5 5cross db ownership chaining 0 1 0 0cursor threshold -1 2147483647 -1 -1Database Mail XPs 0 1 0 0default full-text language 0 2147483647 1033 1033default language 0 9999 0 0default trace enabled 0 1 1 1disallow results from triggers 0 1 0 0fill factor (%) 0 100 0 0ft crawl bandwidth (max) 0 32767 100 100ft crawl bandwidth (min) 0 32767 0 0ft notify bandwidth (max) 0 32767 100 100ft notify bandwidth (min) 0 32767 0 0index create memory (KB) 704 2147483647 0 0in-doubt xact resolution 0 2 0 0lightweight pooling 0 1 0 0locks 5000 2147483647 0 0max degree of parallelism 0 64 0 0max full-text crawl range 0 256 4 4max server memory (MB) 16 2147483647 2147483647 2147483647max text repl size (B) 0 2147483647 65536 65536max worker threads 128 32767 0 0media retention 0 365 0 0min memory per query (KB) 512 2147483647 1024 1024min server memory (MB) 0 2147483647 0 0nested triggers 0 1 1 1network packet size (B) 512 32767 4096 4096Ole Automation Procedures 0 1 0 0open objects 0 2147483647 0 0PH timeout (s) 1 3600 60 60precompute rank 0 1 0 0priority boost 0 1 0 0query governor cost limit 0 2147483647 0 0query wait (s) -1 2147483647 -1 -1recovery interval (min) 0 32767 0 0

Page 204: 9 Jan 01, 2007-431 Dec 31, 2007

remote access 0 1 1 1remote admin connections 0 1 0 0remote login timeout (s) 0 2147483647 20 20remote proc trans 0 1 0 0remote query timeout (s) 0 2147483647 600 600Replication XPs 0 1 0 0scan for startup procs 0 1 0 0server trigger recursion 0 1 1 1set working set size 0 1 0 0show advanced options 0 1 1 1SMO and DMO XPs 0 1 1 1SQL Mail XPs 0 1 0 0transform noise words 0 1 0 0two digit year cutoff 1753 9999 2049 2049user connections 0 32767 0 0user options 0 32767 0 0Web Assistant Procedures 0 1 0 0xp_cmdshell 0 1 1 1

Configuration option ’show advanced options’ changed from 1 to 0. Run the RECONFIGURE statement to install.

SQL SERVER – 2005 NorthWind Database or AdventureWorks Database – Samples Databases

May 23, 2007 by pinaldave

SQL Server 2005 does not install sample databases by default due to security reasons.I have received many questions regarding where is sample database in SQL Server 2005. One can install it afterwards. AdventureWorks and AdvetureWorksDS are the new sample databases for SQL Server 2005, they can be download from here.

After installing sample databases the second most asked question is WHERE IS NORTHWIND?

Northwind database was the best sample database for SQL Server 2000. Since I started to work with AdventureWorks of SQL Server 2005, I like AdventureWorks as much as Northwind. Northwind is not the best database due to few new features of analysis and reporting service of SQL Server 2005. MSDN Book On Line (BOL) uses the AdventureWorks in all of their example and it makes it easy to follow up if proper understanding of AdventureWorks schema is developed. However, SQL Server Compact Edition uses Northwind as sample database.

If you still want to download and install Northwind and Pubs in SQL Server 2005, download them from here.

My recommendation : Start getting familiar with AdventureWorks.UPDATE: SQL SERVER – 2005 NorthWind Database or AdventureWorks Database – Samples Databases – Part 2 explains how to restored NorthWind to SQL Server 2000 using images.

SQL SERVER – 2005 Explanation Left Semi Join Showplan Operator and Other Operator

May 23, 2007 by pinaldave

I come across very interesting documentation about Joins, while I was researching about article about EXCEPT yesterday. There are few interesting kind of join operations exists when execution plan is displayed in text format.

Left Semi Join Showplan Operator The Left Semi Join operator returns each row from the first (top) input when there is a matching row in the second (bottom) input. If no join predicate exists in the Argument column, each row is a matching row.

Left Anti Semi Join Showplan Operator The Left Anti Semi Join operator returns each row from the first (top) input when there is no matching row in the second (bottom) input. If no join predicate exists in the Argument column, each row is a matching row.

Page 205: 9 Jan 01, 2007-431 Dec 31, 2007

Right Anti Semi Join Showplan Operator The Right Anti Semi Join operator outputs each row from the second (bottom) input when a matching row in the first (top) input does not exist. A matching row is defined as a row that satisfies the predicate in the Argument column (if no predicate exists, each row is a matching row).

Right Semi Join Showplan Operator The Right Semi Join operator returns each row from the second (bottom) input when there is a matching row in the first (top) input. If no join predicate exists in the Argument column, each row is a matching row.

Following script will display Left Anti Semi Join Showplan Operator in the result pan.USE AdventureWorks;GOSET SHOWPLAN_TEXT ONGOSELECT ProductIDFROM Production.ProductWHERE ProductIDNOT IN (SELECT ProductIDFROM Production.WorkOrder);GOSET SHOWPLAN_TEXT OFFGO

Result Set:|–Nested Loops(Left Anti Semi Join, OUTER REFERENCES:([AdventureWorks].[Production].[Product].[ProductID], [Expr1006]) WITH UNORDERED PREFETCH)|–Index Scan(OBJECT:([AdventureWorks].[Production].[Product].[AK_Product_rowguid]))|–Top(TOP EXPRESSION:((1)))|–Index Seek(OBJECT:([AdventureWorks].[Production].[WorkOrder].[IX_WorkOrder_ProductID]), SEEK:([AdventureWorks].[Production].[WorkOrder].[ProductID]=[AdventureWorks].[Production].[Product].[ProductID]) ORDERED FORWARD)

SQLAuthority News – New Scoble Plugin of WordPress

May 23, 2007 by pinaldave

Just a day ago, I was explaining one of my friend who is interested in writing blog about interesting places he visits. I explained him few things and let him figured other remaining. He called me after few min and asked that he can not find Scoble Plugin of WordPress and once found how to integrate it. It was hilarious so I asked him, where did he heard about that plugin and where was he for last few years. I told him Scoble Plugin is around for many years and easily available with Mozilla (joke again). Well, finally I explained him how to integrate Scoble Plugin by going to http://scobleizer.com/.

I usually get this question, how do I keep pace with what is going on. I used to read many blogs but recently I have stopped reading those hundreds of blog. I just read Robert’s Link Blog or Shared Items. Link blog contains few selected blogs and posts. I unsubscribe to any blog from my reader if I see any post of that Link Blog. He reads hundreds of them so I do not have to read them. I just read those few which have interesting information. One man spends time and others save their time. Sounds like good deal.

Summary: More time for me to spend on SQL.

SQL SERVER – 2005 Comparison EXCEPT operator vs. NOT IN

May 22, 2007 by pinaldave

The EXCEPT operator returns all of the distinct rows from the query to the left of the EXCEPT operator when there is no matching rows in the right query. The EXCEPT operator is equivalent of the Left Anti Semi Join. EXCEPT operator works the same way NOT IN. EXCEPTS returns any distinct values from the query to the left of the EXCEPT operand that are not also returned from the right query.

Example of EXCEPT operator is displayed along Example of NOT IN. If you run both of the Query and compare the Execution plan it is exactly same. EXCEPT and NOT IN does same functions and have same execution plan but EXCEPT has much simpler syntax. The row-by-row comparison provided by EXCEPT,

Page 206: 9 Jan 01, 2007-431 Dec 31, 2007

combined with the number of rows being returned remaining consistent, provides compelling evidence that re-factored query is correct. EXCEPT works with * as well as alias.

Example: (Both of the scripts returns same number of rows)----SQL SERVER 2005 MethodUSE AdventureWorks;GOSELECT ProductIDFROM Production.ProductEXCEPTSELECT ProductIDFROM Production.WorkOrder ;GO

----SQL SERVER 2000 Method which works&nbspIN SQL SERVER 2005USE AdventureWorks;GOSELECT ProductIDFROM Production.ProductWHERE ProductIDNOT IN (SELECT ProductIDFROM Production.WorkOrder);GO

Following the execution plan which indicates EXCEPT and NOT IN uses same execution plan. Click on below image to see larger image.

SQL SERVER – Top 15 free SQL Injection Scanners – Link to Security Hacks

May 21, 2007 by pinaldave

SQL injection is a technique for exploiting web applications that use client supplied data in SQL queries, but without first stripping potentially harmful characters. Checking for SQL Injection vulnerabilities involves auditing your web applications and the best way to do it is by using automated SQL Injection Scanners. Security-Hacks.com compiled a list of free SQL Injection Scanners. I really enjoy reading the article.

Read Security Hacks Article

Send me email if above link is not working.

Page 207: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – 2005 Build List Link

May 21, 2007 by pinaldave

What is Build List?All SQL Server has build list, this is incremental list of numbers which indicates which version SQL Server is running and what are its compatibility, patches etc.

Regular Columnist Steve Jones of SQL Server Central has created build list. It is updated and informative.

Microsoft Hot fixes are always cumulative. You can find your build number with:SELECT@@Version

SQL SERVER – SQL Code Formatter Tools

May 20, 2007 by pinaldave

SQL Code Formatting is very important. Every SQL Server DBA has its own preference about formatting. I like to format all keywords to uppercase. Following are two online tools, which formats SQL Code very good. I tested following script with those tools.

use tempdbgocreate procedure SP_NonFatal_INSERT @Column2 int =NULLAS declare @ErrorMsgID int insert NonFatalvalues (@Column2) set @ErrorMsgID =@@ERRORif @ErrorMsgID 0 BEGINRAISerror (‘An error occured updating the NonFatal table’,10,1) endGO

Tool 1 : Instant SQL FormatterUSE TEMPDBGO

CREATE PROCEDURE sp_NONFATAL_INSERT@Column2 INT = NULLASDECLARE @ErrorMsgID INTINSERT NONFATALVALUES(@Column2)SET @ErrorMsgID =@@ ERRORIF @ErrorMsgID 0BEGINRAISERROR (‘An error occured updating the NonFatal table’,10,1)END

Tool 2 : SQLinFormUSE tempdb GOCREATE PROCEDUREsp_NonFatal_INSERT @Column2 INT =NULLASDECLARE@ErrorMsgID INTINSERT NonFatal VALUES (@Column2) SET @ErrorMsgID =@@ERRORIF @ErrorMsgID 0BEGINRAISERROR ('An error occured updating the NonFatal table',10,1)END

SQL SERVER – Script/Function to Find Last Day of Month

May 20, 2007 by pinaldave

Page 208: 9 Jan 01, 2007-431 Dec 31, 2007

Following query will find the last day of the month. Query also take care of Leap Year.

Script:

DECLARE @date DATETIMESET @date='2008-02-03'SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)), DATEADD(m,1,@date))AS LastDayOfMonthGODECLARE @date DATETIMESET @date='2007-02-03'SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)), DATEADD(m,1,@date))AS LastDayOfMonthGOResultSet:LastDayOfMonth-----------------------2008-02-29 00:00:00.000

(1 row(s) affected)

LastDayOfMonth-----------------------2007-02-28 00:00:00.000

(1 row(s) affected)

SQL SERVER – ASCII to Decimal and Decimal to ASCII

May 19, 2007 by pinaldave

ASCII – Returns the ASCII code value of the leftmost character of a character expression.

CHAR – Fixed-length non-Unicode character data with length of n bytes.

Examples:----Decimal to ASCIISELECT CHAR(80)+CHAR(73)+CHAR(78)+CHAR(65)+CHAR(76) AS SQLAuthorityAuthorGO

----ASCII to DecimalSELECT ASCII('P') AS SQLAuthorityAuthorUNION ALLSELECT ASCII('I')UNION ALLSELECT ASCII('N')UNION ALLSELECT ASCII('A')UNION ALLSELECT ASCII('L')GO

Refer the ASCII-Decimal Table here.

SQL SERVER – Math Functions for 2005

May 19, 2007 by pinaldave

The large majority of math functions are specific to applications using trigonometry, calculus, and geometry. This are very important and it is very difficult to have all of them together at place.

Math FunctionsAbsolute value ABSArc cosine ACOS

Page 209: 9 Jan 01, 2007-431 Dec 31, 2007

Arc sine ASINArc tangent of n ATANArc tangent of n and m ATN2Smallest integer >= value CEILINGCosine COSHyperbolic cosine COTExponential value EXPRound down to nearest integer FLOORNatural logarithm LOGLogarithm, base 10 LOG10Modulus (remainder) USE MODULO (%) OPERATORPower POWERRandom number RANDRound ROUNDSign of number SIGNSine SINSquare root SQRTTangent TANConvert number if NULL ISNULLStandard deviation STDEVVariance VAR

SQL SERVER – 2005 Understanding Trigger Recursion and Nesting with examples

May 18, 2007 by pinaldave

Trigger events can be fired within another trigger action. One Trigger execution can trigger even on another table or same table. This trigger is called NESTED TRIGGER or RECURSIVE TRIGGER. Nested triggers SQL Server supports the nesting of triggers up to a maximum of 32 levels. Nesting means that when a trigger is fired, it will also cause another trigger to be fired. If a trigger creates an infinitive loop, the nesting level of 32 will be exceeded and the trigger will cancel with an error message. Recursive triggers When a trigger fires and performs a statement that will cause the same trigger to fire, recursion will occur.

Disable Nesting/Recursing TriggersFollowing script will stop executing all the nested triggers.sp_CONFIGURE 'nested_triggers',0GORECONFIGUREGO

There is also alternate way to stop Trigger Recursion

ALTER DATABASE databasenameSET RECURSIVE_TRIGGERS ON | OFF

Restrict Trigger Nesting to certain levelPut following script in trigger code. This will stop the trigger recursion after certain levels. In following case it will stop after 5 recursion.IF ((SELECT TRIGGER_NESTLEVEL()) > 5 )RETURN

SQL SERVER – 2005 – SSMS Change T-SQL Batch Separator

May 18, 2007 by pinaldave

I recently received one big file with many T-SQL batches. It was very big file and I was asked that this file was tested many times and it can run one transaction. I noticed the separator of the batches is not GO but it was EndBatch. I have following two options to run the whole batch in one transation.

1) Mass replace EndBatch with GO.Only problem I had with is that if EndBatch word was used in other place then batch separator it will

Page 210: 9 Jan 01, 2007-431 Dec 31, 2007

replace there too. I searched and noticed that it was used in name of the Stored Procedure. I finally came up with second method which worked fine.

2) Change the batch separator.Go to Tools >> Options >> Change the Batch Separator to EndBatch from GO.

SQL SERVER – Disable Index – Enable Index – ALTER Index

May 17, 2007 by pinaldave

There are few requirements in real world when Index on table needs to be disabled and re-enabled afterwards. e.g. DTS, BCP, BULK INSERT etc. Index can be dropped and recreated. I prefer to disable the Index if I am going to re-enable it again.

USE AdventureWorksGO----Diable IndexALTER INDEX [IX_StoreContact_ContactTypeID] ON Sales.StoreContact DISABLEGO----Enable IndexALTER INDEX [IX_StoreContact_ContactTypeID] ON Sales.StoreContact REBUILDGO

SQL SERVER – Fix : Error 1205 : Transaction (Process ID) was deadlocked on resources with another process and has been chosen as the deadlock victim. Rerun the transaction

May 16, 2007 by pinaldave

Fix : Error 1205 : Transaction (Process ID) was deadlocked on resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Deadlock occurs when two users have locks on separate objects and each user wants a lock on the other’s object. When this happens, SQL Server ends the deadlock by automatically choosing one and aborting the process, allowing the other process to continue. The aborted transaction is rolled back and an error message is sent to the user of the aborted process. Generally, the transaction that requires the least amount of overhead to rollback is the transaction that is aborted.

Fix/Workaround/Solution:Deadlock priority can be set by user. In other words, user can choose which process should stop to allow other process to continue. SQL Server automatically chooses the process to terminate which is running

Page 211: 9 Jan 01, 2007-431 Dec 31, 2007

completes the circular chain of locks. Sometime, it chooses the process which is running the for shorter period then other process.

To reduce the chance of a deadlock:

Minimize the size of transaction and transaction times. Always access server objects in the same order each time in application. Avoid cursors, while loops, or process which requires user input while it is running. Reduce lock time in application. Use query hints to prevent locking if possible (NoLock, RowLock) Select deadlock victim by using SET DEADLOCK_PRIORITY.

SQL SERVER 2005 has new priority HIGH as well as numeric-priority.

SQL SERVER 2005 SyntaxSET DEADLOCK_PRIORITY { LOW | NORMAL | HIGH | <numeric-priority> | @deadlock_var | @deadlock_intvar }<numeric-priority> ::= { -10 | -9 | -8 | … | 0 | … | 8 | 9 | 10 }Example:The following example sets the deadlock priority to NORMAL.SET DEADLOCK_PRIORITY NORMAL;GO

SQL SERVER – Fix: Error 130: Cannot perform an aggregate function on an expression containing an aggregate or a subquery

May 16, 2007 by pinaldave

Fix: Error 130: Cannot perform an aggregate function on an expression containing an aggregate or a subquery

Following statement will give the following error: “Cannot perform an aggregate function on an expression containing an aggregate or a subquery.” MS SQL Server doesn’t support it.USE PUBSGOSELECT AVG(COUNT(royalty)) RoyaltyAvgFROM dbo.royschedGO

You can get around this problem by breaking out the computation of the average in derived tables.USE PUBSGOSELECT AVG(t.RoyaltyCounts)FROM(SELECT COUNT(royalty) AS RoyaltyCountsFROM dbo.roysched) TGO

SQL SERVER – Binary Sequence Generator – Truth Table Generator

May 15, 2007 by pinaldave

Run following script in query editor to generate truth table with its decimal value and binary sequence. The truth table is 512 rows long. This can be extended or reduced by adding or removing cross joins respectively.

Script:USE AdventureWorks;DECLARE @Binary TABLE ( Digit bit)INSERT @Binary

Page 212: 9 Jan 01, 2007-431 Dec 31, 2007

VALUES (0)INSERT @BinaryVALUES (1)SELECT ((a.Digit*256) + (b.Digit*128) + (c.Digit*64) +(d.Digit*32) + (e.Digit*16) + (f.Digit*8) +(g.Digit*4) + (h.Digit*2) + (i.Digit*1)) DecimalValue,a.Digit '256', b.Digit '128' , c.Digit '64',d.Digit '32', e.Digit '16', f.Digit '8',g.Digit '4', h.Digit '2', i.Digit '1'FROM @Binary aCROSS JOIN @Binary bCROSS JOIN @Binary cCROSS JOIN @Binary dCROSS JOIN @Binary eCROSS JOIN @Binary fCROSS JOIN @Binary gCROSS JOIN @Binary hCROSS JOIN @Binary iORDER BY ((a.Digit*256) + (b.Digit*128) + (c.Digit*64) +(d.Digit*32) + (e.Digit*16) + (f.Digit*8) +(g.Digit*4) + (h.Digit*2) + (i.Digit*1))GO

Resultset:DecimalValue 256 128 64 32 16 8 4 2 1———— —– —– —– —– —– —– —– —– —–0 0 0 0 0 0 0 0 0 01 0 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 1 03 0 0 0 0 0 0 0 1 14 0 0 0 0 0 0 1 0 05 0 0 0 0 0 0 1 0 16 0 0 0 0 0 0 1 1 07 0 0 0 0 0 0 1 1 18 0 0 0 0 0 1 0 0 09 0 0 0 0 0 1 0 0 110 0 0 0 0 0 1 0 1 011 0 0 0 0 0 1 0 1 112 0 0 0 0 0 1 1 0 013 0 0 0 0 0 1 1 0 114 0 0 0 0 0 1 1 1 015 0 0 0 0 0 1 1 1 116 0 0 0 0 1 0 0 0 0—- many rows —-509 1 1 1 1 1 1 1 0 1510 1 1 1 1 1 1 1 1 0511 1 1 1 1 1 1 1 1 1

(512 row(s) affected)

SQL SERVER – DBCC commands List – documented and undocumented

May 15, 2007 by pinaldave

Database Consistency Checker (DBCC) commands can gives valuable insight into what’s going on inside SQL Server system. DBCC commands have powerful documented functions and many undocumented capabilities. Current DBCC commands are most useful for performance and troubleshooting exercises.To learn about all the DBCC commands run following script in query analyzer.DBCC TRACEON(2520)DBCC HELP (‘?’)GOTo learn about syntax of an individual DBCC command run following script in query analyzer.DBCC HELP(<command>)GOFollowing is the list of all the DBCC commands and their syntax. List contains all documented and undocumented DBCC commands.DBCC activecursors [(spid)]

Page 213: 9 Jan 01, 2007-431 Dec 31, 2007

DBCC addextendedproc (function_name, dll_name)

DBCC addinstance (objectname, instancename)

DBCC adduserobject (name)

DBCC auditevent (eventclass, eventsubclass, success, loginname, rolename, dbusername, loginid)

DBCC autopilot (typeid, dbid, tabid, indid, pages [,flag])

DBCC balancefactor (variance_percent)

DBCC bufcount [(number_of_buffers)]

DBCC buffer ( {‘dbname’ | dbid} [, objid [, number [, printopt={0|1|2} ][, dirty | io | kept | rlock | ioerr | hashed ]]])

DBCC bytes ( startaddress, length )

DBCC cachestats

DBCC callfulltext

DBCC checkalloc [('database_name'[, NOINDEX | REPAIR])][WITH NO_INFOMSGS[, ALL_ERRORMSGS][, ESTIMATEONLY]]

DBCC checkcatalog [('database_name')] [WITH NO_INFOMSGS]

DBCC checkconstraints [( 'tab_name' | tab_id | 'constraint_name' | constraint_id )][WITH ALL_CONSTRAINTS | ALL_ERRORMSGS]

DBCC checkdb [('database_name'[, NOINDEX | REPAIR])][WITH NO_INFOMSGS[, ALL_ERRORMSGS][, PHYSICAL_ONLY][, ESTIMATEONLY][,DBCC TABLOCK]

DBCC checkdbts (dbid, newTimestamp)]

DBCC checkfilegroup [( [ {'filegroup_name' | filegroup_id} ][, NOINDEX] )] [WITH NO_INFOMSGS[, ALL_ERRORMSGS][, PHYSICAL_ONLY][, ESTIMATEONLY][, TABLOCK]]

DBCC checkident (‘table_name’[, { NORESEED | {RESEED [, new_reseed_value] } } ] )

DBCC checkprimaryfile ( {‘FileName’} [, opt={0|1|2|3} ])

DBCC checktable (‘table_name’[, {NOINDEX | index_id | REPAIR}])[WITH NO_INFOMSGS[, ALL_ERRORMSGS][, PHYSICAL_ONLY][, ESTIMATEONLY][, TABLOCK]]

DBCC cleantable (‘database_name’|database_id, ‘table_name’|table_id,[batch_size])

DBCC cacheprofile [( {actionid} [, bucketid])

DBCC clearspacecaches (‘database_name’|database_id,‘table_name’|table_id, ‘index_name’|index_id)

DBCC collectstats (on | off)

Page 214: 9 Jan 01, 2007-431 Dec 31, 2007

DBCC concurrencyviolation (reset | display | startlog | stoplog)

DBCC config

DBCC cursorstats ([spid [,'clear']])

DBCC dbinfo [('dbname')]

DBCC dbrecover (dbname [, IgnoreErrors])

DBCC dbreindex (‘table_name’ [, index_name [, fillfactor ]]) [WITH NO_INFOMSGS]

DBCC dbreindexall (db_name/db_id, type_bitmap)

DBCC dbrepair (‘dbname’, DROPDB [, NOINIT])

DBCC dbtable [({'dbname' | dbid})]

DBCC debugbreak

DBCC deleteinstance (objectname, instancename)

DBCC des [( {'dbname' | dbid} [, {'objname' | objid} ])]

DBCC detachdb [( 'dbname' )]

DBCC dropcleanbuffers

DBCC dropextendedproc (function_name)

DBCC dropuserobject (‘object_name’)

DBCC dumptrigger ({‘BREAK’, {0 | 1}} | ‘DISPLAY’ | {‘SET’, exception_number}| {‘CLEAR’, exception_number})

DBCC errorlog

DBCC extentinfo [({'database_name'| dbid | 0}[,{'table_name' | table_id} [, {'index_name' | index_id | -1}]])]

DBCC fileheader [( {'dbname' | dbid} [, fileid])

DBCC fixallocation [({'ADD' | 'REMOVE'},{'PAGE' | 'SINGLEPAGE' | 'EXTENT' | 'MIXEDEXTENT'}, filenum, pagenum [, objectid, indid])

DBCC flush (‘data’ | ‘log’, dbid)

DBCC flushprocindb (database)

DBCC free dll_name (FREE)

DBCC freeproccache

dbcc freeze_io (db)

Page 215: 9 Jan 01, 2007-431 Dec 31, 2007

dbcc getvalue (name)

dbcc icecapquery (‘dbname’, stored_proc_name[, #_times_to_icecap (-1 infinite, 0 turns off)])Use ‘dbcc icecapquery (printlist)’ to see list of SP’s to profile.Use ‘dbcc icecapquery (icecapall)’ to profile all SP’s.

dbcc incrementinstance (objectname, countername, instancename, value)

dbcc ind ( { ‘dbname’ | dbid }, { ‘objname’ | objid }, { indid | 0 | -1 | -2 } )

DBCC indexdefrag ({dbid | dbname | 0}, {tableid | tablename}, {indid |indname})

DBCC inputbuffer (spid)

DBCC invalidate_textptr (textptr)

DBCC invalidate_textptr_objid (objid)

DBCC iotrace ( { ‘dbname’ | dbid | 0 | -1 }, { fileid | 0 }, bufsize, [ { numIOs | -1 }[, { timeout (sec) | -1 } [, printopt={ 0 | 1 }]]] )

DBCC latch ( address [, 'owners'] [, 'stackdumps'])

DBCC lock ([{'DUMPTABLE' | 'DUMPSTATS' | 'RESETSTATS' | 'HASH'}] |[{'STALLREPORTTHESHOLD', stallthreshold}])

DBCC lockobjectschema (‘object_name’)

DBCC log ([dbid[,{0|1|2|3|4}[,['lsn','[0x]x:y:z’]|['numrecs',num]|['xdesid','x:y']|['extent','x:y']|['pageid','x:y']|['objid',{x,'y'}]|['logrecs',{'lop'|op}...]|['output',x,['filename','x']]…]]])

DBCC loginfo [({'database_name' | dbid})]

DBCC matview ({‘PERSIST’ | ‘ENDPERSIST’ | ‘FREE’ | ‘USE’ | ‘ENDUSE’})

DBCC memobjlist [(memory object)]

DBCC memorymap

DBCC memorystatus

DBCC memospy

DBCC memusage ([IDS | NAMES], [Number of rows to output])

DBCC monitorevents (’sink’ [, 'filter-expression'])

DBCC newalloc – please use checkalloc instead

DBCC no_textptr (table_id , max_inline)

DBCC opentran [({'dbname'| dbid})] [WITH TABLERESULTS[,NO_INFOMSGS]]

DBCC outputbuffer (spid)

Page 216: 9 Jan 01, 2007-431 Dec 31, 2007

DBCC page ( {‘dbname’ | dbid}, filenum, pagenum[, printopt={0|1|2|3} ][, cache={0|1} ])

DBCC perflog

DBCC perfmon

DBCC pglinkage (dbid, startfile, startpg, number, printopt={0|1|2}, targetfile, targetpg, order={1|0})

DBCC pintable (database_id, table_id)

DBCC procbuf [({'dbname' | dbid}[, {'objname' | objid}[, nbufs[, printopt = { 0 | 1 } ]]] )]

DBCC proccache

DBCC prtipage (dbid, objid, indexid [, [{{level, 0}| {filenum, pagenum}}] [,printopt]])

DBCC pss [(uid[, spid[, printopt = { 1 | 0 }]] )]

DBCC readpage ({ dbid, ‘dbname’ }, fileid, pageid, formatstr [, printopt = { 0 | 1} ])

DBCC rebuild_log (dbname [, filename])

DBCC renamecolumn (object_name, old_name, new_name)

DBCC resource

DBCC row_lock (dbid, tableid, set) – Not Needed

DBCC ruleoff ({ rulenum | rulestring } [, { rulenum | rulestring } ]+)

DBCC ruleon ( rulenum | rulestring } [, { rulenum | rulestring } ]+)

DBCC setcpuweight (weight)

DBCC setinstance (objectname, countername, instancename, value)

DBCC setioweight (weight)

DBCC show_statistics (‘table_name’, ‘target_name’)

DBCC showcontig (table_id | table_name [, index_id | index_name][WITH FAST, ALL_INDEXES, TABLERESULTS [,ALL_LEVELS]])

DBCC showdbaffinity

DBCC showfilestats [(file_num)]

DBCC showoffrules

DBCC showonrules

DBCC showtableaffinity (table)

Page 217: 9 Jan 01, 2007-431 Dec 31, 2007

DBCC showtext (‘dbname’, {textpointer | {fileid, pageid, slotid[,option]}})

DBCC showweights

DBCC shrinkdatabase ({dbid | ‘dbname’}, [freespace_percentage[, {NOTRUNCATE | TRUNCATEONLY}]])

DBCC shrinkfile ({fileid | ‘filename’}, [compress_size[, {NOTRUNCATE | TRUNCATEONLY | EMPTYFILE}]])

DBCC sqlmgrstats

DBCC sqlperf (LOGSPACE)({IOSTATS | LRUSTATS | NETSTATS | RASTATS [, CLEAR]}| {THREADS} | {LOGSPACE})

DBCC stackdump [( {uid[, spid[, ecid]} | {threadId, ‘THREADID’}] )]

DBCC tab ( dbid, objid )

DBCC tape_control {‘query’ | ‘release’}[,('.tape')]

DBCC tec [( uid[, spid[, ecid]] )]

DBCC textall [({'database_name'|database_id}[, 'FULL' | FAST] )]

DBCC textalloc ({‘table_name’|table_id}[, 'FULL' | FAST])

DBCC thaw_io (db)

DBCC traceoff [( tracenum [, tracenum ... ] )]

DBCC traceon [( tracenum [, tracenum ... ] )]

DBCC tracestatus (trace# [, ...trace#])

DBCC unpintable (dbid, table_id)

DBCC updateusage ({‘database_name’| 0} [, 'table_name' [, index_id]])[WITH [NO_INFOMSGS] [,] COUNT_ROWS]

DBCC upgradedb (db) DBCC usagegovernor (command, value)

DBCC useplan [(number_of_plan)]

DBCC useroptions DBCC wakeup (spid)

DBCC writepage ({ dbid, ‘dbname’ }, fileid, pageid, offset, length, data)

SQL SERVER – MS TechNet : Storage Top 10 Best Practices

May 14, 2007 by pinaldave

This one of the very interesting article I read regarding SQL Server 2005 Storage. Please refer original article at MS TechNet here.

Page 218: 9 Jan 01, 2007-431 Dec 31, 2007

Understand the IO characteristics of SQL Server and the specific IO requirements / characteristics of your application.

More / faster spindles are better for performance. Try not to “over” optimize the design of the storage; simpler designs generally offer good

performance and more flexibility. Validate configurations prior to deployment. Always place log files on RAID 1+0 (or RAID 1) disks. Isolate log from data at the physical disk level. Consider configuration of TEMPDB database. Lining up the number of data files with CPU’s has scalability advantages for allocation intensive

workloads. Don’t overlook some of SQL Server basics. Don’t overlook storage configuration bases.

SQL SERVER – Query to Find First and Last Day of Current Month

May 13, 2007 by pinaldave

Following query will run respective to today’s date. It will return Last Day of Previous Month, First Day of Current Month, Today, Last Day of Previous Month and First Day of Next Month respective to current month.

DECLARE @mydate DATETIMESELECT @mydate = GETDATE()SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)),@mydate),101) ,'Last Day of Previous Month'UNIONSELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),@mydate),101) AS Date_Value,'First Day of Current Month' AS Date_TypeUNIONSELECT CONVERT(VARCHAR(25),@mydate,101) AS Date_Value, 'Today' AS Date_TypeUNIONSELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)),101) ,'Last Day of Current Month'UNIONSELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))-1),DATEADD(mm,1,@mydate)),101) ,'First Day of Next Month'GO

SQL SERVER – UDF – Function to Parse AlphaNumeric Characters from String

May 13, 2007 by pinaldave

Following function keeps only Alphanumeric characters in string and removes all the other character from the string. This is very handy function when working with Alphanumeric String only. I have used this many times.

CREATE FUNCTION dbo.UDF_ParseAlphaChars(@string VARCHAR(8000))RETURNS VARCHAR(8000)ASBEGINDECLARE @IncorrectCharLoc SMALLINTSET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)WHILE @IncorrectCharLoc > 0BEGINSET @string = STUFF(@string, @IncorrectCharLoc, 1, '')SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)ENDSET @string = @string

Page 219: 9 Jan 01, 2007-431 Dec 31, 2007

RETURN @stringENDGO

—-TestSELECT dbo.UDF_ParseAlphaChars('ABC”_I+{D[]}4|:e;””5,<.F>/?6')GO

Result Set : ABCID4e5F6

SQL SERVER – 2005 – List all the database

May 12, 2007 by pinaldave

List all the database on SQL Servers.All the following Stored Procedure list all the Databases on Server.

I personally use EXEC sp_databases because it gives the same results as other but it is self explaining.----SQL SERVER 2005 System ProceduresEXEC sp_databasesEXEC sp_helpdb----SQL 2000 Method still works in SQL Server 2005SELECT nameFROM sys.databasesSELECT nameFROM sys.sysdatabases----SQL SERVER Un-Documented ProcedureEXEC sp_msForEachDB 'PRINT ''?'''

SQL SERVER – Fix : Error : Msg 6263, Level 16, State 1, Line 2 Enabling SQL Server 2005 for CLR Support

May 12, 2007 by pinaldave

Error:

Fix : Error : Msg 6263, Level 16, State 1, Line 2 Enabling SQL Server 2005 for CLR Support

Fix/Workaround/Solution:

1) Enable Server for CLR Support.

2) Run following query in Query Analyzer

sp_CONFIGURE 'clr_enabled',1GORECONFIGUREGO

If CLR procedure is used without enabling CLR, it will show error message as .NET Framework is not enabled.

SQL SERVER – Explanation SQL Command GO

May 11, 2007 by pinaldave

GO is not a Transact-SQL statement; it is often used in T-SQL code. Go causes all statements from the beginning of the script or the last GO statement (whichever is closer) to be compiled into one execution plan and sent to the server independent of any other batches. SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server. The

Page 220: 9 Jan 01, 2007-431 Dec 31, 2007

current batch of statements is composed of all statements entered since the last GO, or since the start of the ad hoc session or script if this is the first GO.

GO Statement must be written in new line as it is not T-SQL command. T-SQL statement can not occupy the same line as GO. GO statement can contain comments.

Following is example for SQL SERVER 2005 for database Adventureworks.USE AdventureWorks;GODECLARE @MyMsg VARCHAR(50)SELECT @MyMsg = 'Hello, World.'GO ---- @MyMsg is not valid after this GO ends the batch.

—- Yields an error because @MyMsg not declared in this batch.PRINT @MyMsgGO

SQL SERVER – Download Microsoft SQL Server 2005 System Views Map

May 11, 2007 by pinaldave

The Microsoft SQL Server 2005 System Views Map shows the key system views included in SQL Server 2005, and the relationships between them. It is available to download from Microsoft Site. It can be printed and mounted at Office Depot or Kinko’s.

Download SQL SERVER 2005 System Views

SQL SERVER – 2008 Katmai – Download Datasheet Final from Microsoft

May 10, 2007 by pinaldave

Few interesting thing about Katmai.SQL Server “Katmai” will provide a more secure, reliable and manageable enterprise data platform.SQL Server “Katmai” will enable developers and administrators to save time by allowing them to store and consume any type of data from XML to documents.SQL Server “Katmai” provides a more scalable infrastructure that enables IT to drive business intelligence throughout the organization.SQL Server “Katmai” along with .NET Framework 3.0 will accelerate the development of the next generation of applications.

Reference : Pinal Dave (http://blog.SQLAuthority.com) MS SQL Server (All the above text)

Download Final Datasheet of Katmai from Microsoft

SQL SERVER – Fix: Error : HResult 0×2, Level 16, State 1 Named Pipes Provider: Could not open a connection to SQL Server

May 10, 2007 by pinaldave

Error:

HResult 0×2, Level16, State 1Named Pipes Provider: Could not open a connection to SQL Server.Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..Sqlcmd: Error: Microsoft SQL native Client : Login timeout expired

Solution/Fix/WorkAround:By default SQL Server 2005 has TCP/IP connections disabled. To enable TCP/IP support, use the SQL Server

Page 221: 9 Jan 01, 2007-431 Dec 31, 2007

Configuration Manager tool, select SQL Server 2005 Network Configuration, select Protocols, double-click on TCP/IP, and turn on Enabled.

AND

By default SQL Server 2005 has Named Pipes connections disabled. To enable Named Pipes support, use the SQL Server Configuration Manager tool, select SQL Server 2005 Network Configuration, select Protocols, double-click on Named Pipes, and turn on Enabled.

SQL SERVER – 2008 Katmai – Your Data, Any Place, Any Time

May 10, 2007 by pinaldave

I was following up on the news of first Microsoft Business Intelligence (BI) Conference held at Seattle. Good news is – SQL Server 2008 code name ‘Katmai’ is announced. I went to the official website I like the catchy line “Your Data, Any Place, Any Time“. As per my opinion the most important thing about Katmai is that it can be used to manage any type of data, including relational data, documents, geographic information and XML.

The question I received many times since yesterday is :I am still using SQL Server 2000, I was planning to upgrade to SQL Server 2005 very soon. Should I wait till Katmai is released or upgrade to SQL Server 2005 any way and do the upgrade process again next year?

My answer is : Upgrade to SQL Server 2005 any way.There are many advantages to upgrade to SQL Server 2005. They can be easily find online and almost every where. You can always go to SQL Server 2008 Katmai if you prefer.

Now for me the real question is : What Katmai brings to me and my organization additionally to make me upgrade to it?Many sites list the advantage of it : 1) MS Press Pass 2) MS SQL Server

The real factor drives the success of the any software are :No software is perfect. There will be service pack for Katmai. Katmai may be expensive for some organization. It may (most likely) require more upgraded hardware to run the server. Corporation should be in need of features provided by Katmai. If all of this are in order, upgrade to Katmai sooner to take advantage of the latest technology in 2008.

Page 222: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Fix : Error 2501 : Cannot find a table or object with the name . Check the system catalog.

May 9, 2007 by pinaldave

Error 2501 : Cannot find a table or object with the name . Check the system catalog.

This is very generic error beginner DBAs or Developers faces. The solution is very simple and easy. Follow the direction below in order.

Fix/Workaround/Solution:

Make sure that correct Database is selected. If not please run USE YourDatabase.

Check the object or table name. They must be spelled correct.

If database is case sensitive please use correct case.

Use object belongs to other owner use two parts name as scheme_name.object_name.

SQLAuthority News – Author Visit – MIS2007 Part II – Database Raid Discussion

May 9, 2007 by pinaldave

MIS2007 is really going good. There are many things going on. As I mentioned in my previous article, It is really pleasure to meet industry leaders. There was discussion about what is good for database RAID 5 configuration or RAID 10. This subject is always very interesting.

We were discussing from small databases (5GB) to larger databases(5 TB). The question was which RAID 5 or RAID 10. Surprisingly, everybody who participated in discussion said their experience says RAID 10 is better for this particular application as there are lots of reads and writes in database. One of the expert suggested that they have seen performance improvement of more than 6 times for RAID 10. One expert expressed that though they prefer RAID 10 but their IT department suggest RAID 5. The reason was RAID 10 is very expensive over RAID 5 with 6 TB database.

Overall, we all agreed on RAID 10 without any discussion. Please consult your IT department and run few performance test before implementation.

There was very good key note address by Roger Dow, President and CEO, Travel Industry Association. It was very interesting and motivation note. He addressed the issue “There is no such thing as customer loyalty in an intensely competitive world. Customers are changing and we must change to satisfy their individual needs.” Read More: SQL SERVER – Raid Configuration – RAID 10

SQL SERVER – Index Optimization CheckList

May 8, 2007 by pinaldave

Index optimization is always interesting subject to me. Every time I receive request to help optimize query or query on any specific table. I always ask Jr.DBA to go over following list first before I take a look at it. Most of the time the Query Speed is optimized just following basic rules mentioned below. Once following checklist applied interesting optimization part begins which only experiment and experience can resolve.

Create Index on frequently used columns in T-SQL Code. Columns used in WHERE, ORDER BY and GROUP BY are good candidate for Indexes. Create Index on column which are used in JOIN Condition.

Remove any un-necessary Indexes. As Index occupies hard drive space as well as it decreases performance of all the insert, updates, deletes to the table.

Smaller Index Key gives better performance than Index key which covers large data or many columns

Index on Integer Columns performs better than varchar columns.

Page 223: 9 Jan 01, 2007-431 Dec 31, 2007

Clustered Index must exist before creating Non-Clustered Index. Clustered Index must be created on Single Column which is not changing and narrow in size. Best

candidate is primary key. Non-clustered Indexes increases performance of the query that returns fewer rows and rows has

wide selectivity spectrum. Each table must have one Clustered Index. If column have low selectivity avoid creating Index on that column as it slow down the rows

modification and system will not get benefit from Index. Multiple Columns Index or Covered Index should be ordered as Most Selective column on left and

gradually decreasing selectivity as they go right. Use SORT_IN_TEMPDB option when table is created if tempdb is on different disk. This will

increase the performance to create Index. Rebuild Index frequently using ALTER INDEX and De-fragment Index to keep performance optimal

for Indexes.

SQLAuthority News – Author Visit – The 2007 Marketing Innovation Summit, Las Vegas

May 8, 2007 by pinaldave

I am attending The 2007 Marketing Innovation Summit“, Las Vegas. It started on 5/6/2007 and will continue till 5/9/2007. Unica Corporation has arranged this conference.

The MIS 2007 Agenda includes:

Case studies and best practices Sessions focused on Relationship Marketing, Internet Marketing and Marketing Operations Hands on “how to” sessions General sessions from distinguished industry experts A one-day Pre-Summit Affinium New User Workshop and Getting Prepared for Affinium Plan Post-Summit Hands-On Training Evening networking activities

In two days so far, I have learned a lot and have met many industry leaders. Talking about cutting edge technology and SQL Server was perfect environment for me. I was glad to meet couple of SQLAuthority.com readers also. It was fun to meet everybody. Tomorrow I am going to attend few more track sessions and I am sure they will be excellent as this ones.

SQL SERVER – Top 10 Hidden Gems in SQL Server 2005

May 7, 2007 by pinaldave

Top 10 Hidden Gems in SQL Server 2005By Cihan Biyikoglu

SQL Server 2005 has hundreds of new and improved components. Some of these improvements get a lot of the spotlight. However there is another set that are the hidden gems that help us improve performance, availability or greatly simplify some challenging scenarios. This paper lists the top 10 such features in SQL Server 2005 that we have discovered through the implementation with some of our top customers and partners.

1. TableDiff.exe2. Triggers for Logon Events (New in Service Pack 2)3. Boosting performance with persisted-computed-columns (pcc).4. DEFAULT_SCHEMA setting in sys.database_principles5. Forced Parameterization6. Vardecimal Storage Format7. Indexing made easier with SQL Server 20058. Figuring out the most popular queries in seconds9. Scalable Shared Databases10. Soft-NUMA

Page 224: 9 Jan 01, 2007-431 Dec 31, 2007

Read original Microsoft TechNet Article for detailed explanation

SQL SERVER – 2005/2000 Examples and Explanation for GOTO

May 7, 2007 by pinaldave

The GOTO statement causes the execution of the T-SQL batch to stop processing the following commands to GOTO and processing continues from the label where GOTO points.GOTO statement can be used anywhere within a procedure, batch, or function. GOTO can be nested as well. GOTO can be executed by any valid user on SQL SERVER. GOTO can co-exists with other control of flow statements (IF…ELSE, WHILE). GOTO can only go(jump) to label in the same batch, it can not go to label out side of the batch.

Syntax:Define the label:label :ALTER the execution:GOTO label

My Views on GOTOI do not prefer to use GOTO (except while doing error checking sometime). Use GOTO statement sparingly. Excessive use of the GOTO statement adds difficult to understand the logic of the T-SQL batch. I have almost always implemented the logic which involves GOTO with other control-of-flow statement. GOTO is best used for breaking out of deeply nested control-of-flow statements.

The label that is the target of a GOTO identifies only the target of the jump. The label does nothing to isolate the statements following it from the statements immediately before it. Any user executing the statements immediately before the label skips the label and executes the statements after the label. This happens unless the statement immediately preceding the label is itself a control-of-flow statement, such as a RETURN.

The following is an examples of a GOTO from BOL:

GOTO Example for SQL SERVER 2005:DECLARE @Counter INT;SET @Counter = 1;WHILE @Counter < 10BEGINSELECT @CounterSET @Counter = @Counter + 1IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.IF @Counter = 5 GOTO Branch_Two --This will never execute.ENDBranch_One:SELECT 'Jumping To Branch One.'GOTO Branch_Three; --This will prevent Branch_Two from executing.Branch_Two:SELECT 'Jumping To Branch Two.'Branch_Three:SELECT 'Jumping To Branch Three.'

GOTO Example for SQL SERVER 2000:USE pubsGODECLARE @tablename sysnameSET @tablename = N'authors'table_loop:IF (@@FETCH_STATUS <> -2)BEGINSELECT @tablename = RTRIM(UPPER(@tablename))EXEC ("SELECT "" + @tablename + "" = COUNT(*) FROM "+ @tablename )PRINT " "ENDFETCH NEXT

Page 225: 9 Jan 01, 2007-431 Dec 31, 2007

FROM tnames_cursor INTO @tablenameIF (@@FETCH_STATUS <> -1) GOTO table_loopGO

SQL SERVER – Creating Comma Separate Values List from Table – UDF – SP

May 6, 2007 by pinaldave

Following script will create common separate values (CSV) or common separate list from tables. convert list to table. Following script is written for SQL SERVER 2005. It will also work well with very big TEXT field. If you want to use this on SQL SERVER 2000 replace VARCHAR(MAX) with VARCHAR(8000) or any other varchar limit. It will work with INT as well as VARCHAR.

There are three ways to do this. 1) Using COALESCE 2) Using SELECT Smartly 3) Using CURSOR.

The table is example is:TableName:

Page 226: 9 Jan 01, 2007-431 Dec 31, 2007

NumberTableNumberCols

first

second

third

fourth

fifth

Output : first,second,third,fourth,fifth

Option 1: This is the smartest way.DECLARE @listStr VARCHAR(MAX)SELECT @listStr = COALESCE(@listStr+',' , '') + NumberColsFROM NumberTableSELECT @listStrPlease make a note that COALESCE returns the first NOT NULL value from the argument list we pass.

Option 2: This is the smart but not the best way; though I have seen similar code many times.DECLARE @listStr VARCHAR(MAX)SET @listStr = ''SELECT @listStr = @listStr + NumberCols + ','FROM NumberTableSELECT SUBSTRING(@listStr , 1, LEN(@listStr)-1)I sometime use ISNULL(NumberCols,’NullValue’) to convert NULL values to other desired value.

Option 3: Cursor are not the best way, please use either of above options.

Above script can be converted to User Defined Function (UDF) or Storped Procedure (SP).

SQL SERVER – UDF – Function to Convert List to Table

May 6, 2007 by pinaldave

Following Users Defined Functions will convert list to table. It also supports user defined delimiter. Following UDF is written for SQL SERVER 2005. It will also work well with very big TEXT field. If you want to use this on SQL SERVER 2000 replace VARCHAR(MAX) with VARCHAR(8000) or any other varchar limit. It will work with INT as well as VARCHAR.

CREATE FUNCTION dbo.udf_List2Table(@List VARCHAR(MAX),@Delim CHAR)

Page 227: 9 Jan 01, 2007-431 Dec 31, 2007

RETURNS@ParsedList TABLE(item VARCHAR(MAX))ASBEGINDECLARE @item VARCHAR(MAX), @Pos INTSET @List = LTRIM(RTRIM(@List))+ @DelimSET @Pos = CHARINDEX(@Delim, @List, 1)WHILE @Pos > 0BEGINSET @item = LTRIM(RTRIM(LEFT(@List, @Pos - 1)))IF @item <> ''BEGININSERT INTO @ParsedList (item)VALUES (CAST(@item AS VARCHAR(MAX)))ENDSET @List = RIGHT(@List, LEN(@List) - @Pos)SET @Pos = CHARINDEX(@Delim, @List, 1)ENDRETURNENDGO

Run following script to test above UDF.----Example 1 for VARHCARSELECT item AS Example1FROM dbo.udf_List2Table('first||2nd||III||1+1+1+1','||')GO----Example 2 for INTSELECT CAST(item AS INT) AS Example2FROM dbo.udf_List2Table('111,222,333,444,555',',')GO

ResultSet:Example1————-first2ndIII1+1+1+1

(4 row(s) affected)

Example2————-111222333444555

SQL SERVER – 2005 Enable CLR using T-SQL script

Page 228: 9 Jan 01, 2007-431 Dec 31, 2007

May 5, 2007 by pinaldave

Before doing any .Net coding in SQL Server you must enable the CLR. In SQL Server 2005, the CLR is OFF by default.This is done in an effort to limit security vulnerabilities. Following is the script which will enable CLR.

EXEC sp_CONFIGURE 'show advanced options' , '1';GORECONFIGURE;GOEXEC sp_CONFIGURE 'clr enabled' , '1'GORECONFIGURE;GO

SQL SERVER – UDF – User Defined Function to Find Weekdays Between Two Dates

May 5, 2007 by pinaldave

Following user defined function returns number of weekdays between two dates specified. This function excludes the dates which are passed as input params. It excludes Saturday and Sunday as they are weekends. I always had this function with for reference but after some research I found original source website of the function. This function has been written by Author Alexander Chigrik.

CREATE FUNCTION dbo.spDBA_GetWeekDays( @StartDate datetime,@EndDate datetime )RETURNS INTASBEGINDECLARE @WorkDays INT, @FirstPart INTDECLARE @FirstNum INT, @TotalDays INTDECLARE @LastNum INT, @LastPart INTIF (DATEDIFF(DAY, @StartDate, @EndDate) 0) THEN @LastPart - 1ELSE 0ENDSELECT @WorkDays = @WorkDays * 5 + @FirstNum + @LastNumENDRETURN ( @WorkDays )ENDGOThis function can be used asSELECT dbo.spDBA_GetWeekDays ('10/10/2005', '11/22/2005')GO

SQL SERVER – Fix : Error : Msg 7311, Level 16, State 2, Line 1 Cannot obtain the schema rowset DBSCHEMA_TABLES_INFO for OLE DB provider SQLNCLI for linked server LinkedServerName

May 4, 2007 by pinaldave

You may receive an error message when you try to run distributed queries from a 64-bit SQL Server 2005 client to a linked 32-bit SQL Server 2000 server or to a linked SQL Server 7.0 server.

Error:The stored procedure required to complete this operation could not be found on the server. Please contact your system administrator.Msg 7311, Level 16, State 2, Line 1Cannot obtain the schema rowset “DBSCHEMA_TABLES_INFO” for OLE DB provider “SQLNCLI” for linked server “<LinkedServerName>”. The provider supports the interface, but returns a failure code when it is used.

Fix/WorkAround/Solution:

Page 229: 9 Jan 01, 2007-431 Dec 31, 2007

Use Windows Authentication modeFor a default instanceosql -E -S <LinkedServerName> -i <Location>\instcat.sql

For a named instanceosql -E -S <LinkedServerName>\<InstanceName> -i <Location>\instcat.sql

Use SQL Server Authentication modeFor a default instanceosql -U <AdminLogin> -P <AdminPassword> -S <LinkedServerName> -i <Location>\instcat.sql

For a named instanceosql -U <AdminLogin> -P <AdminPassword> -S <LinkedServerName>\<InstanceName> -i <Location>\instcat.sql

By default, this folder is C:\Program Files\Microsoft SQL Server\MSSQL\Install.

Example:osql -U sa -P MyPassWord -S Database.IpAddress.com -i “C:\Program Files\Microsoft SQL Server\MSSQL\Install\instcat.sql”

SQL SERVER – Download SQL Server Management Studio Keyboard Shortcuts (SSMS Shortcuts)

May 4, 2007 by pinaldave

Download SQL Server Management Studio Keyboard Shortcuts

I have received many emails appreciating my article Query Analyzer Shortcuts and requesting same for SQL Server Management Studio Keyboard Shortcuts. I see frequent downloads of the PDF generated by SQLAuthority for the same on server. There is original article on MSDN site. I have combined complete article in one PDF again. It is easy to refer, print and manage.

Download SQL Server Management Studio Keyboard Shortcuts

SQL SERVER – DBCC commands to free several SQL Server memory caches

May 3, 2007 by pinaldave

DBCC commands to free several SQL Server memory caches:

DBCC FREESYSTEMCACHEReleases all unused cache entries from all caches. The SQL Server 2005 Database Engine proactively cleans up unused cache entries in the background to make memory available for current entries.

DBCC FREESESSIONCACHEFlushes the distributed query connection cache used by distributed queries against an instance of Microsoft SQL Server.

DBCC FREEPROCCACHERemoves all elements from the procedure cache.

SQL SERVER – Enable Login – Disable Login using ALTER LOGIC – Change name of the ‘SA’

May 3, 2007 by pinaldave

In SQL SERVER 2005, all the login (including ’sa’ ) can be enabled and disabled using ALTER LOGIN command.

Page 230: 9 Jan 01, 2007-431 Dec 31, 2007

To disable ’sa’ login:ALTER LOGIN sa DISABLEGO

To enable ’sa’ login:ALTER LOGIN sa ENABLEGO

Also for additional security (prevent educated guess from hackers) the name of the ’sa’ account can be changed.ALTER LOGIN [sa] WITH NAME = [AdminUser]GO

SQL SERVER – FIX : ERROR 1101 : Could not allocate a new page for database because of insufficient disk space in filegroup

May 2, 2007 by pinaldave

ERROR 1101 : Could not allocate a new page for database because of insufficient disk space in filegroup . Create the necessary space by dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.

Fix/Workaround/Solution:Make sure there is enough Hard Disk space where database files are stored on server.Turn on AUTOGROW for file groups.

SQL SERVER – 2005 TOP Improvements/Enhancements

May 2, 2007 by pinaldave

SQL Server 2005 introduces two enhancements to the TOP clause.1) User can specify an expression as an input to the TOP keyword.2) User can use TOP in modification statements (INSERT, UPDATE, and DELETE).

Explanation : User can specify an expression as an input to the TOP keyword.In SQL SERVER 2000 usage of TOP is implemented in following query.

SELECT TOP 10 TableColumnIDFROM TableName

For ages Developers and DBAs wants to pass parameters to TOP keyword. IN SQL SERVER 2005 it is possible. Example, @iNum is variables set before SELECT statement is ran.

DECLARE @iNum INTSET @iNum = 10SELECT TOP (@iNum) TableColumnIDFROM TableName

This code will run fine in SQL SERVER 2005. Now it is possible to pass variables through Stored Procedures and T-SQL Code. Not only variables but we can run sub-query as a parameters of the TOP. Example, following query will return TOP 1/4 rows from table TableName.

SELECT TOP (SELECT CAST((SELECT COUNT(*)/4FROM TableName) AS INT)) *FROM TableName

Explanation : User can use TOP in modification statements (INSERT, UPDATE, and DELETE).In SQL SERVER 2000 usage of the limited row modification was implemented using SET ROWSET command. Example,

SET ROWCOUNT 5UPDATE TableName

Page 231: 9 Jan 01, 2007-431 Dec 31, 2007

SET TableColumn = 14SET ROWCOUNT 0

In SQL SERVER 2005 limited row modification can be achieved by TOP keyword function. Example,

UPDATE TOP(5) TableNameSET TableColumn = 14

SQL SERVER – Copy Column Headers in Query Analyzers in Result Set

May 1, 2007 by pinaldave

Copy Column Headers in Query Analyzers in Result Set.

In Query Analyzer go to Menu >> Tools >> Options >> ResultsSelect Default results Target: Results to TextResults output format:(*): Tab DelimitedPrint column headers(*): Checkbox ON(check)

SQLAuthority.com 100th Post – Gratitude Note to Readers

May 1, 2007 by pinaldave

Hello All,

I would like to express my deep gratitude to all of my readers for their emails, comments, suggestions and continuous support on the occasion of 101st post on this blog.

I would like to extend my gratitude to my parents. In good times or trying times my parents are there with me always. Mom and Dad thank you for your encouragement, warmth, advise and continuous love.

Kind Regards and Best Wishes,

SQL SERVER – Collate – Case Sensitive SQL Query Search

April 30, 2007 by pinaldave

Case Sensitive SQL Query Search

If Column1 of Table1 has following values ‘CaseSearch, casesearch, CASESEARCH, CaSeSeArCh’, following statement will return you all the four records.

SELECT Column1FROM Table1WHERE Column1 = 'casesearch'

To make the query case sensitive and retrieve only one record (“casesearch”) from above query, the collation of the query needs to be changed as follows.

SELECT Column1FROM Table1WHERE Column1 COLLATE Latin1_General_CS_AS = 'casesearch'

Adding COLLATE Latin1_General_CS_AS makes the search case sensitive.

Default Collation of the SQL Server installation SQL_Latin1_General_CP1_CI_AS is not case sensitive.

To change the collation of the any column for any table permanently run following query.

Page 232: 9 Jan 01, 2007-431 Dec 31, 2007

ALTER TABLE Table1ALTER COLUMN Column1 VARCHAR(20)COLLATE Latin1_General_CS_AS

To know the collation of the column for any table run following Stored Procedure.

EXEC sp_help DatabaseName

Second results set above script will return you collation of database DatabaseName.

SQL SERVER – FIX : ERROR : Msg 3159, Level 16, State 1, Line 1 – Msg 3013, Level 16, State 1, Line 1

April 30, 2007 by pinaldave

While moving some of the script from SQL SERVER 2000 to SQL SERVER 2005 our migration team faced following error.

Msg 3159, Level 16, State 1, Line 1The tail of the log for the database “AdventureWorks” has not been backed up.Use BACKUP LOG WITH NORECOVERY to backup the log if it contains work you do not want to lose.Use the WITH REPLACE or WITH STOPAT clause of the RESTORE statement to just overwrite the contents of the log.Msg 3013, Level 16, State 1, Line 1RESTORE DATABASE is terminating abnormally.

Following is the similar script using AdventureWorks samples database as example. This scripts works perfectly fine with SQL SERVER 2000. It gives the error in SQL SERVER 2005.

RESTORE DATABASE AdventureWorksFROM DISK = 'C:\BackupAdventureworks.bak'WITH MOVE 'AdventureWorks_Data' TO 'C:\Data',MOVE 'AdventureWorks_Log' TO 'C:\Data'

The reason of error is already explained in the error detail. Requirement of backing up tail of the log for the database can be overridden by using RESTORE command. Most of the WITH clause statements can be used in combination with the others. Change the syntax of above script with addition of REPLACE in WITH clause.

ALTER DATABASE AdventureWorksSET SINGLE_USER WITHROLLBACK IMMEDIATERESTORE DATABASE AdventureWorksFROM DISK = 'C\:BackupAdventureworks.bak'WITH MOVE 'AdventureWorks_Data' TO 'C:\Data\datafile.mdf',MOVE 'AdventureWorks_Log' TO 'C:\Data\logfile.ldf',REPLACE

SQL SERVER – SET ROWCOUNT – Retrieving or Limiting the First N Records from a SQL Query

April 30, 2007 by pinaldave

A SET ROWCOUNT statement simply limits the number of records returned to the client during a single connection. As soon as the number of rows specified is found, SQL Server stops processing the query. The syntax looks like this:SET ROWCOUNT 10SELECT *FROM dbo.Orders

Page 233: 9 Jan 01, 2007-431 Dec 31, 2007

WHERE EmployeeID = 5ORDER BY OrderDateSET ROWCOUNT 0To set this option off so that all rows are returned, specify SET ROWCOUNT 0.

When does it work?SET ROWCOUNT option is ignored for INSERT, UPDATE, and DELETE statements against remote tables and local, remote partitioned views and when an explicit TOP expression is used in the same statement. This includes statements in which INSERT is followed by a SELECT clause. SET ROWCOUNT overrides the SELECT statement TOP keyword if the rowcount is the smaller value.

How does it work?Setting the SET ROWCOUNT option causes most Transact-SQL statements to stop processing when they have been affected by the specified number of rows. This includes triggers and data modification statements such as INSERT, UPDATE, and DELETE. The ROWCOUNT option does not affect dynamic cursors, but it does limit the rowset of keyset and insensitive cursors. This option should be used with caution and primarily with the SELECT statement. The setting of SET ROWCOUNT is set at execute or run time and not at parse time.

Interesting Facts:Though SET ROWCOUNT n cannot be used in a UDF, the current ROWCOUNT limit setting of its caller will be applied to the SELECT statements in the UDF. When SET ROWCOUNT n applies to a SELECT statement with sub-queries, the results and ordering are always guaranteed. To avoid confusion and unexpected logical errors, it’s better to turn SET ROWCOUNT n on just before the final SELECT statement that returns the records.

SQL SERVER 2005In SQL server 2005, SET ROWCOUNT n has the same behavior as SQL server 2000. It’s recommended to use TOP (n) instead of SET ROWCOUNT n.

SQL SERVER – 2005 Security DataSheet

April 29, 2007 by pinaldave

Microsoft has implemented strong security features into the Microsoft® SQL Server™ 2005, which provides a security-enabled platform for enterprise-class relational database and analysis solutions. SQL Server 2005 provides cutting edge security technology and addresses several security issues, including automatic secured updates and encryption of sensitive data.

Download the SQL Server 2005 Security DataSheet from SQLAuthority.comDownload the SQL Server 2005 Security DataSheet from Microsoft.com

SQL SERVER – Random Number Generator Script – SQL Query

April 29, 2007 by pinaldave

Random Number Generator

There are many methods to generate random number in SQL Server.

Method 1 : Generate Random Numbers (Int) between Rang---- Create the variables for the random number generationDECLARE @Random INT;DECLARE @Upper INT;DECLARE @Lower INT

---- This will create a random number between 1 and 999SET @Lower = 1 ---- The lowest random numberSET @Upper = 999 ---- The highest random numberSELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)SELECT @Random

Page 234: 9 Jan 01, 2007-431 Dec 31, 2007

Method 2 : Generate Random Float NumbersSELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )+ (DATEPART(ss, GETDATE()) * 1000 )+ DATEPART(ms, GETDATE()) )

Method 3 : Random Numbers Quick Scripts---- random float from 0 up to 20 - [0, 20)SELECT 20*RAND()-- random float from 10 up to 30 - [10, 30)SELECT 10 + (30-10)*RAND()--random integer BETWEEN 0AND 20 - [0, 20]SELECT CONVERT(INT, (20+1)*RAND())----random integer BETWEEN 10AND 30 - [10, 30]SELECT 10 + CONVERT(INT, (30-10+1)*RAND())

Method 4 : Random Numbers (Float, Int) Tables Based with TimeDECLARE @t TABLE( randnum float )DECLARE @cnt INT; SET @cnt = 0WHILE @cnt <=10000BEGINSET @cnt = @cnt + 1INSERT INTO @tSELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )+ (DATEPART(ss, GETDATE()) * 1000 )+ DATEPART(ms, GETDATE()) )ENDSELECT randnum, COUNT(*)FROM @tGROUP BY randnum

Method 5 : Random number on a per row basis---- The distribution is pretty good however there are the occasional peaks.---- If you want to change the range of values just change the 1000 to the maximum value you want.---- Use this as the source of a report server report and chart the results to see the distributionSELECT randomNumber, COUNT(1) countOfRandomNumberFROM (SELECT ABS(CAST(NEWID() AS binary(6)) %1000) + 1 randomNumberFROM sysobjects) sampleGROUP BY randomNumberORDER BY randomNumber

SQL SERVER – Replication Keywords Explanation and Basic Terms

April 29, 2007 by pinaldave

While discussing replication with Jr. DBAs at work, I realize some of them have not experienced replication feature of SQL SERVER. Following is quick reference of replication keywords I created for easy conversation.

PublisherThe publisher is the source database where replication begins. It makes data available for replication.

SubscriberThe subscriber is the destination database where replication ends. It either receives a snapshot of all the published data or applies transactions that have been replicated to itself.

DistributorThe distributor is the intermediary between the publisher and subscriber. It receives published transactions or snapshots and then stores and forwards these publications to the subscribers.

PublicationThe publication is the storage container for different articles. A subscriber can subscribe to an individual article or an entire publication.

Page 235: 9 Jan 01, 2007-431 Dec 31, 2007

ArticleAn article is the data, transactions, or stored procedures that are stored within a publication. This is the actual information that is going to be replicated.

Two-phase commitTwo-phase commit is a form of replication in which modifications made to the publishing database are made at the subscription database at the same time.

MSDN : Replication

SQL SERVER – Explanation SQL SERVER Merge Join

April 28, 2007 by pinaldave

The Merge Join transformation provides an output that is generated by joining two sorted data sets using a FULL, LEFT, or INNER join. The Merge Join transformation requires that both inputs be sorted and that the joined columns have matching meta-data. User cannot join a column that has a numeric data type with a column that has a character data type. If the data has a string data type, the length of the column in the second input must be less than or equal to the length of the column in the first input with which it is merged.

USE pubsGOSELECT a.au_idFROM authors aJOIN titleauthor b ON a.au_id = b.au_idOPTION (MERGE JOIN)GO

Merge join itself is very fast, but it can be an expensive choice if sort operations are required . However, if the data volume is large and the desired data can be obtained presorted from existing B-tree indexes, merge join is often the fastest available join algorithm. Because the query optimizer usually selects the best execution plan for a given select statement, it is not necessary to enforce the desirable join type, but sometimes it can be useful. User can enforce the desirable join type by using the OPTION clause.

Following query will be benefited by MERGE JOIN because authors and titleauthor both has primary key index on au_id. Due to Primary Key on au_id it is physically sorted by au_id.

This article is the in-depth analysis of the MERGE JOIN. Very informative.

SQL Server ReplicationReplication is a set of technologies for copying and distributing data and database objects from one database to another and then synchronizing between databases to maintain consistency. Using replication, you can distribute data to different locations and to remote or mobile users over local and wide area networks, dial-up connections, wireless connections, and the Internet.

Transactional replication is typically used in server-to-server scenarios that require high throughput, including: improving scalability and availability; data warehousing and reporting; integrating data from multiple sites; integrating heterogeneous data; and offloading batch processing. Merge replication is primarily designed for mobile applications or distributed server applications that have possible data conflicts. Common scenarios include: exchanging data with mobile users; consumer point of sale (POS) applications; and integration of data from multiple sites. Snapshot replication is used to

Page 236: 9 Jan 01, 2007-431 Dec 31, 2007

provide the initial data set for transactional and merge replication; it can also be used when complete refreshes of data are appropriate. With these three types of replication, SQL Server provides a powerful and flexible system for synchronizing data across your enterprise.

In addition to replication, in SQL Server 2008, you can sychronize databases by using Microsoft Sync Framework and Sync Services for ADO.NET. Sync Services for ADO.NET provides an intuitive and flexible API that you can use to build applications that target offline and collaboration scenarios. For an overview of Sync Services for ADO.NET, see Microsoft Sync Framework. For complete documentation, see this MSDN Web site.

Browse Content by Life Cycle

 Product Evaluation

 Getting Started

 Planning and Architecture

 Development

 Deployment

 Operations

 Security and Protection

 Troubleshooting

 Technical Reference

Browse Content by Role

 Administrator

 Developer

 Architect

SQL SERVER – Restrictions of Views – T SQL View Limitations

April 28, 2007 by pinaldave

UPDATE: (5/15/2007) Thank you Ben Taylor for correcting errors and incorrect information from this post. He is Database Architect and writes Database Articles at www.sswug.org.

Page 237: 9 Jan 01, 2007-431 Dec 31, 2007

I have been coding as T-SQL for many years. I never have to use view ever in my career. I do not see in my near future I am using Views. I am able to achieve same database architecture goal using either using Third Normal tables, Replications or other database design work around.SQL Views have many many restrictions. There are few listed below. I love T-SQL but I do not like using Views.

The ANSI_NULLS and QUOTED_IDENTIFIER options must be turned on when the view is created. Following SP will turn those options on.

sp_dboption 'ANSI_NULLS', TRUEsp_dboption 'QUOTED_IDENTIFIER', TRUE

The ANSI_NULLS option must have been turned on during the creation of all the tables that are referenced by the view.

All the tables referenced by the view must be in the same database as the view.

All the tables referenced by the view must have the same owner as the view.

Indexed view must be created with the SCHEMABINDING option. This option prohibits the schema of the base tables from being changed (adding or dropping a column, for instance). To change the tables, Indexed view must be dropped.

Any user-defined functions referenced in the view must have been created with the SCHEMABINDING option as well.

Any functions referenced in an indexed view must be deterministic; deterministic functions return the same value each time they’re invoked with the same arguments.

A column can not be referenced twice in the SELECT statement unless all references, or all but one reference, to the column are made in a complex expression.Illegal:SELECT qty, orderid, qtyLegal:SELECT qty, orderid, SUM(qty)

You can’t use ROWSET, UNION, TOP, ORDER BY, DISTINCT, COUNT(*), COMPUTE, or COMPUTE BY.

The AVG, MAX, MIN, STDEV, STDEVP, VAR, and VARP aggregate functions aren’t allowed in the SELECT statement.

A SUM() that references a nullable expression isn’t allowed.

CONTAINS and FREETEXT aren’t allowed in the SELECT statement.

If you use GROUP BY, you can’t use HAVING, ROLLUP, or CUBE, and you must use COUNT_BIG() in the select list.

You can’t modify more than one table at a time through a view.

If your view is based on aggregate functions, you can’t use it to modify data.

If your view is based on a table that contains fields that don’t allow null values yet your view doesn’t display those fields, then you won’t be able to insert new data.

SQL SERVER – Good, Better and Best Programming Techniques

April 28, 2007 by pinaldave

A week ago, I was invited to meeting of programmers. Subject of meeting was “Good, Better and Best Programming Techniques”. I had made small note before I went to meeting, so if I have to talk about or

Page 238: 9 Jan 01, 2007-431 Dec 31, 2007

discuss SQL Server it can come handy. Well, I did not get chance to talk on that as it was very causal and just meeting and greetings. Everybody just talked about what they think about their job. I talked very briefly about SQL Server, my current job and some funny incident at work.

Everybody laughed big when I talked about funny bug ticket I received which was about – Client does not receive Email sent by system. Well, at the end it was resolved without any programming as client did not have email address and needed to open one.

Well, here is my note which I prepared to discuss in meeting. This is not complete and is not in very details. This note contains what I think is best programming technique in SQL. There are lots to add here and many opinion are very generic to SQL and other programming languages.

Notes prepared for “Good, Better and Best Programming Techniques” meeting

Do not prefix stored procedure with SP_ prefix. As they are first searched in master database, before it is searched in any other database.

Always install latest server packs and security packs.

Make sure your SQL Server runs on optimal hardware. If your operating system supports 64 bit SQL Server, install 64 bit SQL Server on it. Raid 10 Array.

Reduce Network Traffic by using Stored Procedure. Return only required result set from database. If application needs paging it should have done in SQL Server instead of at application level.

After running query check Actual Execution Plan for cost of the query. Query can be analyzed in Database Engine Tuning Advisor.

Use User Defined Functions sparsely, use Stored Procedures instead.

Stored Procedure can achieve all the tasks UDF can do. SP provides much more features than UDFs.

Test system with realistic data rather than sample data. Realistic data provides better scenario for testing and reveals problems with real system before it goes to production.

Do not use SELECT *, use proper column names to decrease network traffic and fewer locks on table.

Avoid Cursors as it results in performance degradation. Sub Query, derived tables, CTE can perform same operation.

Reduces the use of nullable columns.

NULL columns consumes an extra byte on each column used as well as adds overhead in queries. Also NULL is not good for logic development for programmers.

Reduce deadlocks using query hints and proper logic of order in columns.

Normalized database always increases scalability and stability of the system. Do not go over 3rd normal form as it will adversely affect performance.

Use WHERE clauses to compare assertive logic. Use IN rather than NOT IN even though IN will require more value to specify in clause.

BLOBS must be stored filesystem and database should have path to them only. If path is common stored them in application variable and append with filename from the BLOBColumnName.

Always perform referential integrity checks and data validations using constraints such as the foreign key and check constraints.

Page 239: 9 Jan 01, 2007-431 Dec 31, 2007

SQL Server optimizer will use an index scan if the ORDER BY clause is on an indexed column.

Stored Procedure should return same numbers of resultset and same columns in any input parameters. Result Set of Stored Procedure should be deterministic.

Index should be created on highly selective columns, which are used in JOINS, WHERE and ORDER BY clause.

Format SQL Code. Make it readable. Wrap it.

Use Column name in ORDER BY clause instead of numbers.

Do not use TEXT or NTEXT if possible. In SQL Server 2005 use VARCHAR(MAX) or NVARCHAR(MAX).

Join tables in order that they always perform the most restrictive search first to filter out the maximum number of rows in the early phases of a multiple table join.

Remember to SET NOCOUNT ON at the beginning of your SQL bataches, stored procedures, triggers to avoid network traffic. This will also reduct the chances of error on linked server.

Do not use temp tables use CTE or Derived tables instead.

Always take backup of all the data.

Never ever work on production server.

Ask someone for help if you need it. We all need to learn.

SQL SERVER – Query to Retrieve the Nth Maximum Value

April 27, 2007 by pinaldave

Replace Employee with your table name, and Salary with your column name. Where N is the level of Salary to be determined.

SELECT *FROM Employee E1WHERE (N-1) = (SELECT COUNT(DISTINCT(E2.Salary))FROM Employee E2WHERE E2.Salary > E1.Salary)

In the above example, the inner query uses a value of the outer query in its filter condition meaning; the inner query cannot be evaluated before evaluating the outer query. So each row in the outer query is evaluated first and the inner query is run for that row.

SQL SERVER – 2005 Locking Hints and Examples

April 27, 2007 by pinaldave

Locking Hints and Examples are as follows. The usage of them is same same but effect is different.

ROWLOCKUse row-level locks when reading or modifying data.

PAGLOCKUse page-level locks when reading or modifying data.

Page 240: 9 Jan 01, 2007-431 Dec 31, 2007

TABLOCKUse a table lock when reading or modifying data.

DBLOCKUse a database lock when reading or modifying data.

UPDLOCKUPDLOCK reads data without blocking other readers, and update it later with the assurance that the data has not changed since last read.

XLOCKUse exclusive locks instead of shared locks while reading a table, and use hold locks until the end of the statement or transaction.

HOLDLOCKUse a hold lock to hold a lock until completion of the transaction, instead of releasing the lock as soon as the required table, row, or data page is no longer required.

NOLOCKThis does not lock any object. This is the default for SELECT operations. It does not apply to INSERT, UPDATE, and DELETE statements.

Examples:SELECT OrderIDFROM Orders (WITH ROWLOCK)WHERE OrderID BETWEEN 100AND 2000

UPDATE Products (WITH NOLOCK)SET ProductCat = 'Machine'WHERE ProductSubCat = 'Mac'

SQL SERVER – SELECT vs. SET Performance Comparison

April 27, 2007 by pinaldave

Usage:SELECT : Designed to return data.SET : Designed to assign values to local variables.

While testing the performance of the following two scripts in query analyzer, interesting results are discovered.

SET @foo1 = 1;SET @foo2 = 2;SET @foo3 = 3;SELECT@foo1 = 1,@foo2 = 2,@foo3 = 3;

While comparing their performance in loop SELECT statement gives better performance then SET. In other words, SET is slower than SELECT. The reason is that each SET statement runs individually and updates on values per execution, whereas the entire SELECT statement runs once and update all three values in one execution.

SET is the ANSI standard for variable assignment, SELECT is not. SET can only assign one variable at a time, SELECT can make multiple assignments at once – that gives SELECT slight speed advantage over SET. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all keeping the variable unchanged.

Page 241: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Difference Between Unique Index vs Unique Constraint

April 26, 2007 by pinaldave

Unique Index and Unique Constraint are the same. They achieve same goal. SQL Performance is same for both.

Add Unique ConstraintALTER TABLE dbo.<tablename> ADD CONSTRAINT<namingconventionconstraint> UNIQUE NONCLUSTERED(<columnname>) ON [PRIMARY]

Add Unique IndexCREATE UNIQUE NONCLUSTERED INDEX<namingconventionconstraint> ON dbo.<tablename>(<columnname>) ON [PRIMARY]

There is no difference between Unique Index and Unique Constraint. Even though syntax are different the effect is the same. Unique Constraint creates Unique Index to maintain the constraint to prevent duplicate keys. Unique Index or Primary Key Index are physical structure that maintain uniqueness over some combination of columns across all rows of a table. It is a convenient way to enforce a Unique Constraint for SQL Server.

SQL SERVER – Enable xp_cmdshell using sp_configure

April 26, 2007 by pinaldave

The xp_cmdshell option is a server configuration option that enables system administrators to control whether the xp_cmdshell extended stored procedure can be executed on a system.---- To allow advanced options to be changed.

EXEC sp_configure ’show advanced options’, 1

GO

—- To update the currently configured value for advanced options.

RECONFIGURE

GO

—- To enable the feature.

EXEC sp_configure ‘xp_cmdshell’, 1

GO

—- To update the currently configured value for this feature.

RECONFIGURE

GO

SQL SERVER – 2005 – DBCC ROWLOCK – Deprecated

Page 242: 9 Jan 01, 2007-431 Dec 31, 2007

April 26, 2007 by pinaldave

Title says all.

My search engine log says many web users are looking for DBCC ROWLOCK in SQL SERVER 2005. It is deprecated feature for SQL SERVER 2005. It is Automatically on for SQL SERVER 2005.

More Deprecated Features of SQL SERVER 2005 Refer MSDN Discontinued Database Engine Functionality in SQL Server 2005.

SQL SERVER – Alternate Fix : ERROR 1222 : Lock request time out period exceeded

April 25, 2007 by pinaldave

ERROR 1222 : Lock request time out period exceeded.

MSDN Suggests solution here.

It says find offending transaction and terminate it and run the query again. Though sometime there is requirement that we can not terminate anything. If we know which transaction is locking up resources and database, we need to still run the same transaction.

Alternate Fix/WorkAround/Solution:In this scenario following changes must be done in the offending transaction:1) Modify the Transaction use query hints (use RECOMPILE,MAXDOPhints)2) Run big Transaction in smaller transactions.3) Upgrade Hardware if possible.

SQL SERVER – ERROR Messages – sysmessages error severity level

April 25, 2007 by pinaldave

SQL ERROR Messages

Each error message displayed by SQL Server has an associated error message number that uniquely identifies the type of error. The error severity levels provide a quick reference for you about the nature of the error. The error state number is an integer value between 1 and 127; it represents information about the source that issued the error. The error message is a description of the error that occurred. The error messages are stored in the sysmessages system table.

We can see all the system messages running following statement in query analyzer.SELECT *FROM master.dbo.sysmessagesThe severity level are displayed in the table below.

0 to 10 Messages with a severity level of 0 to 10 are informational messages and not actual errors.

11 to 16Severity levels 11 to 16 are generated as a result of user problems and can be fixed by the user. For example, the error message returned in the invalid update query, used earlier, had a severity level of 16.

17Severity level 17 indicates that SQL Server has run out of a configurable resource, such as locks. Severity error 17 can be corrected by the DBA, and in some cases, by the database owner.

18 Severity level 18 messages indicate nonfatal internal software problems.19 Severity level 19 indicates that a nonconfigurable resource limit has been exceeded.20 Severity level 20 indicates a problem with a statement issued by the current process.

21 Severity level 21 indicates that SQL Server has encountered a problem that affects all the processes in a database.

22 Severity level 22 means a table or index has been damaged. To try to determine the extent of the problem, stop and restart SQL Server. If the problem is in the cache and not on the disk, the restart corrects the problem. Otherwise, use DBCC to determine the extent of the

Page 243: 9 Jan 01, 2007-431 Dec 31, 2007

damage and the required action to take.

23 Severity level 23 indicates a suspect database. To determine the extent of the damage and the proper action to take, use the DBCC commands.

24 Severity level 24 indicates a hardware problem.25 Severity level 25 indicates some type of system error.

Discontinued Database Engine Functionality in SQL Server 2008

This topic describes the Database Engine features

Page 244: 9 Jan 01, 2007-431 Dec 31, 2007

that are no longer available in SQL Server 2008.

Category Discontinued feature Replacement

Aliases sp_addalias

Replace aliases with a combination of user accounts and database roles. For more information, see CREATE USER (Transact-SQL) and CREATE ROLE (Transact-SQL). Remove aliases in upgraded databases by using sp_dropalias.

APIs Registered Servers API Replaced by a new registered servers API that supports new SQL Server 2008 features.

Backup and restore DUMP statement BACKUP

Backup and restore LOAD statement RESTORE

Backup and restore BACKUP LOG WITH NO_LOG

None. The transaction log is automatically truncated when the database is using the simple recovery model. If you must remove the log backup chain from a database, switch to the simple recovery model.

Backup and restore

BACKUP LOG WITH TRUNCATE_ONLY

None. The transaction log is automatically truncated when the database is using the simple recovery model. If you must remove the log backup chain from a database, switch to the simple recovery model.

Backup and restore BACKUP TRANSACTION BACKUP LOG

Page 245: 9 Jan 01, 2007-431 Dec 31, 2007

Compatibility level

60, 65, and 70 compatibility levels Databases must be set to at least compatibility level 80.

DBCC DBCC CONCURRENCYVIOLATION None

Groups sp_addgroup Use roles.Groups sp_changegroup Use roles.Groups sp_dropgroup Use roles.Groups sp_helpgroup Use roles.

Sample databases Northwind and pubs

Use AdventureWorks. Northwind and pubs are available as downloads, or can be copied from a previous installation of SQL Server.For more information, see AdventureWorks Sample Databases.

Tools Surface Area Configuration Tool

The Surface Area Configuration Tool is discontinued for SQL Server 2008. For more information, see Backward Compatibility.

Web Assistant

sp_makewebtask

sp_dropwebtask

sp_runwebtask

sp_enumcodepages

We recommend that you use SQL Server Reporting Services instead.

SQL SERVER – 2005 Take Off Line or Detach Database

April 25, 2007 by pinaldave

EXEC sp_dboption N'mydb', N'offline', N'true'ORALTER DATABASE [mydb] SET OFFLINE WITHROLLBACK AFTER 30 SECONDSORALTER DATABASE [mydb] SET OFFLINE WITHROLLBACK IMMEDIATE

Using the alter database statement (SQL Server 2k and beyond) is the preferred method. The rollback after statement will force currently executing statements to rollback after N seconds. The default is to wait for all currently running transactions to complete and for the sessions to be terminated. Use the rollback immediate clause to rollback transactions immediately.

SQL SERVER – TRIM() Function – UDF TRIM()

April 24, 2007 by pinaldave

SQL Server does not have function which can trim leading or trailing spaces of any string. TRIM() is very popular function in many languages. SQL does have LTRIM() and RTRIM() which can trim leading and trailing spaces respectively. I was expecting SQL Server 2005 to have TRIM() function. Unfortunately, SQL Server 2005 does not have that either. I have created very simple UDF which does the same work.

FOR SQL SERVER 2000:CREATE FUNCTION dbo.TRIM(@string VARCHAR(8000))RETURNS VARCHAR(8000)BEGINRETURN LTRIM(RTRIM(@string))ENDGO

FOR SQL SERVER 2005:CREATE FUNCTION dbo.TRIM(@string VARCHAR(MAX))RETURNS VARCHAR(MAX)BEGINRETURN LTRIM(RTRIM(@string))

Page 246: 9 Jan 01, 2007-431 Dec 31, 2007

ENDGO

Both the above UDF can be tested with following scriptSELECT dbo.TRIM(' leading trailing ')It will return string in result window as'leading trailing'

There will be no spaces around them. It is very little but useful trick.

SQL SERVER – Six Properties of Relational Tables

April 24, 2007 by pinaldave

Relational tables have six properties:

Values Are AtomicThis property implies that columns in a relational table are not repeating group or arrays. The key benefit of the one value property is that it simplifies data manipulation logic. Such tables are referred to as being in the “first normal form” (1NF).

Column Values Are of the Same KindIn relational terms this means that all values in a column come from the same domain. A domain is a set of values which a column may have. This property simplifies data access because developers and users can be certain of the type of data contained in a given column. It also simplifies data validation. Because all values are from the same domain, the domain can be defined and enforced with the Data Definition Language (DDL) of the database software.

Each Row is UniqueThis property ensures that no two rows in a relational table are identical; there is at least one column, or set of columns, the values of which uniquely identify each row in the table. Such columns are called primary keys. This property guarantees that every row in a relational table is meaningful and that a specific row can be identified by specifying the primary key value.

The Sequence of Columns is InsignificantThis property states that the ordering of the columns in the relational table has no meaning. Columns can be retrieved in any order and in various sequences. The benefit of this property is that it enables many users to share the same table without concern of how the table is organized. It also permits the physical structure of the database to change without affecting the relational tables.

The Sequence of Rows is InsignificantThis property is analogous the one above but applies to rows instead of columns. The main benefit is that the rows of a relational table can be retrieved in different order and sequences. Adding information to a relational table is simplified and does not affect existing queries.

Each Column Has a Unique NameBecause the sequence of columns is insignificant, columns must be referenced by name and not by position. A column name need not be unique within an entire database but only within the table to which it belongs.

SQL SERVER – 2005 Collation Explanation and Translation

April 24, 2007 by pinaldave

Just a day before one of our SQL SERVER 2005 needed Case-Sensitive Binary Collation. When we install SQL SERVER 2005 it gives options to select one of the many collation. I says in words like ‘Dictionary order, case-insensitive, uppercase preference’. I was confused for little while as I am used to read collation like ‘SQL_Latin1_General_Pref_Cp1_CI_AS_KI_WI’. I did some research and find following link which explains many of the SQL SERVER 2005 collation.

Complete documentation MSDN – SQL SERVER Collation

Page 247: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – Fix: Sqllib error: OLEDB Error encountered calling IDBInitialize::Initialize. hr = 0×80004005. SQLSTATE: 08001, Native Error: 17

March 16, 2007 by pinaldave

Error received:

Sqllib error: OLEDB Error encountered calling IDBInitialize::Initialize. hr = 0×80004005. SQLSTATE: 08001, Native Error: 17Error state: 1, Severity: 16Source: Microsoft OLE DB Provider for SQL ServerError message: [DBNETLIB]SQL Server does not exist or access denied

The simple fix:Microsoft SQL Server 2005 >> Configuration Tools >> SQL Server Configuration Manager >> SQL Server 2005 Network Configuration >> Enable TCP-IP.

Selecting a SQL Server Collation

This topic describes SQL Server 2008 collation options for instances of SQL Server that require compatibility with versions of SQL Server that do not use collations.

The following SQL collations

Page 248: 9 Jan 01, 2007-431 Dec 31, 2007

are listed on the Collation Settings page of the SQL Server

Page 249: 9 Jan 01, 2007-431 Dec 31, 2007

Installation Wizard.

SQL sort

order ID

Sort order name Description SQL collation

31 diction.437 Dictionary order, case-sensitive SQL_Latin1_General_Cp437_CS_AS_KI_WI

32 nocase.437 Dictionary order, case-insensitive SQL_Latin1_General_Cp437_CI_AS_KI_WI

33 nocasepr.437Dictionary order, case-insensitive, uppercase preference

SQL_Latin1_General_Pref_Cp437_CI_AS_KI_WI

34 noaccent.437 Dictionary order, case-insensitive, accent-insensitive SQL_Latin1_General_Cp437_CI_AI_KI_WI

40 cp437bin.437 Binary SQL_Latin1_General_Cp437_BIN40 cp850bin.850 Binary SQL_Latin1_General_Cp850_BIN41 diction.850 Dictionary order, case-sensitive SQL_Latin1_General_Cp850_CS_AS_KI_WI

42 nocase.850 Dictionary order, case-insensitive SQL_Latin1_General_Cp850_CI_AS_KI_WI

44 noaccent.850 Dictionary order, case-insensitive, accent-insensitive SQL_Latin1_General_Cp850_CI_AI_KI_WI

44 nocase34.850Dictionary order, case-insensitive, uppercase preference

SQL_Latin1_General_Pref_Cp850_CI_AS_KI_WI

49 nocase34.850 Strict compatibility with Version 1.x case-insensitive databases SQL_1xCompat_Cp850_CI_AS_KI_WI

51 diction.iso Dictionary order, case-sensitive SQL_Latin1_General_Cp1_CS_AS_KI_WI

52 nocase.iso Dictionary order, case-insensitive SQL_Latin1_General_Cp1_CI_AS_KI_WI

53 nocasepr.isoDictionary order, case-insensitive, uppercase preference

SQL_Latin1_General_Pref_Cp1_CI_AS_KI_WI

54 noaccent.iso Dictionary order, case-insensitive, accent-insensitive SQL_Latin1_General_Cp1_CI_AI_KI_WI

55 altdict.850 Alternate dictionary order, case-sensitive SQL_AltDiction_Cp850_CS_AS_KI_WI

56 altnocsp.850Alternate dictionary order, case-insensitive, uppercase preference

SQL_AltDiction_Pref_Cp850_CI_AS_KI_WI

57 altnoacc.850 Alternate dictionary order, case-insensitive, accent-insensitive SQL_AltDiction_Cp850_CI_AI_KI_WI

58 scan.850Scandinavian dictionary sort order, case-insensitive, uppercase preference

SQL_Scandainavian_Pref_Cp850_CI_AS_KI_WI

59 scandict.850 Scandinavian dictionary sort order, case-sensitive SQL_Scandainavian_Cp850_CS_AS_KI_WI

60 scannocase.850 Case-insensitive Scandinavian dictionary sort order, without

SQL_Scandainavian_Cp850_CI_AS_KI_WI

Page 250: 9 Jan 01, 2007-431 Dec 31, 2007

case preference

61 altnocs.850 Alternate dictionary order, case-insensitive SQL_AltDiction_Cp850_CI_AS_KI_WI

80 binary.250 Binary SQL_Latin1_General_1250_BIN81 diction.250 Dictionary order, case-sensitive SQL_Latin1_General_Cp1250_CS_AS_KI_WI

82 nocase.250 Dictionary order, case-insensitive SQL_Latin1_General_Cp1250_CI_AS_KI_WI

83 csydic.250 Czech dictionary order, case-sensitive SQL_Czech_Cp1250_CS_AS_KI_WI

84 csync.250 Czech dictionary order, case-insensitive SQL_Czech_Cp1250_CI_AS_KI_WI

85 hundic.250 Hungarian dictionary order, case-sensitive SQL_Hungarian_Cp1250_CS_AS_KI_WI

86 hunnc.250 Hungarian dictionary order, case-insensitive SQL_Hungarian_Cp1250_CI_AS_KI_WI

87 plkdic.250 Polish dictionary order, case-sensitive SQL_Polish_Cp1250_CS_AS_KI_WI

88 plknc.250 Polish dictionary order, case-insensitive SQL_Polish_Cp1250_CI_AS_KI_WI

89 romdic.250 Romanian dictionary order, case-sensitive SQL_Romanian_Cp1250_CS_AS_KI_WI

90 romnc.250 Romanian dictionary order, case-insensitive SQL_Romanian_Cp1250_CI_AS_KI_WI

91 shldic.250 Croatian dictionary order, case-sensitive SQL_Croatian_Cp1250_CS_AS_KI_WI

92 shlnc.250 Croatian dictionary order, case-insensitive SQL_Croatian_Cp1250_CI_AS_KI_WI

93 skydic.250 Slovak dictionary order, case-sensitive SQL_Slovak_Cp1250_CS_AS_KI_WI

94 skync.250 Slovak dictionary order, case-insensitive SQL_Slovak_Cp1250_CI_AS_KI_WI

95 slvdic.250 Slovenian dictionary order, case-sensitive SQL_Slovenian_Cp1250_CS_AS_KI_WI

96 slvnc.250 Slovenian dictionary order, case-insensitive SQL_Slovenian_Cp1250_CI_AS_KI_WI

104 binary.250 Binary SQL_Latin1_General_1251_BIN105 diction.251 Dictionary order, case-sensitive SQL_Latin1_General_Cp1251_CS_AS_KI_WI

106 nocase.251 Dictionary order, case-insensitive SQL_Latin1_General_Cp1251_CI_AS_KI_WI

107 ukrdic.251 Ukrainian dictionary order, case-sensitive SQL_Ukrainian_Cp1251_CS_AS_KI_WI

108 ukrnc.251 Ukrainian dictionary order, case-insensitive SQL_Ukrainian_Cp1251_CI_AS_KI_WI

112 binary.253 Binary SQL_Latin1_General_1253_BIN113 diction.253 Dictionary order, case-sensitive SQL_Latin1_General_Cp1253_CS_AS_KI_WI

114 nocase.253 Dictionary order, case-insensitive SQL_Latin1_General_Cp1253_CI_AS_KI_WI

121 graltdct.253 Dictionary order, case-sensitive, accent-sensitive SQL_Latin1_General_Cp1253_CI_AS_KI_WI

124 grnoacce.253 Dictionary order, case-insensitive, accent-insensitive SQL_Latin1_General_Cp1253_CI_AI_KI_WI

128 binary.254 Binary SQL_Latin1_General_1254_BIN129 diction.254 Dictionary order, case-sensitive SQL_Latin1_General_Cp1254_CS_AS_KI_WI

130 nocase.254 Dictionary order, case-insensitive SQL_Latin1_General_Cp1254_CI_AS_KI_WI

136 binary.255 Binary SQL_Latin1_General_1255_BIN137 diction.255 Dictionary order, case-sensitive SQL_Latin1_General_Cp1255_CS_AS_KI_WI

138 nocase.255 Dictionary order, case-insensitive SQL_Latin1_General_Cp1255_CI_AS_KI_WI

144 binary.256 Binary SQL_Latin1_General_1256_BIN145 diction.256 Dictionary order, case-sensitive SQL_Latin1_General_Cp1256_CS_AS_KI_WI

146 nocase.256 Dictionary order, case-insensitive SQL_Latin1_General_Cp1256_CI_AS_KI_WI

Page 251: 9 Jan 01, 2007-431 Dec 31, 2007

152 binary.257 Binary SQL_Latin1_General_1257_BIN153 diction.257 Dictionary order, case-sensitive SQL_Latin1_General_Cp1257_CS_AS_KI_WI

154 nocase.257 Dictionary order, case-insensitive SQL_Latin1_General_Cp1257_CI_AS_KI_WI

155 etidic.257 Estonian dictionary order, case-sensitive SQL_Estonian_Cp1257_CS_AS_KI_WI

156 etinc.257 Estonian dictionary order, case-insensitive SQL_Estonian_Cp1257_CI_AS_KI_WI

157 lvidic.257 Latvian dictionary order, case-sensitive SQL_Latvian_Cp1257_CS_AS_KI_WI

158 lvinc.257 Latvian dictionary order, case-insensitive SQL_Latvian_Cp1257_CI_AS_KI_WI

159 lthdic.257 Lithuanian dictionary order, case-sensitive SQL_Lithuanian_Cp1257_CS_AS_KI_WI

160 lthnc.257 Lithuanian dictionary order, case-insensitive SQL_Lithuanian_Cp1257_CI_AS_KI_WI

183 danonocp.isoDanish/Norwegian dictionary order, case-insensitive, uppercase preference

SQL_Danish_Pref_Cp1_CI_AS_KI_WI

184 islanocp.iso

Swedish/Finnish[Phone] dictionary order, case-insensitive, uppercase preference

SQL_SwedishPhone_Pref_Cp1_CI_AS_KI_WI

185 svf2nocp.iso.isoSwedish/Finnish[Std] dictionary order, case-insensitive, uppercase preference

SQL_SwedishStd_Pref_Cp1_CI_AS_KI_WI

186 islanocp.isoIcelandic dictionary order, case-insensitive, uppercase preference

SQL_Icelandic_Pref_Cp1_CI_AS_KI_WI

SQL SERVER – 2005 Security Best Practices – Operational and Administrative Tasks

March 21, 2007 by pinaldave

This white paper covers some of the operational and administrative tasks associated with SQL Server 2005 security and enumerates best practices and operational and administrative tasks that will result in a more secure SQL Server system.

Read the article about this paper on Microsoft TechNet.

Read/Download the white paper (doc).

SQL SERVER – Fix: Error Msg 128 The name is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.

March 22, 2007 by pinaldave

Error Message:

Server: Msg 128, Level 15, State 1, Line 3The name is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.

Causes:

This error occurs when using a column as the DEFAULT value of another column when a table is created.CREATE TABLE [dbo].[Items] ([OrderCount] INT,[ProductAmount] INT,[TotalAmount] DEFAULT ([OrderCount] + [ProductAmount])

Page 252: 9 Jan 01, 2007-431 Dec 31, 2007

)Executing this CREATE TABLE statement will generate the following error message:

Server: Msg 128, Level 15, State 1, Line 5The name ‘TotalAmount’ is not permitted in this context.Only constants, expressions, or variables allowed here.Column names are not permitted.

Solution/Workaround/Fix:

When setting the DEFAULT value of a column make sure to use only constants, expressions or variables and not another column.System functions can be used as DEFAULT values. e.g. GETDATE(), NEWID()Use Computed Column in place of Default keyword.CREATE TABLE [dbo].[Items] ([OrderCount] INT,[ProductAmount] INT,[TotalAmount] AS ([OrderCount] + [ProductAmount]))

SQL SERVER – Stored Procedure – Clean Cache and Clean Buffer

March 23, 2007 by pinaldave

Use DBCC FREEPROCCACHE to clear the procedure cache. Freeing the procedure cache would cause, for example, an ad-hoc SQL statement to be recompiled rather than reused from the cache. If observing through SQL Profiler, one can watch the Cache Remove events occur as DBCC FREEPROCCACHE goes to work. DBCC FREEPROCCACHE will invalidate all stored procedure plans that the optimizer has cached in memory and force SQL Server to compile new plans the next time those procedures are run.

Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server. DBCC DROPCLEANBUFFERS serves to empty the data cache. Any data loaded into the buffer cache due to the prior execution of a query is removed.

DBCC FREEPROCCACHEDBCC DROPCLEANBUFFERS

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record

March 25, 2007 by pinaldave

SELECT @@IDENTITYIt returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY()It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT(‘tablename’)It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

Page 253: 9 Jan 01, 2007-431 Dec 31, 2007

To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.

SQL SERVER – Fix : Error 701 There is insufficient system memory to run this query

March 27, 2007 by pinaldave

Generic Solution:Check the settings for both min server memory (MB) and max server memory (MB). If max server memory (MB) is a value close to the value of min server memory (MB), then increase the max server memory (MB) value.Check the size of the virtual memory paging file. If possible, increase the size of the file.

For SQL Server 2005:Install following HotFix and Restart Server.

Additionally following DBCC Commands can be ran to free memory:

DBCC FREESYSTEMCACHE DBCC FREESESSIONCACHE DBCC FREEPROCCACHE

SQL SERVER – Fix : Error 8101 An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON

March 28, 2007 by pinaldave

This error occurs when user has attempted to insert a row containing a specific identity value into a table that contains an identity column. Run following commands according to your SQL Statement:

Before your SQL Statement:SET IDENTITY_INSERT <tablename> ON

{YOUR SQL INSERT STATEMENT}After your SQL Statement:SET IDENTITY_INSERT <tablename> OFF

SQL SERVER – Difference between DISTINCT and GROUP BY – Distinct vs Group By

March 29, 2007 by pinaldave

This question is asked many times to me. What is difference between DISTINCT and GROUP BY?

A DISTINCT and GROUP BY usually generate the same query plan, so performance should be the same across both query constructs. GROUP BY should be used to apply aggregate operators to each group. If all you need is to remove duplicates then use DISTINCT. If you are using sub-queries execution plan for that query varies so in that case you need to check the execution plan before making decision of which is faster.

Example of DISTINCT:SELECT DISTINCT Employee, RankFROM Employees

Example of GROUP BY:SELECT Employee, RankFROM EmployeesGROUP BY Employee, Rank

Example of GROUP BY with aggregate function:SELECT Employee, Rank, COUNT(*) EmployeeCount

Page 254: 9 Jan 01, 2007-431 Dec 31, 2007

FROM EmployeesGROUP BY Employee, Rank

SQL SERVER – Index Seek Vs. Index Scan (Table Scan)

March 30, 2007 by pinaldave

Index Scan retrieves all the rows from the table. Index Seek retrieves selective rows from the table.

Index Scan:Since a scan touches every row in the table whether or not it qualifies, the cost is proportional to the total number of rows in the table. Thus, a scan is an efficient strategy if the table is small or if most of the rows qualify for the predicate.

Index Seek:Since a seek only touches rows that qualify and pages that contain these qualifying rows, the cost is proportional to the number of qualifying rows and pages rather than to the total number of rows in the table.

Index Scan is nothing but scanning on the data pages from the first page to the last page. If there is an index on a table, and if the query is touching a larger amount of data, which means the query is retrieving more than 50 percent or 90 percent of the data, and then optimizer would just scan all the data pages to retrieve the data rows. If there is no index, then you might see a Table Scan (Index Scan) in the execution plan.

Index seeks are generally preferred for the highly selective queries. What that means is that the query is just requesting a fewer number of rows or just retrieving the other 10 (some documents says 15 percent) of the rows of the table.

In general query optimizer tries to use an Index Seek which means that optimizer has found a useful index to retrieve recordset. But if it is not able to do so either because there is no index or no useful indexes on the table then SQL Server has to scan all the records that satisfy query condition.

SQL SERVER – 2005 Best Practices Analyzer (February 2007 CTP)

March 31, 2007 by pinaldave

Microsoft has released a tool called the Microsoft SQL Server Best Practices Analyzer. With this tool, you can test and implement a combination of SQL Server best practices and then implement them on your SQL Server. The SQL Server 2005 Best Practices Analyzer gathers data from Microsoft Windows and SQL Server configuration settings. Best Practices Analyzer uses a predefined list of SQL Server 2005 recommendations and best practices to determine if there are potential issues in the database environment.

Download SQL Server 2005 Best Practices Analyzer (February 2007 Community Technology Preview)

Abstract courtesy : Microsoft

SQL SERVER – TempDB is Full. Move TempDB from one drive to another drive.

April 1, 2007 by pinaldave

If you come across following errors in log file, please follow the direction below.Source: MSSQLSERVEREvent ID: 17052Description: The LOG FILE FOR DATABASE 'tempdb' IS FULL.Back up the TRANSACTION LOG FOR the DATABASE TO freeup SOME LOG SPACE

Make sure that TempDB is set to autogrow and do not set a maximum size for TempDB. If the current drive is too full to allow autogrow events, then arrange a bigger drive, or add files to TempDB on another device (using ALTER DATABASE as described below and allow those files to autogrow.

Page 255: 9 Jan 01, 2007-431 Dec 31, 2007

Move TempDB from one drive to another drive. There are major two reasons why TempDB needs to move from one drive to other drive.1) TempDB grows big and the existing drive does not have enough space.2) Moving TempDB to another file group which is on different physical drive helps to improve database disk read, as they can be read simultaneously.

Follow direction below exactly to move database and log from one drive (c:) to another drive (d:) and (e:).

Open Query Analyzer and connect to your server. Run this script to get the names of the files used for TempDB.USE TempDBGOEXEC sp_helpfileGO

Results will be something like:name fileid filename filegroup size——- —— ————————————————————– ———- ——-tempdev 1 C:Program FilesMicrosoft SQL ServerMSSQLdatatempdb.mdf PRIMARY 16000 KBtemplog 2 C:Program FilesMicrosoft SQL ServerMSSQLdatatemplog.ldf NULL 1024 KBalong with other information related to the database. The names of the files are usually tempdev and demplog by default. These names will be used in next statement. Run following code, to move mdf and ldf files.USE masterGOALTER DATABASE TempDB MODIFY FILE(NAME = tempdev, FILENAME = 'd:datatempdb.mdf')GOALTER DATABASE TempDB MODIFY FILE(NAME = templog, FILENAME = 'e:datatemplog.ldf')GO

The definition of the TempDB is changed. However, no changes are made to TempDB till SQL Server restarts. Please stop and restart SQL Server and it will create TempDB files in new locations.

SQL SERVER – 2005 – Performance Dashboard Reports

April 2, 2007 by pinaldave

The Microsoft SQL Server 2005 Performance Dashboard Reports are used to monitor and resolve performance problems on your SQL Server 2005 database server. The SQL Server instance being monitored and the Management Studio client used to run the reports must both be running SP2 or later.

Common performance problems that the dashboard reports may help to resolve include:- CPU bottlenecks (and what queries are consuming the most CPU)- IO bottlenecks (and what queries are performing the most IO).- Index recommendations generated by the query optimizer (missing indexes)- Blocking- Latch contention

The SQL Server 2005 Performance Dashboard Reports only use Dynamic Management Views and Catalog Views. They do not poll performance counters from the OS, nor do they store a history of your server’s performance over time. These are very light-weight reports that will help diagnose performance problems as they are occurring.

Download SQL Server 2005 Performance Dashboard Reports

SQL SERVER – T-SQL Paging Query Technique Comparison – SQL 2000 vs SQL 2005

April 3, 2007 by pinaldave

I was doing paging in SQL Server 2000 using Temp Table or Derived Tables. I decided to checkout new function ROW_NUMBER() in SQL Server 2005. ROW_NUMBER() returns the sequential number of a row

Page 256: 9 Jan 01, 2007-431 Dec 31, 2007

within a partition of a result set, starting at 1 for the first row in each partition. I have compared both the following query on SQL Server 2005.

SQL 2005 Paging Method

USE AdventureWorksGODECLARE @StartRow INTDECLARE @EndRow INT SET @StartRow = 120 SET @EndRow = 140

SELECT FirstName, LastName, EmailAddress FROM ( SELECT PC.FirstName, PC.LastName, PC.EmailAddress, ROW_NUMBER() OVER( ORDER BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumber FROM Person.Contact PC) PersonContact WHERE RowNumber > @StartRow AND RowNumber < @EndRow ORDER BY FirstName, LastName, EmailAddressGO

SQL 2000 Paging Method

USE AdventureWorksGODECLARE @StartRow INTDECLARE @EndRow INT SET @StartRow = 120 SET @EndRow = 140

CREATE TABLE #tables (RowNumber INT IDENTITY(1,1), FirstName VARCHAR(100), LastName VARCHAR(100), EmailAddress VARCHAR(100))INSERT INTO #tables (FirstName, LastName, EmailAddress) SELECT PC.FirstName, PC.LastName, PC.EmailAddress FROM Person.Contact PC ORDER BY FirstName, LastName, EmailAddress

SELECT FirstName, LastName, EmailAddress FROM #tables WHERE RowNumber > @StartRow AND RowNumber < @EndRowDROP TABLE #tablesGO

While running both the query at same time in query analyzer and comparing execution plan I have discovered that SQL 2005 query method cost is 46% and SQL 2000 query method cost is 54%. Looking at client Statistics I noticed significant improvement in Time Statistics.

Update (6/11/2007) : Extention of this article is published SQL SERVER – 2005 T-SQL Paging Query Technique Comparison (OVER and ROW_NUMBER()) – CTE vs. Derived Table

SQL SERVER – 2005 T-SQL Paging Query Technique Comparison (OVER and ROW_NUMBER()) – CTE vs. Derived Table

June 11, 2007 by pinaldave

I have received few emails and comments about my post SQL SERVER – T-SQL Paging Query Technique Comparison – SQL 2000 vs SQL 2005. The main question was is this can be done using CTE? Absolutely! What about Performance? It is same! Please refer above mentioned article for history of paging.

Page 257: 9 Jan 01, 2007-431 Dec 31, 2007

SQL 2005 Paging Method Using Derived TableUSE AdventureWorksGODECLARE @StartRow INTDECLARE @EndRow INTSET @StartRow = 120SET @EndRow = 140SELECT FirstName, LastName, EmailAddressFROM (SELECT PC.FirstName, PC.LastName, PC.EmailAddress,ROW_NUMBER() OVER(ORDER BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumberFROM Person.Contact PC) PersonContactWHERE RowNumber > @StartRowAND RowNumber < @EndRowORDER BY FirstName, LastName, EmailAddressGO

SQL 2005 Paging Method Using CTEUSE AdventureWorksGODECLARE @StartRow INTDECLARE @EndRow INTSET @StartRow = 120;SET @EndRow = 140;WITH PersonContact AS(SELECT PC.FirstName, PC.LastName, PC.EmailAddress,ROW_NUMBER() OVER(ORDER BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumberFROM Person.Contact PC)SELECT FirstName, LastName, EmailAddressFROM PersonContactWHERE RowNumber > @StartRowAND RowNumber < @EndRowORDER BY FirstName, LastName, EmailAddressGO

Following Image of Execution Plan displays that the performance for both of them is same with regarding to each other in one batch. This MAY NOT be true when there is complex query in issue. For most of the time, it is will be same.

Page 258: 9 Jan 01, 2007-431 Dec 31, 2007

Reference : Pinal Dave (http://blog.SQLAuthority.com) , SQL SERVER – T-SQL Paging Query Technique Comparison – SQL 2000 vs SQL 2005

SQL SERVER – Fix: HResult 0×274D, Level 16, State 1 Error: Microsoft SQL Native Client : Login timeout expired.

April 4, 2007 by pinaldave

While Working with SQLCMD in SQL Server 2005 I encountered following error.HResult 0x274D, LEVEL 16, State 1

TCP Provider: No connection could be made because the targetmachine actively refused it.Sqlcmd: Error: Microsoft SQL Native Client : An error hasoccurred WHILE establishing a connection TO the server. WHENconnecting TO SQL Server2005, this failure maybe caused BY the fact that under the DEFAULTsettings SQL Server does NOT allow remote connections.Sqlcmd: Error: Microsoft SQL Native Client : Login timeout

Solution/Fix/WorkAround:By default SQL Server 2005 has TCP/IP connections disabled. To enable TCP/IP support, use the SQL Server Configuration Manager tool, select SQL Server 2005 Network Configuration, select Protocols, double-click onTCP/IP, and turn on Enabled.

SQL SERVER – Performance Optimization of SQL Query and FileGroups

April 5, 2007 by pinaldave

It is suggested to place transaction logs on separate physical hard drives. In this manner, data can be recovered up to the second in the event of a media failure.

Page 259: 9 Jan 01, 2007-431 Dec 31, 2007

In SQL 2005 When database is created without specifying a transaction log size, the transaction log will be re-sized to 25 percent of the size of data files.

Tables and their non-clustered indexes separated into separate file groups can improve performance, because modifications to the table can be written to both the table and the index at the same time.

If tables and their corresponding indexes in a different file group, they must be backed up the two file groups as a single unit as they cannot be backed up separately.

Set a reasonable size of your database and transaction log (25% of database size).

Leave the Autogrow feature ON for the data files and for the log files with reasonable size of autogrow increment.

Don’t set the autoshrink feature run the task during off-peak hours.

Place the log files on other physical disk arrays than those with the data files to improve I/O Performance.

SQL SERVER – DBCC Commands Introduced in SQL Server 2005

April 7, 2007 by pinaldave

SQL Server 2005 has introduced following two documented and five undocumented DBCC Commands. I was able to find documentation for only first one online. If you find any documentation of any other DBCC Commands please add comments. It will be helpful to all of us.

Documented:

freesessioncache () — no parametersFlushes the distributed query connection cache used by distributed queries against an instance of Microsoft SQL Server. View Details

requeststats ({clear} | {setfastdecayrate, rate} | {setslowdecayrate, rate})

UnDocumented:

mapallocunit (I8AllocUnitId | {I4part, I2part})

metadata ({‘print’ [, printopt = {0 |1}] | ‘drop’ | ‘clone’ [, '' | ....]}, {‘object’ [, 'type',...}, {Id | Name}, [{Ownerid | Ownername}], [{Dbid | Dbname}]])

optimizer_whatif property, value

persiststackhash (hashfile, BUFLATCH_TIMEOUT | ATTENTION | OUTOFLOCKS | LATCH_ATTN | OUTOFLOG | OUTOFMEM | SOS [, SKIPLAST | INCLUDELAST])

semetadata (object id | name, index id | name [, partition id])

SQL SERVER – Fix: Server: Msg 7391, Level 16, State 1, Line 1

April 6, 2007 by pinaldave

I have received this error many times on different servers in my careers. There is no single fix for this Error. Server: Msg 7391, Level 16, State 1, Line 1 can happen due to many reasons. I have used various of this reasons with few of my servers. Please refer them and try them one by one. One of them should be applicable to your problem.

Page 260: 9 Jan 01, 2007-431 Dec 31, 2007

You may receive a 7391 error message in SQLOLEDB when you run a distributed transaction against a linked server after you install Windows XP Service Pack 2 or Windows XP Tablet PC Edition 200. View Article.

INFO: Configuring Microsoft Distributed Transaction Coordinator (DTC) to Work Through a Firewall. View Article.

Fix/Workaround/Solution:Not all memory is available when AWE is enabled on a computer that is running a 32-bit version of SQL Server 2000 SP4. View Article.

You receive a “Server: Msg 7391″ error message when you try to perform a distributed transaction by using a Microsoft OLE DB Provider for DB2 linked server in SQL Server. View Article.

Once the error happened when I was updating local table from link server table columns. I was able to resolve the error by inserting linked server table columns to local temporary table and update local table from local temporary table.

SQL SERVER – Search Text Field – CHARINDEX vs PATINDEX

April 8, 2007 by pinaldave

We can use either CHARINDEX or PATINDEX to search in TEXT field in SQL SERVER. The CHARINDEX and PATINDEX functions return the starting position of a pattern you specify.

Both functions take two arguments. With PATINDEX, you must include percent signs before and after the pattern, unless you are looking for the pattern as the first (omit the first %) or last (omit the last %) characters in a column. For CHARINDEX, the pattern cannot include wildcard characters. The second argument is a character expression, usually a column name, in which Adaptive Server searches for the specified pattern.

Example of CHARINDEX:USE AdventureWorks;GOSELECT CHARINDEX('ensure', DocumentSummary)FROM Production.DocumentWHERE DocumentID = 3;GO

Examples of PATINDEX:USE AdventureWorks;GOSELECT PATINDEX('%ensure%',DocumentSummary)FROM Production.DocumentWHERE DocumentID = 3;GO

Summary:PATINDEX is CHARINDEX + WildCard Search. Use either of them depending your need.

SQL SERVER – 2005 Reserved Keywords

April 9, 2007 by pinaldave

Microsoft SQL Server 2005 uses reserved keywords for defining, manipulating, and accessing databases. Reserved keywords are part of the grammar of the Transact-SQL language that is used by SQL Server to parse and understand Transact-SQL statements and batches. It is not legal to include the reserved keywords in a Transact-SQL statement in any location except that defined by SQL Server. No objects in the database should be given a name that matches a reserved keyword. Although it is syntactically possible to use SQL Server reserved keywords as identifiers and object names in Transact-SQL scripts, you can do this only by using delimited identifiers.

Page 261: 9 Jan 01, 2007-431 Dec 31, 2007

Please use Microsoft MSDN BOL to see all the Reserved Keywords. The text above has been referenced from MSDN BOL.

SQL SERVER – SP Performance Improvement without changing T-SQL

April 10, 2007 by pinaldave

There are two ways, which can be used to improve the performance of Stored Procedure (SP) without making T-SQL changes in SP.

1. Do not prefix your Stored Procedure with sp_. In SQL Server, all system SPs are prefixed with sp_. When any SP is called which begins sp_ it is looked into masters database first before it is looked into the database it is called in.

2. Call your Stored Procedure prefixed with dbo.SPName – fully qualified name. When SP are called prefixed with dbo. or database.dbo. it will prevent SQL Server from placing a COMPILE lock on the procedure. While SP executes it determines if all objects referenced in the code have the same owners as the objects in the current cached procedure plan.

SQL SERVER – 2005 – Silent Installation – Unattended Installation

April 10, 2007 by pinaldave

Silent SQL Server 2005 Installation is possible in two steps.

1) Creating an .ini fileThe SQL Server CD contains a template file called template.ini . Based on that create another required .ini file which includes a single [Options] section containing multiple parameters, each relating to a different feature or configuration setting.

2) Run Setup on command promptOn command prompt type following script

setup.exe /settings <path TO .ini FILE>

If location of sqlinstall.ini file is at C:\SQLSetup folder. The command to initiate silent installation is:

setup.exe /settings C:SQLSetup sqlinstall.ini

Specify the /qn switch to perform a silent installation (with no dialog boxes) or the /qb switch to specify that only progress dialog boxes should be displayed.

SQL SERVER – 2005 – Explanation of TRY…CATCH and ERROR Handling

April 11, 2007 by pinaldave

SQL Server 2005 offers a more robust set of tools for handling errors than in previous versions of SQL Server. Deadlocks, which are virtually impossible to handle at the database level in SQL Server 2000, can now be handled with ease. By taking advantage of these new features, you can focus more on IT business strategy development and less on what needs to happen when errors occur. In SQL Server 2005, @@ERROR variable is no longer needed after every statement executed, as was the case in SQL Server 2000. SQL Server 2005 provides the TRY…CATCH construct, which is already present in many modern programming languages. TRY/CATCH helps to write logic separate the action and error handling code. The code meant for the action is enclosed in the TRY block and the code for error handling is enclosed in the CATCH block. In case the code within the TRY block fails, the control automatically jumps to the CATCH block, letting the transaction roll back and resume execution. In addition to this, the CATCH block captures and provides error information that shows you the ID, message text, state, severity and transaction state of an error.

Functions to be used in CATCH block are :

ERROR_NUMBER: returns the error number, and is the same value of @@ERROR.

Page 262: 9 Jan 01, 2007-431 Dec 31, 2007

ERROR_SEVERITY: returns the severity level of the error that invoked the CATCH block. ERROR_STATE: returns the state number of the error. ERROR_LINE: returns the line number where the error occurred. ERROR_PROCEDURE: returns the name of the stored procedure or trigger for which the error

occurred. ERROR_MESSAGE: returns the full message text of the error. The text includes the values supplied

for any substitutable parameters, such as lengths, object names, or times.

You can use these functions anywhere inside a CATCH block, and they will return information regarding the error that has occurred. These functions will return the value null outside of the CATCH block.

Syntax:BEGIN TRY{ sql_statement |statement_block }END TRYBEGIN CATCH{ sql_statement |statement_block }END CATCH

The TRY or CATCH block can contain a single T-SQL statement or a series of statements. The CATCH block must follow immediately after the TRY block. The TRY/CATCH block cannot span more than a single batch. In addition, TRY/CATCH block cannot span an IF/ELSE statement.

Example of TRY…CATCH:BEGIN TRYDECLARE @X INT---- Divide by zero to generate ErrorSET @X = 1/0PRINT 'Command after error in TRY block'END TRYBEGIN CATCHPRINT 'Error Detected'END CATCHPRINT 'Command after TRY/CATCH blocks'Above code will return following result:

Error DetectedCommand after TRY/CATCH blocks

If all the statements within the TRY block are executed successfully, then processing does not enter the CATCH block, but instead skips over the CATCH block and executes the first statement following the END CATCH statement. Removing SET statement in above code PRINT ‘Error Detected’ statement is not executed, but the PRINT statement within the TRY block is executed, as well as the PRINT statement after the TRY/CATCH block. TRY/CATCH blocks can be nested.

Limitation of TRY…CATCH:

Compiled errors are not caught. Deferred name resolution errors created by statement level recompilations. (If process is

terminated by Kill commands or broken client connections TRY…CATCH will be not effective) Errors with a severity greater than 10 that do not terminate their database connection are caught

in the TRY/CATCH block.

For errors that are not trapped, SQL Server 2005 passes control back to the application immediately, without executing any CATCH block code.

Similar example of TRY…CATCH which includes all the ERROR functions:USE AdventureWorks;GOBEGIN TRY-- Generate a divide-by-zero error.SELECT 1/0;

Page 263: 9 Jan 01, 2007-431 Dec 31, 2007

END TRYBEGIN CATCHSELECTERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage;END CATCH;GO

SQL SERVER – UDF – User Defined Function to Extract Only Numbers From String

April 11, 2007 by pinaldave

Following SQL User Defined Function will extract/parse numbers from the string.CREATE FUNCTION ExtractInteger(@String VARCHAR(2000))RETURNS VARCHAR(1000)ASBEGINDECLARE @Count INTDECLARE @IntNumbers VARCHAR(1000)SET @Count = 0SET @IntNumbers = ''

WHILE @Count <= LEN(@String)BEGINIF SUBSTRING(@String,@Count,1) >= '0'AND SUBSTRING(@String,@Count,1) <= '9'BEGINSET @IntNumbers = @IntNumbers + SUBSTRING(@String,@Count,1)ENDSET @Count = @Count + 1END

RETURN @IntNumbersENDGO

Run following script in query analyzer.SELECT dbo.ExtractInteger('My 3rd Phone Number is 323-111-CALL')GO

It will return following values.3323111

SQL SERVER – Running 64 bit SQL SERVER 2005 on 32 bit Operating System

April 12, 2007 by pinaldave

Few days ago, I have received email from users asking question :How to run 64 bit SQL SERVER 2005 on 32 bit operating system?

NO. It is not possible. 64 bit SQL Server can not run on 32 bit operating system.

It is true other way. SQL Server 32 bit can run on 64 bit operating system.

Read additional documentation on : 64-bit Computing with SQL Server 2005

SQL SERVER – Fix : Error: 3902, Severity: 16; State: 1 : The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

Page 264: 9 Jan 01, 2007-431 Dec 31, 2007

April 12, 2007 by pinaldave

SQL Server Integration Services Error : The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION. (Microsoft OLE DB Provider for SQL Server)

Fix/Workaround/Solution:

Option 1:To work around this problem, do not call the stored procedure by using ODBC Call syntax. You can call the stored procedure in may ways by using ADO. One of the methods is to call a stored procedure by using a command object. (View Example)

Option 2:If the sql statements are likeBEGIN TRAN

SQL Statements

END TRAN

SET “RetainSameConnection” property on the connection manager to true. This will fix the problem.

SQL SERVER – Fix : Error 1702 CREATE TABLE failed because column in table exceeds the maximum of columns

April 12, 2007 by pinaldave

Error Received:

Error 1702 CREATE TABLE failed because column in table exceeds the maximum of columns

SQL Server 2000 supports table with maximum 1024 columns. This errors happens when we try to create table with 1024 columns or try to add columns to table which exceeds more than 1024.

Fix/Solution/WorkAround:Reduce the number of columns in the table to 1,024 or less.

SQL SERVER – 2005 – Disable Triggers – Drop Triggers

April 13, 2007 by pinaldave

There are two ways to prevent trigger from firing.

1) Drop TriggerExample:DROP TRIGGER TriggerNameGO

2) Disable TriggerDML trigger can be disabled two ways. Using ALETER TABLE statement or use DISABLE TRIGGER. I prefer DISABLE TRIGGER statement.Syntax:DISABLE TRIGGER { [ schema . ] trigger_name[ ,...n ] | ALL }ON { OBJECT_NAME | DATABASE | ALL SERVER } [ ; ]Example:DISABLE TRIGGER TriggerName ON TableName

SQL SERVER – Script to Find SQL Server on Network

Page 265: 9 Jan 01, 2007-431 Dec 31, 2007

April 13, 2007 by pinaldave

I manage lots of SQL Servers. Many times I forget how many server I have and what are their names. New servers are added frequently and old servers are replaced with powerful servers. I run following script to check if server is properly set up and announcing itself. This script requires execute permissions on XP_CMDShell.

CREATE TABLE #servers(sname VARCHAR(255))INSERT #servers (sname)EXEC master..xp_CMDShell 'ISQL -L'DELETEFROM #serversWHERE sname='Servers:'OR sname IS NULLSELECT LTRIM(sname)FROM #serversDROP TABLE #servers

SQL SERVER – Stored Procedures Advantages and Best Advantage

April 13, 2007 by pinaldave

There are many advantages of Stored Procedures. I was once asked what do I think is the most important feature of Stored Procedure? I have to pick only ONE. It is tough question.I answered : Execution Plan Retention and Reuse (SP are compiled and their execution plan is cached and used again to when the same SP is executed again)

Not to mentioned I received the second question following my answer : Why? Because all the other advantage known (they are mentioned below) of SP can be achieved without using SP. Though Execution Plan Retention and Reuse can only be achieved using Stored Procedure only.

Execution plan retention and reuse Query auto-parameterization Encapsulation of business rules and policies Application modularization Sharing of application logic between applications Access to database objects that is both secure and uniform Consistent, safe data modification Network bandwidth conservation Support for automatic execution at system start-up Enhanced hardware and software capabilities Improved security Reduced development cost and increased reliability Centralized security, administration, and maintenance for common routines

SQL SERVER – Fix : Error: 18452 Login failed for user ‘(null)’. The user is not associated with a trusted SQL Server connection.

April 14, 2007 by pinaldave

Some errors never got old. I have seen many new DBA or Developers struggling with this errors.

Error: 18452 Login failed for user ‘(null)’. The user is not associated with a trusted SQL Server connection.

Fix/Solution/Workaround:Change the Authentication Mode of the SQL server from “Windows Authentication Mode (Windows Authentication)”to “Mixed Mode (Windows Authentication and SQL Server Authentication)”.

Run following script in SQL Analyzer to change the authentication

Page 266: 9 Jan 01, 2007-431 Dec 31, 2007

LOGIN sa ENABLEGOALTER LOGIN sa WITH PASSWORD = '<password>'GO

OR

In Object Explorer, expand Security, expand Logins, right-click sa, and then click Properties. On the General page, you may have to create and confirm a password for the sa login. On the Status page, in the Login section, click Enabled, and then click OK.

SQL SERVER – CASE Statement/Expression Examples and Explanation

April 14, 2007 by pinaldave

CASE expressions can be used in SQL anywhere an expression can be used. Example of where CASE expressions can be used include in the SELECT list, WHERE clauses, HAVING clauses, IN lists, DELETE and UPDATE statements, and inside of built-in functions.

Two basic formulations for CASE expression 1) Simple CASE expressions A simple CASE expression checks one expression against multiple values. Within a SELECT statement, a simple CASE expression allows only an equality check; no other comparisons are made. A simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency. If these expressions are equivalent, the expression in the THEN clause will be returned.

Syntax:CASE expressionWHEN expression1 THEN expression1[[WHEN expression2 THEN expression2] [...]][ELSE expressionN]ENDExample:DECLARE @TestVal INTSET @TestVal = 3SELECTCASE @TestValWHEN 1 THEN 'First'WHEN 2 THEN 'Second'WHEN 3 THEN 'Third'ELSE 'Other'END

2) Searched CASE expressionsA searched CASE expression allows comparison operators, and the use of AND and/or OR between each Boolean expression. The simple CASE expression checks only for equivalent values and can not contain Boolean expressions. The basic syntax for a searched CASE expressions is shown below:

Syntax:CASEWHEN Boolean_expression1 THEN expression1[[WHEN Boolean_expression2 THEN expression2] [...]][ELSE expressionN]ENDExample:DECLARE @TestVal INTSET @TestVal = 5SELECTCASEWHEN @TestVal <=3 THEN 'Top 3'ELSE 'Other'END

SQL SERVER – 64 bit Architecture and White Paper

Page 267: 9 Jan 01, 2007-431 Dec 31, 2007

April 14, 2007 by pinaldave

In supportability, manageability, scalability, performance, interoperability, and business intelligence, SQL Server 2005 provides far richer 64-bit support than its predecessor. This paper describes these enhancements. Read the original paper here. Following abstract is taken from the same paper. Another interesting article on 64-bit Computing with SQL Server 2005 is here.

The primary differences between the 64-bit and 32-bit versions of SQL Server 2005 are derived from the benefits of the underlying 64-bit architecture. Some of these are:

The 64-bit architecture offers a larger directly-addressable memory space. SQL Server 2005 (64-bit) is not bound by the memory limits of 32-bit systems. Therefore, more memory is available for performing complex queries and supporting essential database operations.

The 64-bit processor provides enhanced parallelism, thereby providing more linear scalability and support for up to 64 processors, and yielding stronger returns per processor as compared to 32-bit systems.

The improved bus architecture enhances performance by moving more data between cache and processors in shorter periods.

A larger on-die cache allows for faster completion of user requests and more efficient use of processor time.

SQL SERVER – Fix : Error: 1418 – Microsoft SQL Server – The server network address can not be reached or does not exist. Check the network address name and reissue the command

April 22, 2007 by pinaldave

Error: 1418 – Microsoft SQL Server – The server network address can not be reached or does not exist. Check the network address name and reissue the command

The server network endpoint did not respond because the specified server network address cannot be reached or does not exist.

Fix/Workaround/Solution:

Step 1) Your system Firewall should not block SQL Server port.

Step 2) Go to Computer Management >> Service and Application >> SQL Server 2005 Configuration >> Network ConfigurationEnable TCP/IP protocol. Make sure that SQL SERVER port is by Default 1433.

Just to make sure follow one more step which may or may not be necessary.

Step 3) Go to Computer Management >> Service and Application >> SQL Server 2005 Configuration >> Client ConfigurationEnable TCP/IP protocol.

SQL SERVER – Simple Example of Cursor

January 1, 2007 by pinaldave

UPDATE: For working example using AdventureWorks visit : SQL SERVER – Simple Example of Cursor – Sample Cursor Part 2

This is the simplest example of the SQL Server Cursor. I have used this all the time for any use of Cursor in my T-SQL.DECLARE @AccountID INTDECLARE @getAccountID CURSORSET @getAccountID = CURSOR FORSELECT Account_IDFROM AccountsOPEN @getAccountID

Page 268: 9 Jan 01, 2007-431 Dec 31, 2007

FETCH NEXTFROM @getAccountID INTO @AccountIDWHILE @@FETCH_STATUS = 0BEGINPRINT @AccountIDFETCH NEXTFROM @getAccountID INTO @AccountIDENDCLOSE @getAccountIDDEALLOCATE @getAccountID

SQL SERVER – Query to find number Rows, Columns, ByteSize for each table in the current database – Find Biggest Table in Database

January 10, 2007 by pinaldave

USE DatabaseNameGOCREATE TABLE #temp (table_name sysname ,row_count INT,reserved_size VARCHAR(50),data_size VARCHAR(50),index_size VARCHAR(50),unused_size VARCHAR(50))SET NOCOUNT ONINSERT #tempEXEC sp_msforeachtable 'sp_spaceused ''?'''SELECT a.table_name,a.row_count,COUNT(*) AS col_count,a.data_sizeFROM #temp aINNER JOIN information_schema.columns bON a.table_name collate database_default= b.table_name collate database_defaultGROUP BY a.table_name, a.row_count, a.data_sizeORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESCDROP TABLE #temp

SQL SERVER – Query Analyzer Shortcuts

January 20, 2007 by pinaldave

Download Query Analyzer Shortcuts (PDF)

Shortcut Function Shortcut Function

ALT+BREAK Cancel a query CTRL+SHIFT+F2 Clear all bookmarks

ALT+F1 Database object information CTRL+SHIFT+INSERT Insert a template

ALT+F4 Exit CTRL+SHIFT+L Make selection lowercase

CTRL+A Select all CTRL+SHIFT+M Replace template parameters

CTRL+B Move the splitter CTRL+SHIFT+P Open

Page 269: 9 Jan 01, 2007-431 Dec 31, 2007

CTRL+C Copy CTRL+SHIFT+R Remove comment

CTRL+D Display results in grid format CTRL+SHIFT+S Show client statistics

CTRL+Delete Delete through the end of the line CTRL+SHIFT+T Show server trace

CTRL+E Execute query CTRL+SHIFT+U Make selection uppercase

CTRL+F Find CTRL+T Display results in text format

CTRL+F2 Insert/remove bookmark CTRL+U Change database

CTRL+F4 Disconnect CTRL+V Paste

CTRL+F5 Parse query and check syntax CTRL+W Window selector

CTRL+G Go to line CTRL+X Delete

CTRL+H Replace CTRL+Z Undo

CTRL+I Index Tuning Wizard F1 Help for Query Analyzer

CTRL+K Display/hide execution plan F2 Move to next bookmark

CTRL+L Display execution plan F3 Repeat last search

CTRL+N New query window F4 Object Search

CTRL+O Connect F5 Execute a query

CTRL+P Print F6 Switch between query and result panes

CTRL+R Show/Hide results pane F8 Show/hide Object Browser

CTRL+S Save SHIFT+F1 Transact-SQL help

CTRL+SHIFT+0 Show options SHIFT+F2 Move to previous bookmark

CTRL+SHIFT+C Comment out code SHIFT+TAB Decrease indent

CTRL+SHIFT+DEL Clear the active Editor pane SHIFT+F6 Switch panes

CTRL+SHIFT+F Save results to file TAB Increase indent

Download the PDF

SQL SERVER – FIX : Error 15023: User already exists in current database.

February 15, 2007 by pinaldave

Error 15023: User already exists in current database.

1) This is the best Solution.First of all run following T-SQL Query in Query Analyzer. This will return all the existing users in database in result pan.USE YourDBGOEXEC sp_change_users_login 'Report'GO

Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Auto_Fix’ attribute will create the user in SQL Server instance if it does not exist. In following example ‘ColdFusion’ is UserName, ‘cf’ is Password. Auto-Fix links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins.USE YourDBGOEXEC sp_change_users_login 'Auto_Fix', 'ColdFusion', NULL, 'cf'GO

Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Update_One’ links the

Page 270: 9 Jan 01, 2007-431 Dec 31, 2007

specified user in the current database to login. login must already exist. user and login must be specified. password must be NULL or not specifiedUSE YourDBGOEXEC sp_change_users_login 'update_one', 'ColdFusion', 'ColdFusion'GO

2) If login account has permission to drop other users, run following T-SQL in Query Analyzer. This will drop the user.USE YourDBGOEXEC sp_dropuser 'ColdFusion'GO

Create the same user again in the database without any error.

Stored Procedure 1:/*Following Stored Procedure will fix all the Orphan users in databaseby mapping them to username already exist for user on server.This SP is required when user has been created at server level but doesnot show up as user in database.*/CREATE PROCEDURE dbo.spDBA_FixOrphanUsersASDECLARE @username VARCHAR(25)DECLARE GetOrphanUsers CURSORFORSELECT UserName = nameFROM sysusersWHERE issqluser = 1AND (sid IS NOT NULLAND sid <> 0x0)AND SUSER_SNAME(sid) IS NULLORDER BY nameOPEN GetOrphanUsersFETCH NEXTFROM GetOrphanUsersINTO @usernameWHILE @@FETCH_STATUS = 0BEGINIF @username='dbo'EXEC sp_changedbowner 'sa'ELSEEXEC sp_change_users_login 'update_one', @username, @usernameFETCH NEXTFROM GetOrphanUsersINTO @usernameENDCLOSE GetOrphanUsersDEALLOCATE GetOrphanUsersGO

Stored Procedure 2:/*Following Stored Procedure will fix all the Orphan users in databaseby creating the server level user selecting same password as username.Make sure that you change all the password once users are created*/CREATE PROCEDURE dbo.spDBA_FixOrphanUsersPassWordASDECLARE @username VARCHAR(25)DECLARE @password VARCHAR(25)DECLARE GetOrphanUsers CURSORFORSELECT UserName = nameFROM sysusersWHERE issqluser = 1AND (sid IS NOT NULLAND sid <> 0x0)AND SUSER_SNAME(sid) IS NULLORDER BY nameOPEN GetOrphanUsers

Page 271: 9 Jan 01, 2007-431 Dec 31, 2007

FETCH NEXTFROM GetOrphanUsersINTO @usernameSET @password = @usernameWHILE @@FETCH_STATUS = 0BEGINIF @username='dbo'EXEC sp_changedbowner 'sa'ELSEEXEC sp_change_users_login 'Auto_Fix', @username, NULL, @passwordFETCH NEXTFROM GetOrphanUsersINTO @usernameENDCLOSE GetOrphanUsersDEALLOCATE GetOrphanUsersGO

Stored Procedure 3:----Following Stored Procedure will drop all the Orphan users in database.----If you need any of those users, you can create them again.CREATE PROCEDURE dbo.spDBA_DropOrphanUsersASDECLARE @username VARCHAR(25)DECLARE GetOrphanUsers CURSORFORSELECT UserName = nameFROM sysusersWHERE issqluser = 1AND (sid IS NOT NULLAND sid <> 0x0)AND SUSER_SNAME(sid) IS NULLORDER BY nameOPEN GetOrphanUsersFETCH NEXTFROM GetOrphanUsersINTO @usernameWHILE @@FETCH_STATUS = 0BEGINIF @username='dbo'EXEC sp_changedbowner 'sa'ELSEEXEC sp_dropuser @usernameFETCH NEXTFROM GetOrphanUsersINTO @usernameENDCLOSE GetOrphanUsersDEALLOCATE GetOrphanUsersGO

SQL SERVER – Function to Convert List to Table

February 10, 2007 by pinaldave

Update : (5/5/2007)I have updated the UDF to support SQL SERVER 2005. Visit :SQL SERVER – UDF – Function to Convert List to Table

SQL SERVER – Primary Key Constraints and Unique Key Constraints

February 5, 2007 by pinaldave

Primary Key:Primary Key enforces uniqueness of the column on which they are defined. Primary Key creates a clustered index on the column. Primary Key does not allow Nulls.

Page 272: 9 Jan 01, 2007-431 Dec 31, 2007

Create table with Primary Key:CREATE TABLE Authors (AuthorID INT NOT NULL PRIMARY KEY,Name VARCHAR(100) NOT NULL)GO

Alter table with Primary Key:ALTER TABLE AuthorsADD CONSTRAINT pk_authors PRIMARY KEY (AuthorID)GO

Unique Key:Unique Key enforces uniqueness of the column on which they are defined. Unique Key creates a non-clustered index on the column. Unique Key allows only one NULL Value.

Alter table to add unique constraint to column:ALTER TABLE Authors ADD CONSTRAINT IX_Authors_Name UNIQUE(Name)GO

SQL SERVER – UDF – Function to Convert Text String to Title Case – Proper Case

February 1, 2007 by pinaldave

Following function will convert any string to Title Case. I have this function for long time. I do not remember that if I wrote it myself or I modified from original source.

Run Following T-SQL statement in query analyzer:

SELECT dbo.udf_TitleCase('This function will convert this string to title case!')

The output will be displayed in Results pan as follows:

This Function Will Convert This String To Title Case!

T-SQL code of the function is:

CREATE FUNCTION udf_TitleCase (@InputString VARCHAR(4000) )RETURNS VARCHAR(4000)ASBEGINDECLARE @Index INTDECLARE @Char CHAR(1)DECLARE @OutputString VARCHAR(255)SET @OutputString = LOWER(@InputString)SET @Index = 2SET @OutputString =STUFF(@OutputString, 1, 1,UPPER(SUBSTRING(@InputString,1,1)))WHILE @Index <= LEN(@InputString)BEGINSET @Char = SUBSTRING(@InputString, @Index, 1)IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&','''','(')IF @Index + 1 <= LEN(@InputString)BEGINIF @Char != ''''ORUPPER(SUBSTRING(@InputString, @Index + 1, 1)) != 'S'SET @OutputString =STUFF(@OutputString, @Index + 1, 1,UPPER(SUBSTRING(@InputString, @Index + 1, 1)))ENDSET @Index = @Index + 1ENDRETURN ISNULL(@OutputString,'')END

Page 273: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – ReIndexing Database Tables and Update Statistics on Tables

January 31, 2007 by pinaldave

SQL SERVER 2005 uses ALTER INDEX syntax to reindex database. SQL SERVER 2005 supports DBREINDEX but it will be deprecated in future versions.

When any data modification operations (INSERT, UPDATE, or DELETE statements) table fragmentation can occur. DBCC DBREINDEX statement can be used to rebuild all the indexes on all the tables in database. DBCC DBREINDEX is efficient over dropping and recreating indexes.

Execution of Stored Procedure sp_updatestats at the end of the Indexes process ensures updating stats of the database.

Method 1: My Preference

USE MyDatabaseGOEXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)"GOEXEC sp_updatestatsGO

Method 2:

USE MyDatabaseGOCREATE PROCEDURE spUtil_ReIndexDatabase_UpdateStatsASDECLARE @MyTable VARCHAR(255)DECLARE myCursorCURSOR FORSELECT table_nameFROM information_schema.tablesWHERE table_type = 'base table'OPEN myCursorFETCH NEXTFROM myCursor INTO @MyTableWHILE @@FETCH_STATUS = 0BEGINPRINT 'Reindexing Table:  ' + @MyTableDBCC DBREINDEX(@MyTable, '', 80)FETCH NEXTFROM myCursor INTO @MyTableENDCLOSE myCursorDEALLOCATE myCursorEXEC sp_updatestatsGO

SQL SERVER – Query Analyzer Short Cut to display the text of Stored Procedure

January 30, 2007 by pinaldave

This is quick but interesting trick to display the text of Stored Procedure in the result window. Open SQL Query Analyzer >> Tools >> Customize >> Custom Tabtype sp_helptext against Ctrl+3 (or shortcut key of your choice)

Press CTRL + T to enable the text view in result window.Type any Stored Procedure name in your database, select the SP name and type Ctrl+4.

You will see the Stored Procedure text in the Result Window.

Page 274: 9 Jan 01, 2007-431 Dec 31, 2007

SQL SERVER – SQL Joke, SQL Humor, SQL Laugh

January 26, 2007 by pinaldave

I have heard this joke from my friend. I always wanted to write it but I was not able to find the source of the joke. This joke I have located on DavidM’s Blog on SQLTeam.

It is March 1st and the first day of DBMS schoolThe teacher starts off with a role call..

Teacher: Oracle?“Present sir”Teacher: DB2?“Present sir”Teacher: SQL Server?“Present sir”Teacher: MySQL?[Silence]Teacher: MySQL?[Silence]Teacher: Where the hell is MySQL[In rushes MySQL, unshaven, hair a mess]Teacher: Where have you been MySQL“Sorry sir I thought it was February 31st“

SQL SERVER – Creating Comma Separate List From Table

February 20, 2007 by pinaldave

Update : (5/5/2007)I have updated the script to support SQL SERVER 2005. Visit :SQL SERVER – Creating Comma Separate Values List from Table – UDF – SP

SQL SERVER – SQL Server 2005 Samples and Sample Databases (February 2007)

February 24, 2007 by pinaldave

The samples download provides over 100 samples for SQL Server 2005, demonstrating the following components:

Database Engine, including administration, data access, Full-Text Search, Common Language Runtime (CLR) integration, Server Management Objects (SMO), Service Broker, and XML

Analysis Services Integration Services Notification Services Reporting Services Replication

The samples databases downloads include the AdventureWorks sample online transaction processing (OLTP) database, the AdventureWorksDW sample data warehouse, and the AdventureWorksAS sample projects which you can use to build the AdventureWorksAS BI database. These databases are used in the samples and in the code examples in the SQL Server 2005 Books Online. There is also a new sample database called AdventureWorksLT. This is a scaled-down sample database that those who are new to SQL Server will find easier to use and understand.

The text above is copied from MS Download Center.

Download here.

SQL SERVER – UDF – Function to Convert List to Table

Page 275: 9 Jan 01, 2007-431 Dec 31, 2007

May 6, 2007 by pinaldave

Following Users Defined Functions will convert list to table. It also supports user defined delimiter. Following UDF is written for SQL SERVER 2005. It will also work well with very big TEXT field. If you want to use this on SQL SERVER 2000 replace VARCHAR(MAX) with VARCHAR(8000) or any other varchar limit. It will work with INT as well as VARCHAR.

CREATE FUNCTION dbo.udf_List2Table(@List VARCHAR(MAX),@Delim CHAR)RETURNS@ParsedList TABLE(item VARCHAR(MAX))ASBEGINDECLARE @item VARCHAR(MAX), @Pos INTSET @List = LTRIM(RTRIM(@List))+ @DelimSET @Pos = CHARINDEX(@Delim, @List, 1)WHILE @Pos > 0BEGINSET @item = LTRIM(RTRIM(LEFT(@List, @Pos - 1)))IF @item <> ''BEGININSERT INTO @ParsedList (item)VALUES (CAST(@item AS VARCHAR(MAX)))ENDSET @List = RIGHT(@List, LEN(@List) - @Pos)SET @Pos = CHARINDEX(@Delim, @List, 1)ENDRETURNENDGO

Run following script to test above UDF.----Example 1 for VARHCARSELECT item AS Example1FROM dbo.udf_List2Table('first||2nd||III||1+1+1+1','||')GO----Example 2 for INTSELECT CAST(item AS INT) AS Example2FROM dbo.udf_List2Table('111,222,333,444,555',',')GO

ResultSet:Example1————-first2ndIII1+1+1+1

(4 row(s) affected)

Example2————-111222333444555

SQL SERVER – Delete Duplicate Records – Rows

Page 276: 9 Jan 01, 2007-431 Dec 31, 2007

March 1, 2007 by pinaldave

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

DELETEFROM MyTableWHERE ID NOT IN(SELECT MAX(ID)FROM MyTableGROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)

SQL SERVER – Delete Duplicate Records – Rows

March 1, 2007 by pinaldave

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

DELETEFROM MyTableWHERE ID NOT IN(SELECT MAX(ID)FROM MyTableGROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)

SQL SERVER – T-SQL Script to find the CD key from Registry

February 28, 2007 by pinaldave

Here is the way to find SQL Server CD key, which was used to install it on machine. If user do not have permission on the SP, please login using SA username. Expended stored procedure xp_regread can read any registry values. I have used this XP to read CD_KEY. This is undocumented Stroed Procedure and may not be supported in Future Version of SQL Server.

USE masterGOEXEC xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\MicrosoftSQL Server\80\Registration','CD_KEY'GO

SQL SERVER – What is New in SQL Server Agent for Microsoft SQL Server 2005

February 26, 2007 by pinaldave

I came across this interesting and detailed article ‘What’s New in SQL Server Agent for Microsoft SQL Server 2005‘ on Microsoft TechNet.

This article describes Security Improvements, New Roles in the msdb Database, Multiple Proxy Accounts, Performance Improvements, Performance Counters, New SQL Server Agent Subsystems, Shared Schedules, WMI Event Alerts, SQL Server Agent Sessions, Database Mail Support, Stored Procedure Changes in depth.

SQL SERVER – Restore Database Backup using SQL Script (T-SQL)

February 25, 2007 by pinaldave

Page 277: 9 Jan 01, 2007-431 Dec 31, 2007

Database YourDB has full backup YourBaackUpFile.bak. It can be restored using following two steps.

Step 1: Retrive the Logical file name of the database from backup.RESTORE FILELISTONLYFROM DISK = 'D:BackUpYourBaackUpFile.bak'GO

Step 2: Use the values in the LogicalName Column in following Step.----Make Database to single user ModeALTER DATABASE YourDBSET SINGLE_USER WITHROLLBACK IMMEDIATE

----Restore DatabaseRESTORE DATABASE YourDBFROM DISK = 'D:BackUpYourBaackUpFile.bak'WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf'

/*If there is no error in statement before database will be in multiusermode.If error occurs please execute following command it will convertdatabase in multi user.*/ALTER DATABASE YourDB SET MULTI_USERGO

SQL SERVER – Union vs. Union All – Which is better for performance?

March 10, 2007 by pinaldave

This article is completely re-written with better example SQL SERVER – Difference Between Union vs. Union All – Optimal Performance Comparison. I suggest all of my readers to go here for update article.

UNIONThe UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.

UNION ALLThe UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.

The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.

A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

Example: Table 1 : First,Second,Third,Fourth,FifthTable 2 : First,Second,Fifth,Sixth

Result Set:UNION: First,Second,Third,Fourth,Fifth,Sixth (This will remove duplicate values)UNION ALL: First,First,Second,Second,Third,Fourth,Fifth,Fifth,Sixth,Sixth (This will repeat values)

SQL SERVER – Script to Determine Which Version of SQL Server 2000-2005 is Running

March 7, 2007 by pinaldave

Page 278: 9 Jan 01, 2007-431 Dec 31, 2007

To determine which version of SQL Server 2000/2005 is running, connect to SQL Server 2000/2005 by using Query Analyzer, and then run the following code:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

The results are:The product version (for example, 8.00.534).The product level (for example, “RTM” or “SP2″).The edition (for example, “Standard Edition”).

For example, the result looks similar to:8.00.534 RTM Standard Edition

SQL SERVER – QUOTED_IDENTIFIER ON/OFF and ANSI_NULL ON/OFF Explanation

March 5, 2007 by pinaldave

When create or alter SQL object like Stored Procedure, User Defined Function in Query Analyzer, it is created with following SQL commands prefixed and suffixed. What are these – QUOTED_IDENTIFIER ON/OFF and ANSI_NULL ON/OFF?SET QUOTED_IDENTIFIER ONGOSET ANSI_NULLS ONGO--SQL PROCEDURE, SQL FUNCTIONS, SQL OBJECTGOSET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS ONGO

ANSI NULL ON/OFF:This option specifies the setting for ANSI NULL comparisons. When this is on, any query that compares a value with a null returns a 0. When off, any query that compares a value with a null returns a null value.

QUOTED IDENTIFIER ON/OFF:This options specifies the setting for usage of double quotation. When this is on, double quotation mark is used as part of the SQL Server identifier (object name). This can be useful in situations in which identifiers are also SQL Server reserved words.

SQL SERVER – SQL Server 2005 Samples and Sample Databases (February 2007)

February 24, 2007 by pinaldave

The samples download provides over 100 samples for SQL Server 2005, demonstrating the following components:

Database Engine, including administration, data access, Full-Text Search, Common Language Runtime (CLR) integration, Server Management Objects (SMO), Service Broker, and XML

Analysis Services Integration Services Notification Services Reporting Services Replication

The samples databases downloads include the AdventureWorks sample online transaction processing (OLTP) database, the AdventureWorksDW sample data warehouse, and the AdventureWorksAS sample projects which you can use to build the AdventureWorksAS BI database. These databases are used in the samples and in the code examples in the SQL Server 2005 Books Online. There is also a new sample database called AdventureWorksLT. This is a scaled-down sample database that those who are new to SQL Server will find easier to use and understand.

The text above is copied from MS Download Center.

Page 279: 9 Jan 01, 2007-431 Dec 31, 2007

Download here.

SQL SERVER – Query to Find Seed Values, Increment Values and Current Identity Column value of the table

April 23, 2007 by pinaldave

Following script will return all the tables which has identity column. It will also return the Seed Values, Increment Values and Current Identity Column value of the table.

SELECT IDENT_SEED(TABLE_NAME) AS Seed,IDENT_INCR(TABLE_NAME) AS Increment,IDENT_CURRENT(TABLE_NAME) AS Current_Identity,TABLE_NAMEFROM INFORMATION_SCHEMA.TABLESWHERE OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1AND TABLE_TYPE = 'BASE TABLE'

SQL SERVER – Understanding new Index Type of SQL Server 2005 Included Column Index along with Clustered Index and Non-clustered Index

April 23, 2007 by pinaldave

Clustered IndexOnly 1 allowed per tablePhysically rearranges the data in the table to conform to the index constraintsFor use on columns that are frequently searched for ranges of dataFor use on columns with low selectivity

Non-Clustered IndexUp to 249 allowed per tableCreates a separate list of key values with pointers to the location of the data in the data pagesFor use on columns that are searched for single valuesFor use on columns with high selectivity

A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows

Included Column Index (New in SQL Server 2005) In SQL Server 2005, the functionality of non-clustered indexes is extended by adding non-key columns to the leaf level of the non-clustered index. Non-key columns, can help to create cover indexes.By including non-key columns, you can create non-clustered indexes that cover more queries. The Database Engine does not consider non-key columns when calculating the number of index key columns or index key size. Non-key columns can be included in non-clustered index to avoid exceeding the current index size limitations of a maximum of 16 key columns and a maximum index key size of 900 bytes. Another advantage is that using non-key column in index we can have index data types not allowed as index key columns generally.

In following example column FileName is varchar(400), which will increase the size of the index key bigger than it is allowed. If we still want to include in our cover index to gain performance we can do it by using the Keyword INCLUDE.

USE AdventureWorksGOCREATE INDEX IX_Document_TitleON Production.Document (Title, Revision)INCLUDE (FileName)

Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and the INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can

Page 280: 9 Jan 01, 2007-431 Dec 31, 2007

be dropped from a table only after the non-key index is dropped first. For Included Column Index to exist there must be at least one key column defined with a maximum of 16 key columns and 1023 included columns.

Avoid adding unnecessary columns. Adding too many index columns, key or non-key as they will affect negatively on performance. Fewer index rows will fit on a page. This could create I/O increases and reduced cache efficiency. More disk space will be required to store the index. Index maintenance may increase the time that it takes to perform modifications, inserts, updates, or deletes, to the underlying table or indexed view.

Another example to test:Create following Index on Database AdventureWorks in SQL SERVER 2005

USE AdventureWorksGOCREATE NONCLUSTERED INDEX IX_Address_PostalCodeON Person.Address (PostalCode)INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID)GO

Test the performance of following query before and after creating Index. The performance improvement is significant.

SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCodeFROM Person.AddressWHERE PostalCode BETWEEN '98000'AND '99999';GO

SQL SERVER – Raid Configuration – RAID 10

April 22, 2007 by pinaldave

I get question about what configuration of redundant array of inexpensive disks (RAID) I use for my SQL Servers.

The answer is short is: RAID 10. Why? Excellent performance with Read and Write.

RAID 10 has advantage of both RAID 0 and RAID 1. RAID 10 uses all the drives in the array to gain higher I/O rates so more drives in the array higher performance. RAID 5 has penalty for write performance because of the parity in check. There are many article already written about them. If you are interested in reading more please refer book online.

SQL SERVER – @@DATEFIRST and SET DATEFIRST Relations and Usage

April 22, 2007 by pinaldave

The master database’s syslanguages table has a DateFirst column that defines the first day of the week for a particular language. SQL Server with US English as default language, SQL Server sets DATEFIRST to 7 (Sunday) by default. We can reset any day as first day of the week using

SET DATEFIRST 5

This will set Friday as first day of week.@@DATEFIRST returns the current value, for the session, of SET DATEFIRST.

SET LANGUAGE italianGOSELECT @@DATEFIRSTGO----This will return result as 1(Monday)SET LANGUAGE us_english

Page 281: 9 Jan 01, 2007-431 Dec 31, 2007

GOSELECT @@DATEFIRSTGO----This will return result as 7(Sunday)

In this way @@DATEFIRST and SET DATEFIRST are related. When I learned about this feature I was very glad as our company has started to server global clients and simple feature like this helps a lot to avoid confusion.