Documente Academic
Documente Profesional
Documente Cultură
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
In Object Explorer, open Security folder, open Logins folder. Right Click on SA account and go to
Properties.
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
Let me know your thoughts about this post. Let me know if you want me to write more articles like this
one.
Short Summary:
A Practitioners 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 Practitioners 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 its 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.
Rating: 5 Starts
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.
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 Cant 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
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.
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 TRAN
TRUNCATE TABLE TestTable
-- Following SELECT will return TestTable empty
SELECT *
FROM TestTable
-- Following SELECT will return TestTable with original data
ROLLBACK
SELECT *
FROM TestTable
Summary : 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 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.
Above script will create two backups at two different locations, if backup of one location is corrupted
backup from another location will work fine.
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.
The purpose of above mentioned paper is to provide answers to the following questions
If above link is not working due to any reason, please contact me.
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:
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 pinal@sqlauthority.com
If you are looking for talented IT professional : Post Job or email pinal@sqlauthority.com
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.
ResultSet:
OriginalDate CastDate
-
2007-12-22 17:48:14.640 2007/12/22
ResultSet:
OriginalDate
2007-12-22
ResultSet:
OriginalTime
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;
GO
ALTER INDEX ALL ON Production.Product REBUILD
GO
Index Reorganize : This process physically reorganizes the leaf nodes of the index.
USE AdventureWorks;
GO
ALTER INDEX ALL ON Production.Product REORGANIZE
GO
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.
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.
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.
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.
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.
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.
Download Information
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 todays data compared to a previous set of data
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;
GO
EXEC sp_helpindex 'Person.Address'
GO
Let me know if you think this kind of small tips are useful to you.
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.
SELECT
name AS FileName,
size*1.0/128 AS FileSizeinMB,
CASE max_size
WHEN 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' =
CASE
WHEN growth = 0 THEN 'Size is fixed and will not grow.'
WHEN growth > 0
AND is_percent_growth = 0
THEN 'Growth value is in 8-KB pages.'
ELSE 'Growth value is a percentage.'
END
FROM tempdb.sys.database_files;
GO
I have been receiving following question again and again either through email or through comments on
this blog.
I have previously written two article about this issue. Refer them for additional information and details.
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.
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 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
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.
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 theyre finished.
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.
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.
SQL SERVER FIX : Error : 3702 Cannot drop database 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.
Fix/Workaround/Solution:
Following commands will not raise error and successfully drop the database:
USE Master;
GO
DROP 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.
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)
AS
BEGIN
DECLARE @str VARCHAR(255)
DECLARE @count INT
DECLARE @start INT
DECLARE @result VARCHAR(255)
DECLARE @end INT
SET @start=1
SET @end=@datalen_tocheck
SET @count=@datalen_tocheck
SET @str = @string
WHILE (@count <=255)
BEGIN
IF (@result IS NULL)
BEGIN
SET @result=''
END
SET @result=@result+SUBSTRING(@str,@start,@end)
SET @str=REPLACE(@str,SUBSTRING(@str,@start,@end),'')
SET @count=@count+@datalen_tocheck
END
RETURN @result
END
GO>, 1)
Usage:
SET CONCAT_NULL_YIELDS_NULL OFF
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
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
3) Cash infusion
Outsourcing 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.
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 wont improve the situation; it may in fact exacerbate it. If the organization doesnt
understand its own requirements, it wont be able to communicate them to an outside provider.
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.
9) Reduce risk
Tremendous 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.
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
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.
SQL SERVER Sharpen Your Skills: Brush up on FILLFACTOR, ISNULL, NULLIF, and % as
wildcard and operator
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).
SQLAuthority News Microsoft SQL Server 2005 MSIT Three Configuration Pack for
Configuration Manager 2007
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.
SQLAuthority News SQL Joke, SQL Humor, SQL Laugh Database Dilbert
SQLAuthority News Microsoft SQL Server 2005 Assessment Configuration Pack Download
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
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.
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 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
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
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.
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
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
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?
1
2
3
4
5
6
7
8
9
A. Run following script which will generate output in sequence, which will generate output as you
requested.
DECLARE @idt INT
SET @idt = 0
WHILE (@idt < 100)
BEGIN
SELECT @idt = @idt + 1
PRINT @idt
END
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.
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.
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
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
Lets say, the database name is testDev. In the SQL Server Management Studio,
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.
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
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 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
DLLs 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
This release provides developer sample applications in Microsoft Visual Basic and Microsoft Visual C# that
use the ReportViewer controls for Microsoft Visual Studio 2008.
SQL SERVER Rules of Third Normal Form and Normalization Advantage 3NF
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 schemas 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.
Run following simple script on SQL Server 2005 to retrieve all stored procedure in database.
SELECT *
FROM sys.procedures;
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.
Correct Syntax:
CREATE PROCEDURE usp_SelectRecord
AS
BEGIN
SELECT *
FROM TABLE
END
GO
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.
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.
SQLAuthority News Download SQL Server 2005 Books Online (September 2007)
SQL SERVER FIX : ERROR Msg 5174 Each file size must be greater than or equal to 512 KB
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.
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
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.
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 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.
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.
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.
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.
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.
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
Search SQLAuthority
SQLAuthority Feed
My Other Blog
SQL SERVER Find Stored Procedure Related to Table in Database Search in All Stored procedure
SQL SERVER Shrinking Truncate Log File Log Full
SQL SERVER UDF Function to Convert Text String to Title Case Proper Case
SQL SERVER Union vs. Union All Which is better for performance?
SQL SERVER DBCC RESEED Table Identity Value Reset Table Identity
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 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 2005 Find Table without Clustered Index Find Table with no Primary Key
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 Comparison Index Fragmentation, Index De-Fragmentation, Index Rebuild SQL SERVER
2000 and SQL SERVER 2005
SQL SERVER Comparison : Similarity and Difference #TempTable vs @TempVariable
SQL SERVER Definition, Comparison and Difference between HAVING and WHERE Clause
SQL SERVER 2005 List All Stored Procedure Modified in Last N Days
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 2005 Find Stored Procedure Create Date and Modified Date
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 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 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
SQL SERVER 2005 Sample Example of RANKING Functions ROW_NUMBER, RANK, DENSE_RANK,
NTILE
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)
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
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,
Pinal Dave
I have received following questions many times. I will list all the questions here and answer them
together.
Answers to all of the questions are very much related. Master database is system database and it contains
information about running servers 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.
Business Intelligence
Business 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 Warehouse
A single structure that usually, but not always, consists of one or more cubes.
Data Mart
A defined subset of a data warehouse, often a single cube from a group. It represents one business unit.
Cube
A 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 System
The terms 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.
ETL
ETL is abbreviation of Extraction, Transform, and Load.
OLAP
OLAP is abbreviation of online analytical processing.
OLTP
OLTP is abbreviation of online transactional processing.
SQL SERVER Disable All Triggers on a Database Disable All Triggers on All Servers
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;
GO
DISABLE TRIGGER Person.uAddress ON AdventureWorks;
GO
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
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.
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.
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
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 Forced
ALTER DATABASE AdventureWorks
SET PARAMETERIZATION FORCED
GO
-- Change database Parameterization to Simple
ALTER DATABASE AdventureWorks
SET PARAMETERIZATION Simple
GO
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
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.
ResultSet:
1
2
3
4
5
ResultSet:
1
2
3
ResultSet:
1
2
3
4
5
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');
GO
Results were interesting. After I came back from my visit, I ran above script on my personal database
server, where I logged as SA.
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
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)
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
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.
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
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.
SQL SERVER Types of DBCC Commands When Used as Database Console Commands
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 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
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
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
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
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.
SQLAuthority News Book Review Backup & Recovery (Paperback)
Short Summary:
This books 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 arent 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 authors 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 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!
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.
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 1
USE AdventureWorks
GO
CREATE TABLE ConstraintTable
(ID INT CONSTRAINT Ct_ID PRIMARY KEY, ColSecond INT)
GO
--Clean Up
DROP TABLE ConstraintTable
GO
-- Primary Key Constraint upon Table Created Method 2
USE AdventureWorks
GO
CREATE TABLE ConstraintTable
(ID INT, ColSecond INT,
CONSTRAINT Ct_ID PRIMARY KEY (ID))
GO
--Clean Up
DROP TABLE ConstraintTable
GO
-- Primary Key Constraint after Table Created Method 3
USE AdventureWorks
GO
CREATE TABLE ConstraintTable
(ID INT, ColSecond INT)
GO
-- Primary Key Column must not allow NULL
ALTER TABLE ConstraintTable
ALTER COLUMN ID INT NOT NULL
GO
ALTER TABLE ConstraintTable
ADD CONSTRAINT Ct_ID PRIMARY KEY (ID)
--Clean Up
DROP TABLE ConstraintTable
GO
SQL SERVER 2005 Driver for PHP Community Technology Preview (October 2007)
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]
GO
ALTER TABLE [Sales].[Individual]
ADD CONSTRAINT [PK_Individual_CustomerID]
PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)
SQL SERVER Pre-Code Review Tips Tips For Enforcing Coding Standards
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 SQL SERVER Database Coding Standards and Guidelines Complete List Download
SQL SERVER 2005 SQL Server Surface Area Configuration Tool Examples and Explanation
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
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.
3) After selecting the computer to configure, you can launch either of services.
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
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.
Following example demonstrates both the way to create NOT NULL constraints.
USE AdventureWorks
GO
-- NOT NULL Constraint when Table is created
CREATE TABLE ConstraintTable
(ID INT, ColSecond INT NOT NULL)
GO
-- NOT NULL Constraint after Table is created
ALTER TABLE ConstraintTable
ALTER COLUMN ID INT NOT NULL
GO
--Clean Up
DROP TABLE ConstraintTable
GO
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.
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;
GO
SELECT 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.PostalCode
FROM Sales.SalesPerson s
INNER JOIN Person.Contact c
ON s.SalesPersonID = c.ContactID
INNER JOIN Person.Address a
ON a.AddressID = c.ContactID
WHERE TerritoryID IS NOT NULL
AND SalesYTD <> 0;
Resultset:
SQL SERVER 2005 Connection Property of SQL Server Management Studio SSMS
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.
Image 1: Default Login
Image 2: Options
Image 3: Option Network Protocol Example
SQL SERVER Executing Remote Stored Procedure Calling Stored Procedure on Linked Server
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.
Params
Example:
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
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] [-?]
3) Open SQL Server Management Studio with username and password with no splash screen and default
database as AdventureWorks
sqlwb -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\IDE
Click 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
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.
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 cursors current location
within a resultset.
Algebrizer trees: The Algebrizers 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).
One of the developer at my company thought that we can not use RAISEERROR function in new feature of
SQL Server 2005 TRYCATCH. When asked for explanation he suggested SQL SERVER 2005 Explanation
of TRYCATCH and ERROR Handling article as excuse suggesting that I did not give example of
RAISEERROR with TRYCATCH. We all thought it was funny. Just to keep record straight, TRYCATCH can
sure use RAISEERROR function.
First read original article for additional information about how TRYCATCH works with ERROR codes. SQL
SERVER 2005 Explanation of TRYCATCH and ERROR Handling
ResultSet:
ErrorMessage
ResultSet:
Msg 50000, Level 16, State 1, Line 9
Divide by zero error encountered.
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
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.
USE AdventureWorks;
GO
--------Creating the table which will store permanent table
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
----Creating temp table to store ovalues of OUTPUT clause
DECLARE @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 @TmpTable
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
OUTPUT Inserted.ID, Inserted.TEXTVal INTO @TmpTable
VALUES (2,'SecondVal')
----Check the values in the temp table and real table
----The values in both the tables will be same
SELECT * FROM @TmpTable
SELECT * FROM TestTable
----Clean up time
DROP TABLE TestTable
GO
ResultSet 1:
ID TextVal
1 FirstVal
2 SecondVal
ID TextVal
1 FirstVal
2 SecondVal
USE AdventureWorks;
GO
----Creating the table which will store permanent table
CREATE 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.TEXTVal
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
OUTPUT Inserted.ID, Inserted.TEXTVal
VALUES (2,'SecondVal')
----Clean up time
DROP TABLE TestTable
GO
ResultSet 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 table
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
----Creating temp table to store ovalues of OUTPUT clause
DECLARE @TmpTable TABLE (ID_New INT, TEXTVal_New VARCHAR(100),ID_Old INT, TEXTVal_Old
VARCHAR(100))
----Insert values in real table
INSERT TestTable (ID, TEXTVal)
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
VALUES (2,'SecondVal')
----Update the table and insert values in temp table using Output clause
UPDATE TestTable
SET TEXTVal = 'NewValue'
OUTPUT Inserted.ID, Inserted.TEXTVal, Deleted.ID, Deleted.TEXTVal INTO @TmpTable
WHERE ID IN (1,2)
----Check the values in the temp table and real table
----The values in both the tables will be same
SELECT * FROM @TmpTable
SELECT * FROM TestTable
----Clean up time
DROP TABLE TestTable
GO
ResultSet 3:
ID_New TextVal_New ID_Old TextVal_Old
1 NewValue 1 FirstVal
2 NewValue 2 SecondVal
ID TextVal
1 NewValue
2 NewValue
USE AdventureWorks;
GO
----Creating the table which will store permanent table
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
----Creating temp table to store ovalues of OUTPUT clause
DECLARE @TmpTable TABLE (ID INT, TEXTVal VARCHAR(100))
----Insert values in real table
INSERT TestTable (ID, TEXTVal)
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
VALUES (2,'SecondVal')
----Update the table and insert values in temp table using Output clause
DELETE
FROM TestTable
OUTPUT Deleted.ID, Deleted.TEXTVal INTO @TmpTable
WHERE ID IN (1,2)
----Check the values in the temp table and real table
----The values in both the tables will be same
SELECT * FROM @TmpTable
SELECT * FROM TestTable
----Clean up time
DROP TABLE TestTable
GO
ResultSet 4:
ID TextVal
1 FirstVal
2 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
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
pointed many users to that post SQL SERVER 2005 Query Analyzer Microsoft SQL SERVER
Management Studio. Recently I have been receiving similar question.
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.
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.
@@CONNECTIONS
Returns the number of attempted connections, either successful or unsuccessful since SQL Server was last
started.
@@MAX_CONNECTIONS
Returns the maximum number of simultaneous user connections allowed on an instance of SQL Server.
The number returned is not necessarily the number currently configured.
Example:
SELECT GETDATE() AS 'Currunt Time',
@@CONNECTIONS AS 'Total Logins so far',
@@MAX_CONNECTIONS AS 'Max Connection Simultaneously'
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 MDY
INSERT INTO #tempTable
VALUES ('09/28/2007')
SET DATEFORMAT YDM
INSERT INTO #tempTable
VALUES ('2007/28/09')
SET DATEFORMAT YMD
INSERT INTO #tempTable
VALUES ('2007/08/28')
SELECT DateFormatSample
FROM #tempTable
DROP TABLE #tempTable
Resultset:
DateFormatSample
2007-09-28 00:00:00
2007-09-28 00:00:00
2007-08-28 00:00:00
SQL SERVER FIX : Error 3154: The backup set holds a backup of a database other than the
existing database
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.
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 AdventureWorks
FROM DISK = 'C:\BackupAdventureworks.bak'
WITH REPLACE
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.
The code used in the book is available for download on OReilly 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 Dave
Principal Database Administrator
(blog.sqlauthority.com)
SQL SERVER Effect of TRANSACTION on Local Variable After ROLLBACK and After COMMIT
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 INT
SET @FlagInt = 1
PRINT @FlagInt ---- @FlagInt Value will be 1
BEGIN TRANSACTION
SET @FlagInt = 2 ---- @FlagInt Value will be 2
PRINT @FlagInt
ROLLBACK TRANSACTION
PRINT @FlagInt ---- @FlagInt Value will be ?
GO
PRINT '--------------------'
PRINT 'After COMMIT example'
DECLARE @FlagINT INT
SET @FlagInt = 1
PRINT @FlagInt ---- @FlagInt Value will be 1
BEGIN TRANSACTION
SET @FlagInt = 2 ---- @FlagInt Value will be 2
PRINT @FlagInt
COMMIT TRANSACTION
PRINT @FlagInt ---- @FlagInt Value will be ?
GO
ResultSet:
After ROLLBACK example
1
2
2
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
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
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_MShasdbaccess
GO
SQL SERVER 2005 Version Information and Additional Information Extended Stored
Procedure xp_msver
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_msver
ResultSet:
Index Name Internal_Value Character_Value
-
1 ProductName NULL Microsoft SQL Server
2 ProductVersion 589824 9.00.3042.00
3 Language 1033 English (United States)
4 Platform NULL NT INTEL X86
5 Comments NULL NT INTEL X86
6 CompanyName NULL Microsoft Corporation
7 FileDescription NULL SQL Server Windows NT
8 FileVersion NULL 2005.090.3042.00
9 InternalName NULL SQLSERVR
10 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 Corporation
12 OriginalFilename NULL SQLSERVR.EXE
13 PrivateBuild NULL NULL
14 SpecialBuild 199360512 NULL
15 WindowsVersion 170393861 5.1 (2600)
16 ProcessorCount 1 1
17 ProcessorActiveMask 1 00000001
18 ProcessorType 586 PROCESSOR_INTEL_PENTIUM
19 PhysicalMemory 1023 1023 (1073111040)
20 Product ID NULL NULL
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
English
German
French
Japanese
Danish
Spanish
Italian
Dutch
Norwegian
Portuguese
Finnish
Swedish
Czech
Hungarian
Polish
Romanian
Croatian
Slovak
Slovenian
Greek
Bulgarian
Russian
Turkish
British English
Estonian
Latvian
Lithuanian
Brazilian
Traditional Chinese
Korean
Simplified Chinese
Arabic
Thai
SQL SERVER FIX : 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.
SQL SERVER Rename Database to New Name Using Stored Procedure by Changing to Single
User Mode
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;
GO
EXEC sp_dboption AdventureWorks, 'Single User', True
GO
EXEC sp_renamedb 'AdventureWorks', 'AdventureWorks_New'
GO
EXEC sp_dboption AdventureWorks, 'Single User', False
GO
SQLAuthority News Scale-Out Querying with Analysis Services Using SAN Snapshots
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.
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
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 BIT
BEGIN
DECLARE @Ret BIT
IF (PATINDEX('%[^0-9-]%', @Number) = 0
AND CHARINDEX('-', @Number) <= 1
AND @Number NOT IN ('.', '-', '+', '^')
AND LEN(@Number)>0
AND @Number NOT LIKE '%-%')
SET @Ret = 1
ELSE
SET @Ret = 0
RETURN @Ret
END
GO
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
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
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 worlds 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.
Scalability
Availability
Manageability
Built-in Business Intelligence
Faster results
Better decisions
Trusted Platform
Total cost of ownership
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 ;
GO
CREATE TRIGGER reminder
ON Person.Address
AFTER
UPDATE
AS
IF (
UPDATE (StateProvinceID)
OR
UPDATE (PostalCode) )
BEGIN
RAISERROR (50009, 16, 10)
END;
GO
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.
SQL SERVER 2005 List All The Constraint of Database Find Primary Key and Foreign Key
Constraint in Database
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;
GO
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
GO
SQLAuthority News Book Review Pro T-SQL 2005 Programmers Guide (Paperback)
September 15, 2007 by pinaldave
Short Summary:
Pro T-SQL 2005 Programmers Guide book examines SQL Server 2005 T-SQL from a developers
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 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 were 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.
In Summary, A book for every developer who want to take full advantage of the power of T-SQL on SQL
Server 2005.
Pinal Dave
Principal Database Administrator
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
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
SQL Server 2005 DBA Street Smarts: A Real World Guide to SQL Server 2005 Certification Skills
(Paperback)
by Joseph L. Jorden
Short Review:
Microsofts 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:
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.
Task : Selecting and Setting a Recovery Model
This 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 books
focus in not in that direction.
In Summary, A smooth read and great in breadth learning experience for beginners.
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.
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.
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.
Other important notes to keep in mind when utilizing the Scrum process:
SQL SERVER Difference Between EXEC and EXECUTE vs EXEC() Use EXEC/EXECUTE for
SP always
They are the same. Both of them executes stored procedure when called as
EXEC sp_help
GO
EXECUTE sp_help
GO
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
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 Errors
USE AdventureWorks;
GO
----Try this first independently this will throw an error
sp_helptext 'dbo.uspPrintError'
GO
----Try this second independently this will work fine
EXEC 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
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.
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
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.
SQL SERVER UDF User Defined Function Get Number of Days in Month
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 INT
AS
BEGIN
DECLARE @rtDate INT
SET @rtDate = CASE WHEN MONTH(@myDateTime)
IN (1, 3, 5, 7, 8, 10, 12) THEN 31
WHEN MONTH(@myDateTime) IN (4, 6, 9, 11) THEN 30
ELSE CASE WHEN (YEAR(@myDateTime) % 4 = 0
AND
YEAR(@myDateTime) % 100 != 0)
OR
(YEAR(@myDateTime) % 400 = 0)
THEN 29
ELSE 28 END
END
RETURN @rtDate
END
GO
ResultSet:
NumDaysInMonth
31
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 Subqueries
USE AdventureWorks;
GO
SELECT e.EmployeeID
FROM HumanResources.Employee e
WHERE e.ContactID IN
(
SELECT c.ContactID
FROM Person.Contact c
WHERE 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 Subqueries
USE AdventureWorks;
GO
SELECT e.EmployeeID
FROM HumanResources.Employee e
WHERE e.ContactID IN
(
SELECT c.ContactID
FROM Person.Contact c
WHERE 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.
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.
1) Step 1 : Go to Start >> Run >> Type cmd and press enter.
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.
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.
SQL SERVER SQL Joke, SQL Humor, SQL Laugh Valid SQL Error
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.
If you know source of this image please let me know I would like to include that. Visit more SQL Server
Humors.
SQLAuthority News Interesting Read Using A SQL JOIN In A SQL UPDATE/Delete Statement
Ben Nadel
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.
If you on the site of Ben Nadel, checkout the Free ColdFusion Calender System.
SQL SERVER 2005 Find Tables With Primary Key Constraint in Database
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?
SQL SERVER 2005 Find Tables With Foreign Key Constraint in Database
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?
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
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 AdventureWorks
GO
--Searching for Empoloyee table
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Employee%'
GO
--Searching for Empoloyee table and RateChangeDate column together
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Employee%'
AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%RateChangeDate%'
GO
ResultSet:
Name
uspGetEmployeeManagers
uspGetManagerEmployees
uspUpdateEmployeeHireInfo
uspUpdateEmployeeLogin
uspUpdateEmployeePersonalInfo
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
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.
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.
ONLINE
Database is available for access.
OFFLINE
Database is unavailable.
RESTORING
One or more files of the primary filegroup are being restored, or one or more secondary files are being
restored offline.
RECOVERING
Database is being recovered.
RECOVERY PENDING
SQL Server has encountered a resource-related error during recovery.
SUSPECT
At least the primary filegroup is suspect and may be damaged.
EMERGENCY
User 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.
Example:
SELECT DATABASEPROPERTYEX('AdventureWorks', 'Status')
DatabaseStatus_DATABASEPROPERTYEX
GO
SELECT state_desc DatabaseStatus_sysDatabase
FROM sys.databases
WHERE name = 'AdventureWorks'
GO
ResultSet:
DatabaseStatus_DATABASEPROPERTYEX
ONLINE
DatabaseStatus_sysDatabase
ONLINE
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.
SQL_Latin1_General_CP1_CI_AS
2) Using SQL Server Management Studio
Refer the following two diagram to find out the SQL Collation.
Write Click on Database
Click on Properties
SQL SERVER Difference and Explanation among DECIMAL, FLOAT and NUMERIC
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.
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.
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.
SQL SERVER 2005 Use Always Outer Join Clause instead of (*= and =*)
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 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.
SQL SERVER FIX : Error : msg 2540 The system cannot self repair this error
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:
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.
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.
SQL SERVER 2005 Use of Non-deterministic Function in UDF Find Day Difference Between
Any Date and Today
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.
SQL SERVER T-SQL Script to Insert Carriage Return and New Line Feed in Code
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;
GO
PRINT '---------------------------------'
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 return
SQLAuthority.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
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
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.
Conclusion
Simplicity is an implementation philosophy and its a very important one.
SQLAuthority News Book Review Sams Teach Yourself Microsoft SQL Server T-SQL in
10 Minutes
Sams Teach Yourself Microsoft SQL Server T-SQL in 10 Minutes (Sams Teach Yourself)
by Ben Forta
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.
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.
Chapter 10: Using Data Manipulation Functions
It 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.
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.
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
Pinal Dave
Principal Database Administrator
SQL SERVER Find Last Day of Any Month Current Previous Next
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.
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 Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth
ResultSet:
LastDay_PreviousMonth
2007-07-31 23:59:59.000
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 Year
DECLARE @dtDate DATETIME
SET @dtDate = '8/18/2007'
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
LastDay_AnyMonth
ResultSet:
LastDay_AnyMonth
2007-08-31 23:59:59.000
SQL SERVER 2005 Explanation and Script for Online Index Operations Create,
Rebuild, Drop
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;
GO
ALTER INDEX ALL ON Production.Product
REBUILD WITH (ONLINE = ON);
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)
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.
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.
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.
SQL SERVER 2005 Difference and Similarity Between NEWSEQUENTIALID() and NEWID()
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.
ResultSet:
NewIDCol NewSeqCol
DC896759-8B6B-4A62-8EC8-970BE2F0F04C 3D540550-2138-DC11-BF85-00123FD0986A
71129CD4-3A25-470A-AE8E-9475379EC6A7 3E540550-2138-DC11-BF85-00123FD0986A
B915CCDB-F480-4D89-ADD7-40D5DDE4FD52 3F540550-2138-DC11-BF85-00123FD0986A
5920DA2E-6CC2-4FE3-9C13-F5155B1923A0 40540550-2138-DC11-BF85-00123FD0986A
6C60BFD9-ACE1-4F74-BB74-99343A3A707D 41540550-2138-DC11-BF85-00123FD0986A
It 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 error
SELECT NEWSEQUENTIALID()
GO
ResultSet:
Msg 302, Level 16, State 0, Line 1
The 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 GUID
SELECT NEWID()
GO
ResultSet:
26CE6817-B138-413A-92AD-A2F2BBF7E0B8
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.
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.
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)
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.
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.
Pinal Dave
Principal 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.
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.
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.
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 vTestContactID
AS
SELECT FirstName, LastName
FROM Person.Contact
GO
Call the VIEW using
ORDER BY clause.
SELECT *
FROM vTestContactID
ORDER BY FirstName DESC
I really enjoyed writing the solution for this problem.
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 Backup
a. Schedule Backup Routines
b. Backup medium and redundancy
c. SQL Server 2005 T-SQL improvement with regards to backup
2) Index Optimization
a. Implementing Primary Key on non-standard columns for improving performance in certain cases
b. Index statistic optimization
3) Maintenance Tasks
a. Index Re-building
b. Database Consistency Check alerts
4) Replication
a. Snapshot replication optimization (use of new copy database feature)
b. Log-shipping failover set up
5) Architecture Designs
a. Setup Replications over database mirroring
b. Database Normalization advantages and performance
c. TempDB optimization
d. Datafile (.mdf) and Logfile (.ldf) filegroup placement
e. Foreign key relations
f. Re-factoring database schemas based on statistics collected from profiler
g. Analysis of hardware (disk, CPU, connections etc)
f. Security of Database
6) System Tables
a. 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).
QLAuthority News Book Review Learning SQL on SQL Server 2005 (Learning)
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.
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.
Pinal Dave
Principal Database Administrator
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
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 BIT
BEGIN
DECLARE @Ret BIT
IF LEFT(@Number, 1) = '-'
SET @Number = SUBSTRING(@Number, 2, LEN(@Number))
IF (PATINDEX('%[^0-9-]%, @Number) = 0
AND CHARINDEX(-', @Number) <= 1
AND @Number NOT IN ('.', '-', '+', '^')
AND LEN(@Number)>0
AND @Number NOT LIKE '%-%')
SET @Ret = 1
ELSE
SET @Ret = 0
RETURN @Ret
END
GO
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 0
This 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
This post is second part of my previous post about SQL SERVER 2005 List All Stored Procedure
Modified in Last N Days
This post demonstrates the script which displays create date and modify date for any specific stored
procedure in SQL Server.
USE AdventureWorks;
GO
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = 'uspUpdateEmployeeHireInfo'
GO
SQL SERVER 2005 List All The Column With Specific Data Types
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 database
SELECT OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE t.name = 'text' --you can change text to other datatypes
ORDER BY c.OBJECT_ID;
GO
Script 2 : Extended script to identify all the columns datatype and other information in specific
database
SELECT
OBJECT_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.scale
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
ORDER BY c.OBJECT_ID;
Right-click on Database click on Properties and click on Files. There will be column of Autogrowth, click on
small box with three () dots.
SQL SERVER 2005 List Tables in Database Without Primary Key
This is very simple but effective script. It list all the table without primary keys.
USE DatabaseName;
GO
SELECT SCHEMA_NAME(schema_id) AS SchemaName,name AS TableName
FROM sys.tables
WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0
ORDER BY SchemaName, TableName;
GO
SQL SERVER Fix : Error 2596 The repair statement was not processed. The database cannot
be in read-only mode
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.
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;
GO
ALTER DATABASE AdventureWorks
SET SINGLE_USER
WITH
ROLLBACK IMMEDIATE;
GO
ALTER DATABASE AdventureWorks
SET READ_WRITE;
GO
ALTER DATABASE AdventureWorks
SET MULTI_USER;
GO
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).
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.
Server can be turned off using windows services as well. SHUTDOWN permissions are assigned to
members of the sysadmin and serveradmin fixed server roles.
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.
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
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.
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
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.
For more information please see the SQL Server Compact 3.5 Books Online
SQL SERVER Two Different Ways to Comment Code Explanation and Example
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 name
FROM Sales.Products
WHERE 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:
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
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
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.
Pinal Dave
Principal 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
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.
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 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.
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.
http://www.pinaldave.com
http://www.SQLAuthority.com
SQL SERVER Data Warehousing Interview Questions and Answers Complete List Download
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)
Ralph Kimballs paradigm: Data warehouse is the conglomerate of all data marts within the enterprise.
Information is always stored in the dimensional model.
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 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 doesnt 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.
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 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.
Process Goal
OLTP: Snapshot of business processes which does fundamental business tasks
OLAP: Multi-dimensional views of business activities of planning and decision making
Database Design
OLTP: 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.
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 Ive picked up while taking my time to
explore the nooks and crannies of my universitys 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
This series is in response to many of my readers 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.
I will post complete series details here. Please watch this space for additional information.
SQL SERVER 2005 Server and Database Level DDL Triggers Examples and Explanation
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 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.
Following example demonstrates how DDL trigger can be used to prevent dropping stored procedure.
Step 1 :
GO
AS
SELECT 1 test;
GO
Step 2 :
Create DDL trigger which will prevent dropping the stored procedure.
USE AdventureWorks
GO
ON DATABASE
FOR DROP_PROCEDURE
AS
Script :
ROLLBACK;
GO
Step 3 :
USE AdventureWorks
GO
GO
This should throw following message along with error code 3609 :
Script :
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
GO
List of all the DDL events (DROP_PROCEDURE in example above) to use with DDL Trigger are listed on
MSDN.
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.
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')
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:
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.
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.
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.
4. Make sure system tables of Master database allows to update the values.
USE MASTER
GO
sp_CONFIGURE 'allow updates', 1
RECONFIGURE WITH OVERRIDE
GO
5. Change database mode to emergency mode.
Following statement will return the current status of the database
SELECT *
FROM sysdatabases
WHERE name = 'yourdatabasename'
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.
9. Turn off the update to system tables of Master database running following script.
USE MASTER
GO
sp_CONFIGURE 'allow updates',0
RECONFIGURE WITH OVERRIDE
GO
This 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 database
BEGIN
UPDATE sysdatabases
SET status = (value retrieved IN first query OF STEP 5)
WHERE name = 'yourdatabasename
COMMIT TRAN
GO'
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
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.
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.
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.
Reference
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.
SQL SERVER Restore Database Without or With Backup Everything About Restore
and Backup
How to revert the changes, I have only logs but no complete backup?
Answer:
You need complete backup to rollback your changes. If you do not have complete backup you can not
revert back. Sorry.
3) Restore the second most latest (latest 1) transaction back. Now restore the log to the point step by
step.
Reference :
Disaster Recovery
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:
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 AdventureWorks
GO
DECLARE @OrderBy VARCHAR(10)
DECLARE @OrderByDirection VARCHAR(1)
SET @OrderBy = 'State' ----Other options Postal for PostalCode,
---- State for StateProvinceID, City for City
SET @OrderByDirection = 'D' ----Other options A for ascending,
---- D for descending
SELECT AddressID, City, StateProvinceID, PostalCode
FROM person.address
WHERE AddressID < 100
ORDER BY
CASE 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 END
GO
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
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.
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
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.
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()
SQL SERVER 2005 Use ALTER DATABASE MODIFY NAME Instead of sp_renameDB to rename
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.
SQL SERVER Validate Field For DATE datatype using function ISDATE()
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.
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 date
SELECT ISDATE('30/2/2007')
RETURNS : 0 (Zero)
----Valid date
SELECT ISDATE('12/12/20007)'
RETURNS : 1 (ONE)
----Invalid DataType
SELECT ISDATE('SQL')
RETURNS : 0 (Zero)
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
SQL SERVER 2005 Features Comparison Chart
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.
SQL SERVER 2008 Scheduled Launch at an Event in Los Angeles on Feb. 27, 2008
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.
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.
SQL SERVER 2005 List All Stored Procedure Modified in Last N Days
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 name
FROM sys.objects
WHERE 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.
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,create_date, GETDATE()) < 7
----Change 7 to any other day value.
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()
GO
SELECT POWER(2,5)
GO
SELECT POWER(8,-2)
GO
SELECT EXP(99)
GO
SELECT EXP(1)
GO
Results Set :
PI
-
3.14159265358979
PowerEg1
32
PowerEg2
0
ExpEg1
-
9.88903031934695E+42
ExpEg2
-
2.71828182845905
Now the Questions asked in the Title of the Article What is the result of EXP to the POWER of
PI
SELECT 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
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 TINYINT
SELECT ISNULL(@MyVal,'123456') AS MyVal
The error received from above script is :
Msg 245, Level 16, State 1, Line 3
Conversion 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.
SQL SERVER SQL Joke, SQL Humor, SQL Laugh Generic Quotes
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.
Meilir Page-Jones.
Einstein
Abraham Lincoln reportedly said that, given eight hours to chop down a tree, hed spend six sharpening
his axe.
Larry Zana
A: QA testers dont change anything. They just report that its dark.
Kerry Zallar
Andrew Siwko
Karin Donker
If youve found 3 bugs in a program, best estimate is that there are 3 more.
Few of the questions I receive very frequently. I have collect them in spreadsheet and try to answer them
frequently.
Will CAST or CONVERT thrown an error when column values converted from alpha-numeric
characters to numeric?
YES.
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
SQL SERVER FIX : Error : msg 8115, Level 16, State 2, Line 2 Arithmetic overflow error
converting expression to data type
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.
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.
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.
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
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.
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)
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.
#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.
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 variables does not. Temp Table definition can be changed after it is created. Temp
table can be explicitly dropped as well.
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.
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.
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.
SQL SERVER Explanation of WITH ENCRYPTION clause for Stored Procedure and User
Defined Functions
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)
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.
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 dat
abase.
USE AdventureWorks;
GO
EXEC sp_recompile N'Sales.Customer';
GO
----Following script will recompile specific stored procedure uspGetBillOfMaterials only.
USE AdventureWorks;
GO
EXEC sp_recompile 'uspGetBillOfMaterials';
GO
Following are some important improvements in tempdb in SQL Server 2005 over SQL Server
2000
Input/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.
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
SQL SERVER Running Batch File Using T-SQL xp_cmdshell bat file
In last month I received few emails emails regarding SQL SERVER Enable xp_cmdshell using
sp_configure.
The questions are
1) What is the usage of xp_cmdshell and
2) How to execute BAT file using T-SQL?
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
This is very simple and can be achieved using system table sys.tables.
USE YourDBName
GO
SELECT *
FROM sys.Tables
GO
This will return all the tables in the database which user have created.
Explanation : ServerName.DatabaseName.DatabaseOwner.TableName
Example : localhost.AdventureWorks.Person.Contact
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.
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)
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.
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.
Books 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
Pros :
Bonus articles in CD
Cons:
Lack of examples or quiz at the end of chapters (for those who like to check their knowledge after reading
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.
SQL SERVER Comparison Index Fragmentation, Index De-Fragmentation, Index Rebuild SQL
SERVER 2000 and SQL SERVER 2005
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.
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.
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.
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.
Explanation of NULLIF
Syntax:
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.
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.
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?
I have recently received many requests to add an iGoogle Gadget so it can be integrated on iGoogle home
page so Ive gone ahead and done so: Add iGoogle Gadget
SQL SERVER Retrieve Current Date Time in SQL Server CURRENT_TIMESTAMP, GETDATE(),
{fn NOW()}
There are three ways to retrieve the current datetime in SQL SERVER.
CURRENT_TIMESTAMP, GETDATE(), {fn NOW()}
CURRENT_TIMESTAMP
CURRENT_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_TIMESTAMP
GO
SELECT {fn NOW()}
GO
SELECT 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!!!
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
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)
SQL Server Database Coding Standards and Guidelines Complete List Download (PDF)
SQLAuthority Feed
Thank you,
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 seconds
WAITFOR DELAY '000:00:20'
SELECT '20 Second Delay'
GO
----Delay till 7 AM
WAITFOR TIME '7:00:00'
SELECT 'Good Morning'
GO
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.
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
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.
SELECT
dbo.udf_StripHTML('<b>UDF at SQLAuthority.com </b><br><br><a href="http://www.SQLAuthority.co
m">SQLAuthority.com</a>')
Result Set:
If you want to see this example in action click on Image. It will open large image.
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.
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.
c:\>sqlcmd -i instpubs.sql
c:\>sqlcmd -i instnwnd.sql
SQL SERVER Easy Sequence of SELECT FROM JOIN WHERE GROUP BY HAVING ORDER BY
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 yourcolumns
FROM tablenames
JOIN tablenames
WHERE condition
GROUP BY yourcolumns
HAVING aggregatecolumn condition
ORDER 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.
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).
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.
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.
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
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)
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.
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.
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 FULL
GO
Microsoft TechNet
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 = NULL
IF (LEN(@MyVar) = 0)
I decided to send following code to them. After running the following sample code it was clear that LEN of
NULL values is not 0 (Zero) but it is NULL. Similarly, the result for DATALENGTH function is the same.
DATALENGTH of NULL is NULL.
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 ID
FROM ItemsTable
INNER JOIN AccountsTable
WHERE ItemsTable.Collation1Col = AccountsTable.Collation2Col
SELECT ID
FROM ItemsTable
INNER JOIN AccountsTable
WHERE ItemsTable.Collation1Col COLLATE DATABASE_DEFAULT
= AccountsTable.Collation2Col COLLATE DATABASE_DEFAULT
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
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.
SQL SERVER Retrieve Select Only Date Part From DateTime Best Practice
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
I asked him to come up with solution by using date functions. The method he suggested was to use
SELECT 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.
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:
Error:
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.Department
ORDER BY GroupName, Name') AS a;
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.
Very interesting paper written by An Introduction to Spatial Database Systems by Ralf Hartmut Gting.
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.
SQL SERVER UDF Function to Display Current Week Date and Day Weekly Calendar
June 8, 2007 by pinaldave
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.
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 days
SELECT *
FROM dbo.udf_DisplayCurrentWeekDateDays(DATEADD(d,-7,GETDATE()))
GO
2007-08-11 00:00:00.000
SQL SERVER Insert Multiple Records Using One Insert Statement Use of UNION ALL
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 YourDB
GO
INSERT 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 YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
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.
SQL SERVER 2008 (Katmai) June CTP Released Improvement Pillars Diagram
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.
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.
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
Download SQL SERVER Database Coding Standards and Guidelines Complete List
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
DIGG
Coding
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 Products
WHERE ID IN
(
SELECT TOP 2 ID
FROM Products
ORDER 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 Price
FROM Products
ORDER 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 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 dont 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:
12) You might need the length of a string variable in many places of your procedure, but dont call the
LEN function whenever its needed. Instead, call the LEN function once and store the result in a variable
for later use.
13)
IF EXISTS (
SELECT 1
FROM Products
WHERE ID = 50)
Instead Of:
IF EXISTS (
SELECT COUNT(ID)
FROM Products
WHERE 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 Guidelines
SQL SERVER Database Coding Standards and Guidelines Introduction
SQL SERVER Database Coding Standards and Guidelines Part 1
SQL SERVER Database Coding Standards and Guidelines Part 2
SQL SERVER Database Coding Standards and Guidelines Complete List Download
Naming
Examples: TR_Orders_UpdateProducts
Notes: The use of triggers is discouraged
Examples: IX_Products_ProductID
Examples: PK_Products
Example: FK_Products_Orderss
Example: DF_Products_Quantity
General Rules:
Structure
Formatting
Reference:
1) Group related table names:
Products_USA
Products_India
Products_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, Table2
WHERE Table1.d = Table2.c
True code:
SELECT *
FROM Table1
INNER JOIN Table2 ON Table1.d = Table2.c
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.
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.
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 Employees ID number for each record and also a field that displays the ID
number of an Employees 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;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID = pv2.VendorID
ORDER BY pv1.ProductID
SQL SERVER 2005 Microsoft SQL Server Management Pack for Microsoft Operations
Manager 2005 Download SQL Server MOM 2005
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.
SQLAuthority News Dedicated Search Engine for SQLAuthority Search SQL Solutions
Visit search.SQLAuthority.com
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
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.
The solution we came up was to put constraint on the VARCHAR(MAX). SQL SERVER 2005 supports
VARCHAR(MAX) and Constraint.
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
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.
SQL SERVER Primary Key Must Not Contain NULL Primary Key are NOT NULL
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
property cant be set on a column that is part of the primary key. All columns that are part of a tables 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
SQLAuthority.com News Best SQL Job Search Best SQL Job List Find SQL Jobs
Visit : http://jobs.SQLAuthority.com
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.
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.
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.
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)
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 Fix : Error : Server: Msg 544, Level 16, State 1, Line 1 Cannot insert explicit
value for identity column in table
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:
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.
sp_dbcmptlevel
Sets certain database behaviors to be compatible with the specified version of SQL Server.
Example:
----SQL Server 2005 database compatible level to SQL Server 2000
EXEC sp_dbcmptlevel AdventureWorks, 80;
GO
----SQL Server 2000 database compatible level to SQL Server 2005
EXEC sp_dbcmptlevel AdventureWorks, 90;
GO
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.
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).
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
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.
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?
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
Microsoft ADOMD.NET
Microsoft Core XML Services (MSXML) 6.0
Microsoft OLEDB Provider for DB2
Microsoft SQL Server Management Pack for MOM 2005
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
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,LastName
FROM Person.Contact
TABLESAMPLE SYSTEM (10 PERCENT)
Example 2:
SELECT FirstName,LastName
FROM Person.Contact
TABLESAMPLE 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 tables 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. .
SQL SERVER 2005 Replace TEXT with VARCHAR(MAX) Stop using TEXT, NTEXT, IMAGE
Data Types
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
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.
Related Post:
SQL SERVER 2005 Find Tables With Primary Key Constraint in Database
SQL SERVER 2005 Find Tables With Foreign Key Constraint in Database
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 tables
data and reduce the potential for page splits.
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', 1
GO
RECONFIGURE
GO
sp_configure 'fill factor', 90
GO
RECONFIGURE
GO
SQL SERVER Stored Procedure to display code (text) of Stored Procedure, Trigger, View
or Object
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.
Syntax
sp_helptext @objname = 'name'
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
Few days ago I was asked what is our SQL Servers 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
about my database reaching its limit.
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure
GO
EXEC sp_configure 'show advanced options', 0
GO
To 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', 1
GO
RECONFIGURE
GO
sp_configure 'resource timeout', 100
GO
RECONFIGURE
GO
Results 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 0
affinity I/O mask -2147483648 2147483647 0 0
affinity mask -2147483648 2147483647 0 0
Agent XPs 0 1 1 1
allow updates 0 1 0 0
awe enabled 0 1 0 0
blocked process threshold 0 86400 0 0
c2 audit mode 0 1 0 0
clr enabled 0 1 0 0
common criteria compliance enabled 0 1 0 0
cost threshold for parallelism 0 32767 5 5
cross db ownership chaining 0 1 0 0
cursor threshold -1 2147483647 -1 -1
Database Mail XPs 0 1 0 0
default full-text language 0 2147483647 1033 1033
default language 0 9999 0 0
default trace enabled 0 1 1 1
disallow results from triggers 0 1 0 0
fill factor (%) 0 100 0 0
ft crawl bandwidth (max) 0 32767 100 100
ft crawl bandwidth (min) 0 32767 0 0
ft notify bandwidth (max) 0 32767 100 100
ft notify bandwidth (min) 0 32767 0 0
index create memory (KB) 704 2147483647 0 0
in-doubt xact resolution 0 2 0 0
lightweight pooling 0 1 0 0
locks 5000 2147483647 0 0
max degree of parallelism 0 64 0 0
max full-text crawl range 0 256 4 4
max server memory (MB) 16 2147483647 2147483647 2147483647
max text repl size (B) 0 2147483647 65536 65536
max worker threads 128 32767 0 0
media retention 0 365 0 0
min memory per query (KB) 512 2147483647 1024 1024
min server memory (MB) 0 2147483647 0 0
nested triggers 0 1 1 1
network packet size (B) 512 32767 4096 4096
Ole Automation Procedures 0 1 0 0
open objects 0 2147483647 0 0
PH timeout (s) 1 3600 60 60
precompute rank 0 1 0 0
priority boost 0 1 0 0
query governor cost limit 0 2147483647 0 0
query wait (s) -1 2147483647 -1 -1
recovery interval (min) 0 32767 0 0
remote access 0 1 1 1
remote admin connections 0 1 0 0
remote login timeout (s) 0 2147483647 20 20
remote proc trans 0 1 0 0
remote query timeout (s) 0 2147483647 600 600
Replication XPs 0 1 0 0
scan for startup procs 0 1 0 0
server trigger recursion 0 1 1 1
set working set size 0 1 0 0
show advanced options 0 1 1 1
SMO and DMO XPs 0 1 1 1
SQL Mail XPs 0 1 0 0
transform noise words 0 1 0 0
two digit year cutoff 1753 9999 2049 2049
user connections 0 32767 0 0
user options 0 32767 0 0
Web Assistant Procedures 0 1 0 0
xp_cmdshell 0 1 1 1
Configuration option show advanced options changed from 1 to 0. Run the RECONFIGURE statement to
install.
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.
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.
Following script will display Left Anti Semi Join Showplan Operator in the result pan.
USE AdventureWorks;
GO
SET SHOWPLAN_TEXT ON
GO
SELECT ProductID
FROM Production.Product
WHERE ProductID
NOT IN (
SELECT ProductID
FROM Production.WorkOrder);
GO
SET SHOWPLAN_TEXT OFF
GO
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)
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 Roberts 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.
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,
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.
SQL SERVER Top 15 free SQL Injection Scanners Link to Security Hacks
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.
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 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 tempdb
go
create procedure SP_NonFatal_INSERT @Column2 int =NULL
AS declare @ErrorMsgID int insert NonFatal
values (@Column2) set @ErrorMsgID =@@ERROR
if @ErrorMsgID 0 BEGIN
RAISerror (An error occured updating the NonFatal table,10,1) end
GO
Tool 2 : SQLinForm
USE tempdb GO
CREATE PROCEDURE
sp_NonFatal_INSERT @Column2 INT =NULL
AS
DECLARE
@ErrorMsgID INT
INSERT NonFatal VALUES (@Column2) SET @ErrorMsgID =@@ERROR
IF @ErrorMsgID 0
BEGIN
RAISERROR ('An error occured updating the NonFatal table',10,1)
END
Following query will find the last day of the month. Query also take care of Leap Year.
Script:
(1 row(s) affected)
LastDayOfMonth
-----------------------
2007-02-28 00:00:00.000
(1 row(s) affected)
ASCII Returns the ASCII code value of the leftmost character of a character expression.
Examples:
----Decimal to ASCII
SELECT CHAR(80)+CHAR(73)+CHAR(78)+CHAR(65)+CHAR(76) AS SQLAuthorityAuthor
GO
----ASCII to Decimal
SELECT ASCII('P') AS SQLAuthorityAuthor
UNION ALL
SELECT ASCII('I')
UNION ALL
SELECT ASCII('N')
UNION ALL
SELECT ASCII('A')
UNION ALL
SELECT ASCII('L')
GO
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 Functions
Absolute value ABS
Arc cosine ACOS
Arc sine ASIN
Arc tangent of n ATAN
Arc tangent of n and m ATN2
Smallest integer >= value CEILING
Cosine COS
Hyperbolic cosine COT
Exponential value EXP
Round down to nearest integer FLOOR
Natural logarithm LOG
Logarithm, base 10 LOG10
Modulus (remainder) USE MODULO (%) OPERATOR
Power POWER
Random number RAND
Round ROUND
Sign of number SIGN
Sine SIN
Square root SQRT
Tangent TAN
Convert number if NULL ISNULL
Standard deviation STDEV
Variance VAR
SQL SERVER 2005 Understanding Trigger Recursion and Nesting with examples
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.
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.
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 AdventureWorks
GO
----Diable Index
ALTER INDEX [IX_StoreContact_ContactTypeID] ON Sales.StoreContact DISABLE
GO
----Enable Index
ALTER INDEX [IX_StoreContact_ContactTypeID] ON Sales.StoreContact REBUILD
GO
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
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 others
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
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:
SQL SERVER Fix: Error 130: Cannot perform an aggregate function on an expression
containing an aggregate or a subquery
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 doesnt support it.
USE PUBS
GO
SELECT AVG(COUNT(royalty)) RoyaltyAvg
FROM dbo.roysched
GO
You can get around this problem by breaking out the computation of the average in derived tables.
USE PUBS
GO
SELECT AVG(t.RoyaltyCounts)
FROM
(
SELECT COUNT(royalty) AS RoyaltyCounts
FROM dbo.roysched
)T
GO
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
VALUES (0)
INSERT @Binary
VALUES (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 a
CROSS JOIN @Binary b
CROSS JOIN @Binary c
CROSS JOIN @Binary d
CROSS JOIN @Binary e
CROSS JOIN @Binary f
CROSS JOIN @Binary g
CROSS JOIN @Binary h
CROSS JOIN @Binary i
ORDER 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
0000000000
1000000001
2000000010
3000000011
4000000100
5000000101
6000000110
7000000111
8000001000
9000001001
10 0 0 0 0 0 1 0 1 0
11 0 0 0 0 0 1 0 1 1
12 0 0 0 0 0 1 1 0 0
13 0 0 0 0 0 1 1 0 1
14 0 0 0 0 0 1 1 1 0
15 0 0 0 0 0 1 1 1 1
16 0 0 0 0 1 0 0 0 0
- many rows -
509 1 1 1 1 1 1 1 0 1
510 1 1 1 1 1 1 1 1 0
511 1 1 1 1 1 1 1 1 1
Database Consistency Checker (DBCC) commands can gives valuable insight into whats 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 (?)
GO
To learn about syntax of an individual DBCC command run following script in query analyzer.
DBCC HELP(<command>)
GO
Following is the list of all the DBCC commands and their syntax. List contains all documented and
undocumented DBCC commands.
DBCC activecursors [(spid)]
DBCC cachestats
DBCC callfulltext
DBCC config
DBCC debugbreak
DBCC dropcleanbuffers
DBCC errorlog
DBCC freeproccache
DBCC memorymap
DBCC memorystatus
DBCC memospy
DBCC perflog
DBCC perfmon
DBCC proccache
DBCC resource
DBCC showoffrules
DBCC showonrules
DBCC showweights
DBCC sqlmgrstats
This one of the very interesting article I read regarding SQL Server 2005 Storage. Please refer original
article at MS TechNet here.
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 CPUs has scalability advantages for allocation intensive
workloads.
Dont overlook some of SQL Server basics.
Dont overlook storage configuration bases.
SQL SERVER Query to Find First and Last Day of Current Month
Following query will run respective to todays 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.
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)
AS
BEGIN
DECLARE @IncorrectCharLoc SMALLINT
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
WHILE @IncorrectCharLoc > 0
BEGIN
SET @string = STUFF(@string, @IncorrectCharLoc, 1, '')
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
END
SET @string = @string
RETURN @string
END
GO
-Test
SELECT dbo.UDF_ParseAlphaChars('ABC_I+{D[]}4|:e;5,<.F>/?6')
GO
I personally use EXEC sp_databases because it gives the same results as other but it is self explaining.
----SQL SERVER 2005 System Procedures
EXEC sp_databases
EXEC sp_helpdb
----SQL 2000 Method still works in SQL Server 2005
SELECT name
FROM sys.databases
SELECT name
FROM sys.sysdatabases
----SQL SERVER Un-Documented Procedure
EXEC sp_msForEachDB 'PRINT ''?'''
SQL SERVER Fix : Error : Msg 6263, Level 16, State 1, Line 2 Enabling SQL Server 2005 for
CLR Support
Error:
Fix : Error : Msg 6263, Level 16, State 1, Line 2 Enabling SQL Server 2005 for CLR Support
Fix/Workaround/Solution:
sp_CONFIGURE 'clr_enabled',1
GO
RECONFIGURE
GO
If CLR procedure is used without enabling CLR, it will show error message as .NET Framework is not
enabled.
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
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.
SQL SERVER Download Microsoft SQL Server 2005 System Views Map
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 Kinkos.
Reference : Pinal Dave (http://blog.SQLAuthority.com) MS SQL Server (All the above text)
Error:
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 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
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.
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.
SQL SERVER Fix : Error 2501 : Cannot find a table or object with the name . Check the
system catalog.
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.
Use object belongs to other owner use two parts name as scheme_name.object_name.
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
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.
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
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.
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
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.exe
2. Triggers for Logon Events (New in Service Pack 2)
3. Boosting performance with persisted-computed-columns (pcc).
4. DEFAULT_SCHEMA setting in sys.database_principles
5. Forced Parameterization
6. Vardecimal Storage Format
7. Indexing made easier with SQL Server 2005
8. Figuring out the most popular queries in seconds
9. Scalable Shared Databases
10. Soft-NUMA
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 (IFELSE, 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 GOTO
I 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.
SQL SERVER Creating Comma Separate Values List from Table UDF SP
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.
NumberCols
first
second
third
fourth
fifth
Output : first,second,third,fourth,fifth
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 NumberTable
SELECT 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).
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.
(4 row(s) affected)
Example2
-
111
222
333
444
555
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.
SQL SERVER UDF User Defined Function to Find Weekdays Between Two Dates
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.
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
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 1
Cannot 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:
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
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.
SQL SERVER DBCC commands to free several SQL Server memory caches
DBCC FREESYSTEMCACHE
Releases 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 FREESESSIONCACHE
Flushes the distributed query connection cache used by distributed queries against an instance of
Microsoft SQL Server.
DBCC FREEPROCCACHE
Removes all elements from the procedure cache.
SQL SERVER Enable Login Disable Login using ALTER LOGIC Change name of the SA
In SQL SERVER 2005, all the login (including sa ) can be enabled and disabled using ALTER LOGIN
command.
To disable sa login:
ALTER LOGIN sa DISABLE
GO
To enable sa login:
ALTER LOGIN sa ENABLE
GO
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
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.
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.
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(*)/4
FROM 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 5
UPDATE TableName
SET TableColumn = 14
SET ROWCOUNT 0
In SQL SERVER 2005 limited row modification can be achieved by TOP keyword function. Example,
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.
If Column1 of Table1 has following values CaseSearch, casesearch, CASESEARCH, CaSeSeArCh, following
statement will return you all the four records.
SELECT Column1
FROM Table1
WHERE 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 Column1
FROM Table1
WHERE Column1 COLLATE Latin1_General_CS_AS = 'casesearch'
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.
To know the collation of the column for any table run following Stored Procedure.
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
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 1
The 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 1
RESTORE 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.
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.
SQL SERVER SET ROWCOUNT Retrieving or Limiting the First N Records from a
SQL Query
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 10
SELECT *
FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate
SET ROWCOUNT 0
To set this option off so that all rows are returned, specify SET ROWCOUNT 0.
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, its better to turn SET ROWCOUNT n on just before the final SELECT statement that returns
the records.
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.
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.
Publisher
The publisher is the source database where replication begins. It makes data available for replication.
Subscriber
The 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.
Distributor
The 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.
Publication
The publication is the storage container for different articles. A subscriber can subscribe to an individual
article or an entire publication.
Article
An 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 commit
Two-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
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 pubs
GO
SELECT a.au_id
FROM authors a
JOIN titleauthor b ON a.au_id = b.au_id
OPTION (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.
Product Evaluation
Getting Started
Development
Deployment
Operations
Troubleshooting
Technical Reference
Administrator
Developer
Architect
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.
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', TRUE
sp_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 theyre 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, qty
Legal:
SELECT qty, orderid, SUM(qty)
You cant use ROWSET, UNION, TOP, ORDER BY, DISTINCT, COUNT(*), COMPUTE, or COMPUTE BY.
The AVG, MAX, MIN, STDEV, STDEVP, VAR, and VARP aggregate functions arent allowed in the SELECT
statement.
If you use GROUP BY, you cant use HAVING, ROLLUP, or CUBE, and you must use COUNT_BIG() in the
select list.
You cant modify more than one table at a time through a view.
If your view is based on aggregate functions, you cant use it to modify data.
If your view is based on a table that contains fields that dont allow null values yet your view doesnt
display those fields, then you wont be able to insert new data.
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
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.
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.
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.
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.
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.
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.
Ask someone for help if you need it. We all need to learn.
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 E1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(E2.Salary))
FROM Employee E2
WHERE 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.
Locking Hints and Examples are as follows. The usage of them is same same but effect is different.
ROWLOCK
Use row-level locks when reading or modifying data.
PAGLOCK
Use page-level locks when reading or modifying data.
TABLOCK
Use a table lock when reading or modifying data.
DBLOCK
Use a database lock when reading or modifying data.
UPDLOCK
UPDLOCK reads data without blocking other readers, and update it later with the assurance that the data
has not changed since last read.
XLOCK
Use exclusive locks instead of shared locks while reading a table, and use hold locks until the end of the
statement or transaction.
HOLDLOCK
Use 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.
NOLOCK
This does not lock any object. This is the default for SELECT operations. It does not apply to INSERT,
UPDATE, and DELETE statements.
Examples:
SELECT OrderID
FROM Orders (WITH ROWLOCK)
WHERE OrderID BETWEEN 100
AND 2000
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.
Unique Index and Unique Constraint are the same. They achieve same goal. SQL Performance is same for
both.
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.
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.
GO
RECONFIGURE
GO
GO
RECONFIGURE
GO
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
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.
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.sysmessages
The 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.
Severity levels 11 to 16 are generated as a result of user problems and can be fixed by the
11 to 16 user. For example, the error message returned in the invalid update query, used earlier,
had a severity level of 16.
Severity level 17 indicates that SQL Server has run out of a configurable resource, such as
17 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.
Severity level 21 indicates that SQL Server has encountered a problem that affects all the
21
processes in a database.
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
22
disk, the restart corrects the problem. Otherwise, use DBCC to determine the extent of the
damage and the required action to take.
Severity level 23 indicates a suspect database. To determine the extent of the damage and
23
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.
This topic describes the Database Engine features that are no longer available in SQL Server 2008.
sp_runwebtask
sp_enumcodepages
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 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.
There will be no spaces around them. It is very little but useful trick.
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.
SQL SERVER Fix: Sqllib error: OLEDB Error encountered calling IDBInitialize::Initialize. hr =
080004005. SQLSTATE: 08001, Native Error: 17
Error received:
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 are listed on the Collation Settings page of the SQL Server Installation
Wizard.
SQL
sort Sort order
Description SQL collation
order name
ID
31 diction.437 Dictionary order, case-sensitive SQL_Latin1_General_Cp437_CS_AS_KI_WI
Dictionary order, case-
32 nocase.437 SQL_Latin1_General_Cp437_CI_AS_KI_WI
insensitive
Dictionary order, case-
33 nocasepr.437 insensitive, uppercase SQL_Latin1_General_Pref_Cp437_CI_AS_KI_WI
preference
Dictionary order, case-
34 noaccent.437 SQL_Latin1_General_Cp437_CI_AI_KI_WI
insensitive, accent-insensitive
40 cp437bin.437 Binary SQL_Latin1_General_Cp437_BIN
40 cp850bin.850 Binary SQL_Latin1_General_Cp850_BIN
41 diction.850 Dictionary order, case-sensitive SQL_Latin1_General_Cp850_CS_AS_KI_WI
Dictionary order, case-
42 nocase.850 SQL_Latin1_General_Cp850_CI_AS_KI_WI
insensitive
Dictionary order, case-
44 noaccent.850 SQL_Latin1_General_Cp850_CI_AI_KI_WI
insensitive, accent-insensitive
Dictionary order, case-
44 nocase34.850 insensitive, uppercase SQL_Latin1_General_Pref_Cp850_CI_AS_KI_WI
preference
Strict compatibility with Version
49 nocase34.850 SQL_1xCompat_Cp850_CI_AS_KI_WI
1.x case-insensitive databases
51 diction.iso Dictionary order, case-sensitive SQL_Latin1_General_Cp1_CS_AS_KI_WI
Dictionary order, case-
52 nocase.iso SQL_Latin1_General_Cp1_CI_AS_KI_WI
insensitive
Dictionary order, case-
53 nocasepr.iso insensitive, uppercase SQL_Latin1_General_Pref_Cp1_CI_AS_KI_WI
preference
Dictionary order, case-
54 noaccent.iso SQL_Latin1_General_Cp1_CI_AI_KI_WI
insensitive, accent-insensitive
Alternate dictionary order, case-
55 altdict.850 SQL_AltDiction_Cp850_CS_AS_KI_WI
sensitive
Alternate dictionary order, case-
56 altnocsp.850 insensitive, uppercase SQL_AltDiction_Pref_Cp850_CI_AS_KI_WI
preference
Alternate dictionary order, case-
57 altnoacc.850 SQL_AltDiction_Cp850_CI_AI_KI_WI
insensitive, accent-insensitive
Scandinavian dictionary sort
58 scan.850 order, case-insensitive, SQL_Scandainavian_Pref_Cp850_CI_AS_KI_WI
uppercase preference
Scandinavian dictionary sort
59 scandict.850 SQL_Scandainavian_Cp850_CS_AS_KI_WI
order, case-sensitive
Case-insensitive Scandinavian
60 scannocase.850 dictionary sort order, without SQL_Scandainavian_Cp850_CI_AS_KI_WI
case preference
Alternate dictionary order, case-
61 altnocs.850 SQL_AltDiction_Cp850_CI_AS_KI_WI
insensitive
80 binary.250 Binary SQL_Latin1_General_1250_BIN
81 diction.250 Dictionary order, case-sensitive SQL_Latin1_General_Cp1250_CS_AS_KI_WI
Dictionary order, case-
82 nocase.250 SQL_Latin1_General_Cp1250_CI_AS_KI_WI
insensitive
Czech dictionary order, case-
83 csydic.250 SQL_Czech_Cp1250_CS_AS_KI_WI
sensitive
Czech dictionary order, case-
84 csync.250 SQL_Czech_Cp1250_CI_AS_KI_WI
insensitive
Hungarian dictionary order,
85 hundic.250 SQL_Hungarian_Cp1250_CS_AS_KI_WI
case-sensitive
Hungarian dictionary order,
86 hunnc.250 SQL_Hungarian_Cp1250_CI_AS_KI_WI
case-insensitive
Polish dictionary order, case-
87 plkdic.250 SQL_Polish_Cp1250_CS_AS_KI_WI
sensitive
Polish dictionary order, case-
88 plknc.250 SQL_Polish_Cp1250_CI_AS_KI_WI
insensitive
Romanian dictionary order,
89 romdic.250 SQL_Romanian_Cp1250_CS_AS_KI_WI
case-sensitive
Romanian dictionary order,
90 romnc.250 SQL_Romanian_Cp1250_CI_AS_KI_WI
case-insensitive
Croatian dictionary order, case-
91 shldic.250 SQL_Croatian_Cp1250_CS_AS_KI_WI
sensitive
Croatian dictionary order, case-
92 shlnc.250 SQL_Croatian_Cp1250_CI_AS_KI_WI
insensitive
Slovak dictionary order, case-
93 skydic.250 SQL_Slovak_Cp1250_CS_AS_KI_WI
sensitive
Slovak dictionary order, case-
94 skync.250 SQL_Slovak_Cp1250_CI_AS_KI_WI
insensitive
Slovenian dictionary order,
95 slvdic.250 SQL_Slovenian_Cp1250_CS_AS_KI_WI
case-sensitive
Slovenian dictionary order,
96 slvnc.250 SQL_Slovenian_Cp1250_CI_AS_KI_WI
case-insensitive
104 binary.250 Binary SQL_Latin1_General_1251_BIN
105 diction.251 Dictionary order, case-sensitive SQL_Latin1_General_Cp1251_CS_AS_KI_WI
Dictionary order, case-
106 nocase.251 SQL_Latin1_General_Cp1251_CI_AS_KI_WI
insensitive
Ukrainian dictionary order,
107 ukrdic.251 SQL_Ukrainian_Cp1251_CS_AS_KI_WI
case-sensitive
Ukrainian dictionary order,
108 ukrnc.251 SQL_Ukrainian_Cp1251_CI_AS_KI_WI
case-insensitive
112 binary.253 Binary SQL_Latin1_General_1253_BIN
113 diction.253 Dictionary order, case-sensitive SQL_Latin1_General_Cp1253_CS_AS_KI_WI
Dictionary order, case-
114 nocase.253 SQL_Latin1_General_Cp1253_CI_AS_KI_WI
insensitive
Dictionary order, case-sensitive,
121 graltdct.253 SQL_Latin1_General_Cp1253_CI_AS_KI_WI
accent-sensitive
Dictionary order, case-
124 grnoacce.253 SQL_Latin1_General_Cp1253_CI_AI_KI_WI
insensitive, accent-insensitive
128 binary.254 Binary SQL_Latin1_General_1254_BIN
129 diction.254 Dictionary order, case-sensitive SQL_Latin1_General_Cp1254_CS_AS_KI_WI
Dictionary order, case-
130 nocase.254 SQL_Latin1_General_Cp1254_CI_AS_KI_WI
insensitive
136 binary.255 Binary SQL_Latin1_General_1255_BIN
137 diction.255 Dictionary order, case-sensitive SQL_Latin1_General_Cp1255_CS_AS_KI_WI
Dictionary order, case-
138 nocase.255 SQL_Latin1_General_Cp1255_CI_AS_KI_WI
insensitive
144 binary.256 Binary SQL_Latin1_General_1256_BIN
145 diction.256 Dictionary order, case-sensitive SQL_Latin1_General_Cp1256_CS_AS_KI_WI
Dictionary order, case-
146 nocase.256 SQL_Latin1_General_Cp1256_CI_AS_KI_WI
insensitive
152 binary.257 Binary SQL_Latin1_General_1257_BIN
153 diction.257 Dictionary order, case-sensitive SQL_Latin1_General_Cp1257_CS_AS_KI_WI
Dictionary order, case-
154 nocase.257 SQL_Latin1_General_Cp1257_CI_AS_KI_WI
insensitive
Estonian dictionary order, case-
155 etidic.257 SQL_Estonian_Cp1257_CS_AS_KI_WI
sensitive
Estonian dictionary order, case-
156 etinc.257 SQL_Estonian_Cp1257_CI_AS_KI_WI
insensitive
Latvian dictionary order, case-
157 lvidic.257 SQL_Latvian_Cp1257_CS_AS_KI_WI
sensitive
Latvian dictionary order, case-
158 lvinc.257 SQL_Latvian_Cp1257_CI_AS_KI_WI
insensitive
Lithuanian dictionary order,
159 lthdic.257 SQL_Lithuanian_Cp1257_CS_AS_KI_WI
case-sensitive
Lithuanian dictionary order,
160 lthnc.257 SQL_Lithuanian_Cp1257_CI_AS_KI_WI
case-insensitive
Danish/Norwegian dictionary
183 danonocp.iso order, case-insensitive, SQL_Danish_Pref_Cp1_CI_AS_KI_WI
uppercase preference
Swedish/Finnish[Phone]
dictionary order, case-
184 islanocp.iso SQL_SwedishPhone_Pref_Cp1_CI_AS_KI_WI
insensitive, uppercase
preference
Swedish/Finnish[Std] dictionary
185 svf2nocp.iso.iso order, case-insensitive, SQL_SwedishStd_Pref_Cp1_CI_AS_KI_WI
uppercase preference
Icelandic dictionary order, case-
186 islanocp.iso insensitive, uppercase SQL_Icelandic_Pref_Cp1_CI_AS_KI_WI
preference
SQL SERVER 2005 Security Best Practices Operational and Administrative Tasks
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.
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.
Error Message:
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])
)
Executing this CREATE TABLE statement will generate the following error message:
Server: Msg 128, Level 15, State 1, Line 5
The 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])
)
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 FREEPROCCACHE
DBCC DROPCLEANBUFFERS
SELECT @@IDENTITY
It 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.
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
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.
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
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:
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, Rank
FROM Employees
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.
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)
SQL SERVER TempDB is Full. Move TempDB from one drive to another drive.
If you come across following errors in log file, please follow the direction below.
Source: MSSQLSERVER
Event ID: 17052
Description: The LOG FILE FOR DATABASE 'tempdb' IS FULL.
Back up the TRANSACTION LOG FOR the DATABASE TO free
up 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.
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 TempDB
GO
EXEC sp_helpfile
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.
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 servers
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
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
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.
USE AdventureWorks
GO
DECLARE @StartRow INT
DECLARE @EndRow INT
SET @StartRow = 120
SET @EndRow = 140
USE AdventureWorks
GO
DECLARE @StartRow INT
DECLARE @EndRow INT
SET @StartRow = 120
SET @EndRow = 140
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
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.
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.
Reference : Pinal Dave (http://blog.SQLAuthority.com) , SQL SERVER T-SQL Paging Query
Technique Comparison SQL 2000 vs SQL 2005
SQL SERVER Fix: HResult 0274D, Level 16, State 1 Error: Microsoft SQL Native Client : Login
timeout expired.
While Working with SQLCMD in SQL Server 2005 I encountered following error.
HResult 0x274D, LEVEL 16, State 1
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.
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.
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.
Dont 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 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 parameters
Flushes the distributed query connection cache used by distributed queries against an instance of
Microsoft SQL Server. View Details
UnDocumented:
metadata ({print [, printopt = {0 |1}] | drop | clone [, '' | ....]}, {object [, 'type',...}, {Id |
Name}, [{Ownerid | Ownername}], [{Dbid | Dbname}]])
SQL SERVER Fix: Server: Msg 7391, Level 16, State 1, Line 1
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.
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.
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;
GO
SELECT CHARINDEX('ensure', DocumentSummary)
FROM Production.Document
WHERE DocumentID = 3;
GO
Examples of PATINDEX:
USE AdventureWorks;
GO
SELECT PATINDEX('%ensure%',DocumentSummary)
FROM Production.Document
WHERE DocumentID = 3;
GO
Summary:
PATINDEX is CHARINDEX + WildCard Search. Use either of them depending your need.
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.
Please use Microsoft MSDN BOL to see all the Reserved Keywords. The text above has been referenced
from MSDN BOL.
There are two ways, which can be used to improve the performance of Stored Procedure (SP) without
making T-SQL changes in 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. name.
Call your Stored Procedure prefixed with dbo.SPName fully qualified
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.
If location of sqlinstall.ini file is at C:\SQLSetup folder. The command to initiate silent installation is:
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 TRYCATCH 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.
ERROR_NUMBER: returns the error number, and is the same value of @@ERROR.
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 TRY
BEGIN 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 TRYCATCH:
BEGIN TRY
DECLARE @X INT
---- Divide by zero to generate Error
SET @X = 1/0
PRINT 'Command after error in TRY block'
END TRY
BEGIN CATCH
PRINT 'Error Detected'
END CATCH
PRINT 'Command after TRY/CATCH blocks'
Above code will return following result:
Error Detected
Command 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 TRYCATCH:
For errors that are not trapped, SQL Server 2005 passes control back to the application immediately,
without executing any CATCH block code.
SQL SERVER UDF User Defined Function to Extract Only Numbers From String
Following SQL User Defined Function will extract/parse numbers from the string.
CREATE FUNCTION ExtractInteger(@String VARCHAR(2000))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @Count INT
DECLARE @IntNumbers VARCHAR(1000)
SET @Count = 0
SET @IntNumbers = ''
SQL SERVER Running 64 bit SQL SERVER 2005 on 32 bit Operating System
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.
SQL SERVER Fix : Error: 3902, Severity: 16; State: 1 : The COMMIT TRANSACTION request has
no corresponding BEGIN TRANSACTION.
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 like
BEGIN 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
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.
1) Drop Trigger
Example:
DROP TRIGGER TriggerName
GO
2) Disable Trigger
DML 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
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.
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.
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).
LOGIN sa ENABLE
GO
ALTER 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.
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.
Syntax:
CASE
WHEN Boolean_expression1 THEN expression1
[[WHEN Boolean_expression2 THEN expression2] [...]]
[ELSE expressionN]
END
Example:
DECLARE @TestVal INT
SET @TestVal = 5
SELECT
CASE
WHEN @TestVal <=3 THEN 'Top 3'
ELSE 'Other'
END
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 Configuration
Enable 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 Configuration
Enable TCP/IP protocol.
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 INT
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountID
SQL SERVER Query to find number Rows, Columns, ByteSize for each table in the current
database Find Biggest Table in Database
USE DatabaseName
GO
CREATE 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 ON
INSERT #temp
EXEC sp_msforeachtable 'sp_spaceused ''?'''
SELECT a.table_name,
a.row_count,
COUNT(*) AS col_count,
a.data_size
FROM #temp a
INNER JOIN information_schema.columns b
ON a.table_name collate database_default
= b.table_name collate database_default
GROUP BY a.table_name, a.row_count, a.data_size
ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC
DROP TABLE #temp
SQL SERVER FIX : Error 15023: User already exists in current database.
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 YourDB
GO
EXEC 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
specified user in the current database to login. login must already exist. user and login must be specified.
password must be NULL or not specified
USE YourDB
GO
EXEC 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 YourDB
GO
EXEC 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 database
by mapping them to username already exist for user on server.
This SP is required when user has been created at server level but does
not show up as user in database.*/
CREATE PROCEDURE dbo.spDBA_FixOrphanUsers
AS
DECLARE @username VARCHAR(25)
DECLARE GetOrphanUsers CURSOR
FOR
SELECT UserName = name
FROM sysusers
WHERE issqluser = 1
AND (sid IS NOT NULL
AND sid <> 0x0)
AND SUSER_SNAME(sid) IS NULL
ORDER BY name
OPEN GetOrphanUsers
FETCH NEXT
FROM GetOrphanUsers
INTO @username
WHILE @@FETCH_STATUS = 0
BEGIN
IF @username='dbo'
EXEC sp_changedbowner 'sa'
ELSE
EXEC sp_change_users_login 'update_one', @username, @username
FETCH NEXT
FROM GetOrphanUsers
INTO @username
END
CLOSE GetOrphanUsers
DEALLOCATE GetOrphanUsers
GO
Stored Procedure 2:
/*Following Stored Procedure will fix all the Orphan users in database
by 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_FixOrphanUsersPassWord
AS
DECLARE @username VARCHAR(25)
DECLARE @password VARCHAR(25)
DECLARE GetOrphanUsers CURSOR
FOR
SELECT UserName = name
FROM sysusers
WHERE issqluser = 1
AND (sid IS NOT NULL
AND sid <> 0x0)
AND SUSER_SNAME(sid) IS NULL
ORDER BY name
OPEN GetOrphanUsers
FETCH NEXT
FROM GetOrphanUsers
INTO @username
SET @password = @username
WHILE @@FETCH_STATUS = 0
BEGIN
IF @username='dbo'
EXEC sp_changedbowner 'sa'
ELSE
EXEC sp_change_users_login 'Auto_Fix', @username, NULL, @password
FETCH NEXT
FROM GetOrphanUsers
INTO @username
END
CLOSE GetOrphanUsers
DEALLOCATE GetOrphanUsers
GO
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_DropOrphanUsers
AS
DECLARE @username VARCHAR(25)
DECLARE GetOrphanUsers CURSOR
FOR
SELECT UserName = name
FROM sysusers
WHERE issqluser = 1
AND (sid IS NOT NULL
AND sid <> 0x0)
AND SUSER_SNAME(sid) IS NULL
ORDER BY name
OPEN GetOrphanUsers
FETCH NEXT
FROM GetOrphanUsers
INTO @username
WHILE @@FETCH_STATUS = 0
BEGIN
IF @username='dbo'
EXEC sp_changedbowner 'sa'
ELSE
EXEC sp_dropuser @username
FETCH NEXT
FROM GetOrphanUsers
INTO @username
END
CLOSE GetOrphanUsers
DEALLOCATE GetOrphanUsers
GO
Update : (5/5/2007)
I have updated the UDF to support SQL SERVER 2005.
Visit :SQL SERVER UDF Function to Convert List to Table
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.
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.
SQL SERVER UDF Function to Convert Text String to Title Case Proper Case
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.
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 MyDatabase
GO
EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)"
GO
EXEC sp_updatestats
GO
Method 2:
USE MyDatabase
GO
CREATE PROCEDURE spUtil_ReIndexDatabase_UpdateStats
AS
DECLARE @MyTable VARCHAR(255)
DECLARE myCursor
CURSOR FOR
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'base table'
OPEN myCursor
FETCH NEXT
FROM myCursor INTO @MyTable
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Reindexing Table: ' + @MyTable
DBCC DBREINDEX(@MyTable, '', 80)
FETCH NEXT
FROM myCursor INTO @MyTable
END
CLOSE myCursor
DEALLOCATE myCursor
EXEC sp_updatestats
GO
SQL SERVER Query Analyzer Short Cut to display the text of Stored Procedure
This is quick but interesting trick to display the text of Stored Procedure in the result window. Open SQL
Query Analyzer >> Tools >> Customize >> Custom Tab
type sp_helptext against Ctrl+3 (or shortcut key of your choice)
You will see the Stored Procedure text in the Result Window.
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
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)
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.
Download here.
ResultSet:
Example1
-
first
2nd
III
1+1+1+1
(4 row(s) affected)
Example2
-
111
222
333
444
555
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.
DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)
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.
DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)
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 master
GO
EXEC xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Microsoft
SQL Server\80\Registration','CD_KEY'
GO
SQL SERVER What is New in SQL Server Agent for Microsoft SQL Server 2005
I came across this interesting and detailed article Whats 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.
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 FILELISTONLY
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
GO
----Restore Database
RESTORE DATABASE YourDB
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf'
SQL SERVER Union vs. Union All Which is better for performance?
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.
UNION
The 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 ALL
The 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,Fifth
Table 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
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:
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 ON
GO
SET ANSI_NULLS ON
GO--SQL PROCEDURE, SQL FUNCTIONS, SQL OBJECTGO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SQL SERVER SQL Server 2005 Samples and Sample Databases (February 2007)
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.
Download here.
SQL SERVER Query to Find Seed Values, Increment Values and Current Identity Column value
of the table
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.
SQL SERVER Understanding new Index Type of SQL Server 2005 Included Column Index
along with Clustered Index and Non-clustered Index
Clustered Index
Only 1 allowed per table
Physically rearranges the data in the table to conform to the index constraints
For use on columns that are frequently searched for ranges of data
For use on columns with low selectivity
Non-Clustered Index
Up to 249 allowed per table
Creates a separate list of key values with pointers to the location of the data in the data pages
For use on columns that are searched for single values
For 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
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 AdventureWorks
GO
CREATE INDEX IX_Document_Title
ON Production.Document (Title, Revision)
INCLUDE (FileName)
Non-key columns can be included only in non-clustered indexes. Columns cant be defined in both the key
column and the INCLUDE list. Column names cant be repeated in the INCLUDE list. Non-key columns can
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.
USE AdventureWorks
GO
CREATE NONCLUSTERED INDEX IX_Address_PostalCode
ON 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.
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.
The master databases 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.
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.