Monday, October 8, 2012

Copy Column Headers in Query Analyzers in Result Set

Copy Column Headers in Query Analyzers in Result Set.
In Query Analyzer go to Menu >> Tools >> Options >> Results
Select Default results Target: Results to Text
Results output format:(*): Tab Delimited
Print column headers(*): Checkbox ON(check)
Reference : Pinal Dave (http://blog.SQLAuthority.com)

SQL SERVER – Recover the Accidentally Renamed Table

I have no answer to following question. I saw a desperate email marked as urgent delivered in my mailbox.
I accidentally renamed table in my SSMS. I was scrolling very fast and I made mistakes. It was either because I double clicked or clicked on F2 (shortcut key for renaming). However, I have made the mistake and now I have no idea how to fix this.
I am in big trouble. Help me get my original tablename.”
I have seen many similar scenarios in my life and they give me a very good opportunity to preach wisdom but when the house is burning, we cannot talk about how we should have conserved the water earlier. The goal at that point is to put off the fire as fast as we can. I decided to answer this email with my best knowledge.
If you have renamed the table, I think you pretty much is out of luck. Here are few things which you can do which can give you idea about what your tablename can be if you are lucky.
Method 1: (Not Recommended but try your luck)
Check your naming convention of your system. I have often seen that many organizations name their index as IX_TableName_Colms or name their keys as FK_TableName1_TableName2_Cols. If your organization is following the same you can get the name from your table, you may refer your keys. Again, note that this is quite possible that your tablename was already renamed and your keys were not updated. This can easily lead you to select incorrect name. I think follow this if you are confident or move to the next method.
Method 2: (Not Recommended but try your luck)
This method is also based on your orgs naming convention. If you use the name of the table in any columnname (some organizations use tablename in their incremental identity column name), you can get that name from there.
Method 3: (Not Recommended but try your luck)
If you know where your table was used in your stored procedures, you can script your stored procedure and find the name of the table back.
Method 4: (Try your luck)
All the best organizations first create a data model of the schema and there is good chance that this table is used there, you should take your chances and refer original document. If your organization is good at managing docs or source code, you will get the name of the table back for sure.
Method 5: (It WORKS but try on a development server)
There is no sure way to get you the name of the table which you accidentally renamed however, there is one way which will work for sure. You need to take your latest full backup and restore it on your development server (remember not on production or where you have renamed this column). Now restore latest differential file of the full backup. Now restore all the log files one by one making sure that you are restoring before the point of time of you renamed the tablename. Now go to explore and this will give you the name of the table which you have renamed. If you are confident that the same table existed with the same name when the last full backup was made, you do not have to go to all the steps. You can just get the name of the table directly from last backup’s restore. Read the article about Backup Timeline.

Wisdom:
How can I miss to preach wisdom when I get the opportunity to do so? Here are a few points to remember.

  • Use a different account to explore production environment. Do not use the same account which have all the rights and permissions all the time. Use the account which has read only permissions if there are no modification required.
  • Use policy based management to prevent changes which are accidental. If there was policy of valid names, the accidental change of the table was not possible unless it was intentional delibarate changes.
  • Have a proper auditing of the system in place.
  • You can use DDL triggers but be careful with its usage (get it reviewed properly first).
  • (Add your suggestion here)
I guess Method 5 will work all the time (using point in time restore). Everything else is chance of luck and if you are lucky are bad – you will get further incorrect name.
Now go back and read the first line of this blog. Out of five method four methods are just lucky guesses. The method 5 will work but again it is a lengthy process if the size of the database is huge or if you do not have full backup. Did I miss anything obvious? Please leave a comment and I will publish your answer with due credit.
Reference: Pinal Dave (http://blog.sqlauthority.com)

Troubleshooting the Top Five Waits Occurring in SQL Server DBAs

the SQL Server Database Administrator has been running slowly and everyone’s getting cranky. How can you tell what’s wrong and what steps you need to take to restore normal operations?
Database administrators have great instrumentation. When asked, they’re happy to tell you about their bottlenecks in excruciating detail. Use this handy guide to understand and troubleshoot the causes of the most common five wait types likely to impact your DBA’s performance.

5: BRAINIOLATCH_SH

This is a wait on memories that are being returned from long-term storage.
This wait frequently occurs when the DBA is trying to remember what happened that other time two years ago when queries for this application were returning incorrect results and the name of the developer who’s going to get stuck with the bug this time.
If this wait occurs frequently, the DBA needs to become harder to find.

4: TICKETLOG

This wait occurs when so many incidents are coming in that support tickets can’t be created fast enough to keep up. This wait is caused by overeager monitoring and ticketing systems that require clicking lots of buttons.
When this wait type dominates the DBA system, it can be resolved by hiring a Junior DBA for extra processing cycles.

3: LCK_USER_X

Long queues of requests form when multiple users have complaints and form a line behind the DBA’s cubicle.
When LCK_USER waits become high, the DBA can clear them by yelling “Everyone run, I see the deadlock monitor!”

2: REDDIT

No explanation needed.

1: CAFFEINEPACKET

High CAFFEINEPACKET waits are a symptom of coffee starvation in the DBA. This can occur when too much work is being requested while caffeine sources have become low in the DBA.

Thursday, October 4, 2012

Effect of Case Sensitive Collation on Resultset


Collation is a very interesting concept but I quite often see it is heavily neglected. I have seen developer and DBA looking for a workaround to fix collation error rather than understanding if the side effect of the workaround. Collation is a very deep subject. Earlier I wrote an article how one can resolve the collation error when different collation values are compared. Today in most simple way I would like to explain that different collation can return different result. Without understanding business needs (and sensitivity) one should not change the collation of the columns or database.
Let us see a simple example. I am going to create a table with two columns. Both the columns have different collation. One collation is case sensitive (CS) and another one is case insensitive (CI). You can see that col1 and col2 both have exactly the same data.
CREATE TABLE ColTable(Col1 VARCHAR(15) COLLATE Latin1_General_CI_AS,Col2 VARCHAR(14) COLLATE Latin1_General_CS_AS) ;INSERT ColTable(Col1, Col2)VALUES ('Apple','Apple'),
(
'apple','apple'),
(
'pineapple','pineapple'),
(
'Pineapple','Pineapple');GO
-- Retrieve DataSELECT *FROM ColTable
GO
Now let us run two queries and compared its result set. In the first query col1 is used in order by clause and in second query col2 is used in the order by clause.
-- Retrieve DataSELECT *FROM ColTableORDER BY Col1
GO
-- Retrieve DataSELECT *FROM ColTableORDER BY Col2
GO
Technically both the columns have exactly the same data. When either of the columns used in order by it should give exactly the same result. However, in our case it is returning us different result. The reason is simple – collation of the column is different. As mentioned earlier one of the column has a case sensitive collation and another column has a case insensitive collation. When table is ordered by Col2 which is case sensitive leading to lowercase ‘apple’ row before upper case ‘apple’ row.
Let us clean up.
-- Clean upDROP TABLE ColTable
GO
As mentioned collation is a very important concept. It should be properly understood and explored before taking it granted or easy.

Cannot resolve collation conflict for equal to operation


Cannot resolve collation conflict for equal to operation.
In MS SQL SERVER, the collation can be set in column level. When compared 2 different collation column in the query, this error comes up.
SELECT IDFROM ItemsTableINNER JOIN AccountsTableWHERE ItemsTable.Collation1Col = AccountsTable.Collation2Col
If columns ItemsTable.Collation1Col and AccountsTable.Collation2Col have different collation, it will generate the error “Cannot resolve collation conflict for equal to operation“.
To resolve the collation conflict add following keywords around “=” operator.
SELECT IDFROM ItemsTableINNER JOIN AccountsTableWHERE ItemsTable.Collation1Col COLLATE DATABASE_DEFAULT= AccountsTable.Collation2Col COLLATE DATABASE_DEFAULT
Collation can affect following areas:
1) Where clauses
2) Join predicates
3) Functions
4) Databases (e.g. TempDB may be in a different collation database_default than the other databases some times)

Guest Post by Sandip Pani – SQL Server Statistics Name and Index Creation

Sometimes something very small or a common error which we observe in daily life teaches us new things. SQL Server Expert Sandip Pani (winner of Joes 2 Pros Contests) has come across similar experience. Sandip has written a guest post on an error he faced in his daily work. Sandip is working for QSI Healthcare as an Associate Technical Specialist and have more than 5 years of total experience. He blogs at SQLcommitted.com and contribute in various forums. His social media hands are LinkedIn, Facebook and Twitter.

Once I faced following error when I was working on performance tuning project and attempt to create an Index.
Mug 1913, Level 16, State 1, Line 1
The operation failed because an index or statistics with name ‘Ix_Table1_1′ already exists on table ‘Table1′.
The immediate reaction to the error was that I might have created that index earlier and when I researched it further I found the same as the index was indeed created two times. This totally makes sense. This can happen due to many reasons for example if the user is careless and executes the same code two times as well, when he attempts to create index without checking if there was index already on the object. However when I paid attention to the details of the error, I realize that error message also talks about statistics along with the index. I got curious if the same would happen if I attempt to create indexes with the same name as statistics already created. There are a few other questions also prompted in my mind. I decided to do a small demonstration of the subject and build following demonstration script.
The goal of my experiment is to find out the relation between statistics and the index. Statistics is one of the important input parameter for the optimizer during query optimization process. If the query is nontrivial then only optimizer uses statistics to perform a cost based optimization to select a plan. For accuracy and further learning I suggest to read MSDN.
Now let’s find out the relationship between index and statistics. We will do the experiment in two parts. i) Creating Index ii) Creating Statistics
We will be using the following T-SQL script for our example.
IF (OBJECT_ID('Table1') IS NOT NULL)DROP TABLE Table1
GO
CREATE TABLE Table1(Col1 INT NOT NULL,Col2 VARCHAR(20) NOT NULL)GO
We will be using following two queries to check if there are any index or statistics on our sample table Table1.
-- Details of IndexSELECT OBJECT_NAME(OBJECT_ID) AS TableName, Name AS IndexName, type_descFROM sys.indexesWHERE OBJECT_NAME(OBJECT_ID) = 'table1'GO-- Details of StatisticsSELECT OBJECT_NAME(OBJECT_ID) TableName, Name AS StatisticsNameFROM sys.statsWHERE OBJECT_NAME(OBJECT_ID) = 'table1'GO
When I ran above two scripts on the table right after it was created it did not give us any result which was expected.
Now let us begin our test.

1) Create an index on the table

Create following index on the table.
CREATE NONCLUSTERED INDEX Ix_Table1_1 ON Table1(Col1)GO
Now let us use above two scripts and see their results.
We can see that when we created index at the same time it created statistics also with the same name.
Before continuing to next set of demo – drop the table using following script and re-create the table using a script provided at the beginning of the table.
DROP TABLE table1
GO

2) Create a statistic on the table

Create following statistics on the table.
CREATE STATISTICS Ix_table1_1 ON Table1 (Col1)GO
Now let us use above two scripts and see their results.
We can see that when we created statistics Index is not created. The behavior of this experiment is different from the earlier experiment.
Clean up the table setup using the following script:
DROP TABLE table1
GO
Above two experiments teach us very valuable lesson that when we create indexes, SQL Server generates the index and statistics (with the same name as the index name) together. Now due to the reason if we have already had statistics with the same name but not the index, it is quite possible that we will face the error to create the index even though there is no index with the same name.

A Quick Check

To validate that if we create statistics first and then index after that with the same name, it will throw an error let us run following script in SSMS. Make sure to drop the table and clean up our sample table at the end of the experiment.
-- Create sample tableCREATE TABLE TestTable(Col1 INT NOT NULL,Col2 VARCHAR(20) NOT NULL)GO-- Create StatisticsCREATE STATISTICS IX_TestTable_1 ON TestTable (Col1)GO-- Create IndexCREATE NONCLUSTERED INDEX IX_TestTable_1 ON TestTable(Col1)GO-- Check error
/*Msg 1913, Level 16, State 1, Line 2
The operation failed because an index or statistics with name 'IX_TestTable_1' already exists on table 'TestTable'.
*/
-- Clean up
DROP TABLE TestTable
GO

While creating index it will throw the following error as statistics with the same name is already created.

In simple words – when we create index the name of the index should be different from any of the existing indexes and statistics.
Reference: Pinal Dave (http://blog.SQLAuthority.com)

Change Collation of Database Column – T-SQL Script

Just a day before I wrote about SQL SERVER – Find Collation of Database and Table Column Using T-SQL and I have received some good comments and one particular question was about how to change collation of database. It is quite simple do so.
Let us see following example.
USE AdventureWorks
GO
/* Create Test Table */CREATE TABLE TestTable (FirstCol VARCHAR(10))GO/* Check Database Column Collation */SELECT name, collation_nameFROM sys.columnsWHERE OBJECT_ID IN ( SELECT OBJECT_IDFROM sys.objectsWHERE type = 'U'AND name = 'TestTable')GO/* Change the database collation */ALTER TABLE TestTableALTER COLUMN FirstCol VARCHAR(10)COLLATE SQL_Latin1_General_CP1_CS_AS NULLGO/* Check Database Column Collation */SELECT name, collation_nameFROM sys.columnsWHERE OBJECT_ID IN ( SELECT OBJECT_IDFROM sys.objectsWHERE type = 'U'AND name = 'TestTable')GO/* Database Cleanup */DROP TABLE TestTable
GO
When ran above script will give two resultset. First resultset is before column’s collation is changed and it represents default collation of database. Second result set is after column’s collation is changed and it represents newly defined collation.
Let me know what are your ideas about collation and any problem if you have faced for the same. I am interested to share those with the SQL community.
Additionally, if you are looking for solution to SQL SERVER – Cannot resolve collation conflict for equal to operation visit here.
Reference : Pinal Dave (http://www.SQLAuthority.com)