Showing posts with label SQL Server 2012. Show all posts
Showing posts with label SQL Server 2012. Show all posts

Friday, May 2, 2014

Video: SQL Server Performance Tuning with Wait Statistics (CXPACKET)

CXPACKET is a common wait type, resulted by parallel query execution. But does occurrence of CXPACKET wait is always a sign of performance problem???
A lot more written. But here is our second animated video to learn it in a very simple way.



Sunday, December 22, 2013

Microsoft Innovation Center: Presentation Dec 18 2013

On December 18th, 2013, I have presented on topic "*SQL Server: Query Performance Tuning" at Microsoft Innovation Center, Lahore (Pakistan). Primary agenda was to discuss all possible methods to detect costly queries and handling these queries to obtain optimum performance. 

Monday, December 9, 2013

SQL Server : Extracting Data From VSS to SQL Server

Recently, when I was looking to generate some reports for sql files we have in Visual SourceSafe (VSS), I have decided to extract data from VSS to SQL Server, where I can play with data, more easily. 
One tool (off course free) I found which can help for this extraction. This tool  V2M is free to download but works better with less files/no of labels on VSS.
In my case it was not that helpfull and I have to use built in reports from VSS to extract data to text and then to SQL Server, as following.

1-On VSS, open your project, move to your desired folder, right click on it, and then click "Show History"


2- On Project History Options, check on "Recursive" and "Include file Histories" to get versions history for each file and hit OK button
3- It will take time to generate history. Once history page is open hit "Report" button and select "File" as report destination and press OK. It will ask location for file, provide and hit save button.
4- Generated report would be in text format and obviously NOT so simple to export to SQL Server, but not that tricky. You can copy paste whole text to Excel to format it manually and it would take more less time.

Thursday, November 28, 2013

Microsoft Innovation Center: Presentation Nov 27 2013

On November 27th, 2013, I have presented on topic "*SQL Server: 2012 or HEKATON" at Microsoft Innovation Center, Lahore (Pakistan). Primary agenda was to discuss all major and minor new features, introduced in SQL Server 2012 and up coming SQL Server 2014 code name HEKATON. And should we go for SQL Server 2012 or wait for SQL Server 2014.




Tuesday, November 5, 2013

SQL Server : Script to Find and Create Missing Tables for Database Sychronization

Different methods and tools are available to synchronize two SQL Server databases. But one simple way to synchronize is using TSQL Script to find difference and create missing structures. Following script is for the same purpose. Script can be used to find and create missing tables on target database by comparing tables structure with source database.

Thursday, August 15, 2013

SQL Server: Row Count for Specific Data Page

Recently found that for one of our production server, we have to use repair_allow_data_loss parameter to resolve page corruption. But question was how many rows we can loss for a specific corrupt page ???
Rows count on a specific page can be found if we get a page header print  by DBCC Page(). Obviously, before using DBCC Page() you must enable trace (3604).

DBCC TRACEON(3604)
GO
DBCC PAGE('DatabaseName',1,323008,0)
GO

In above case DatabaseName is my database name, 1 is data file id, 323008 is page number for which we need number of rows and 0 parameter value is for print header only. According to MSDN, we have 4 options for this parameter.
  • 0 - print just the page header
  • 1 - page header plus per-row hex dumps and a dump of the page slot array (unless its a page that doesn't have one, like allocation bitmaps)
  • 2 - page header plus whole page hex dump
  • 3 - page header plus detailed per-row interpretation
In output, under Page Header section, m_slotCnt shows number of rows on this particular page. In my case it is 736.

Wednesday, January 2, 2013

SQL Server: A Query Slow in SSMS, Fast in Application, WHY?



Today, a colleague asked me, why his simple select query is taking around 3000ms (3 Seconds) to execute while, same query is quite fast when executed from application.

Answer is simple: SQL Server Management Studio use RBAR-Row By Agonizing Row method to fetch rows and inform row by row to SQL Server that row is received while on other hand application which don’t use RBAR method, inform once after whole batch is received and reluctantly is fast as compared to SSMS or those applications which use RBAR method.

To confirm that query is running slow just because of RBAR factor, I have used extended events for single session waits analysis, a well defined method by Paul Randal. Output was as following: 

 NETWORK_IO is basically ASYNC_NETWORK_IO, when working with extended events. According to BOL “Occurs on network writes when the task is blocked behind the network. Verify that the client is processing data from the server.”

But a more proper definition for this type of wait you can find on Karthik PK’s Blog. He stats that “When a query is fired, SQL Server produces the results ,place it in output buffer and send it to client/Application. Client/Application then fetch the result from the Output buffer, process data  and sends an acknowledgement to SQL Server. If client/Application takes long time to send acknowledgement then SQL Server waits on ASYNC_NETWORK_IO (SQL 2005/2008) or  Network_IO (SQL 2000) before it produces additional results.

Hence proved that, our query delay was just because of NETWORK_IO wait (2870ms out of total 3000ms) and we were on the same machine where SQL Server was installed so no chances of any network problem and its only RBAR method of SQL Server Management Studio which was causing this delay. 

Thursday, December 27, 2012

SQL Server: Client IP Along with DDL Change Log Using Service Broker



Last day, we have discussed all three possible methods for DDL Change Log and as per my suggestions, if you don’t need to conditionally allow/disallow changes then Service Broker is the best way to capture these changes. This method additionally allows you to submit change information to a separate instance on internet as a loosely coupled message.

One of blog reader raised a question that what else we need to add in script if we also need to capture machine IP from where change is coming.

Well answer is simple. We already have information of SPID so we can use this SPID and get client machine IP address by querying sys.dm_exec_connections.  
Change already defined stored procedure as following.



Wednesday, December 26, 2012

SQL Server: Three Common DDL Change Log Methods



Who is changing your objects (tables, views, stored procedures, functions etc) or creating new one, or who actually deleted one or more objects? These are normal questions when more than one person are working on a same database.
Production environment is mostly kept secure for unauthorized access and few known persons are allowed to make changes BUT still you need to keep a track of these changes and if it’s a development database then it is also must to keep a complete log of each change.
Three major ways, we can keep track of these changes.
1.                 DDL Trigger & Event Notifications
2.                 Extended Events
3.                 Service Broker & Event Notifications
DDL Trigger method is most commonly used method, where we write a ddl (after) trigger on each database separately and using information from event notifications, we decide whether to rollback any DDL change or just dump change information to a table.
Extended Events, is the most advance method, not only for DDL change tracking but it’s going to be next biggest tool for DBAs. SQL Server 2012, introduced three new events for DDL change tracking.
1.                 object_altered
2.                 object_created
3.                 object_deleted
Paul Randal script for extended event creation is good one to follow, but don’t forget to change events.
 Service Broker (with event notifications), is the best way I have ever found for DDL Change Tracking before SQL Server 2012. Though its initial steps are bit lengthy, that is why; most people avoid using this method.
Using service broker, you can dump all databases changes data to a single table on an instance, or you can transmit changes information as a message to other instance on internet (if need to create a single point of administration for multiple instances).
(What is Service Broker and what type of objects you need to create, can be found here and here)
Use following simple steps to create DDL Changes Log, for multiple databases on an instance.


Thursday, November 29, 2012

SQL Server: Script to Find Tables in Stored Procedures, That Are Without NonClustered Index

From my query bank here is another useful script which can help a Database Administrator to list down stored procedures with tables names which are used in stored procedures but don't contain and non clustered index.

Query Output:

Wednesday, November 28, 2012

SQL Server: CMEMTHREAD, High Wait Values and Solution



Wait stats is the first place when where we start analyzing health of a production database server. Recently, we have found that a new database production server is not performing up to mark and queries response getting slower and slower in peak hours.
On executing, well known query by Paul Randal to get wait stats, we have found that a time for strange wait “CMEMTHREAD” is too high for said server.


According to BOL “CMEMTHREAD, occurs when a task is waiting on a thread-safe memory object. The wait time might increase when there is contention caused by multiple tasks trying to allocate memory from the same memory object.”
On trying a lot, but totally in vain, I thought asking Paul Randal would be better, as his blog on SQLSkills is one of the big resources from where I have learned about waits and wait types. Paul replied that “My guess is ad hoc plans being inserted into the plan cache. Try turning on 'optimize for ad hoc workloads'.” (That’s what we have already tried)
Skimming through articles and forums, I came a across to Microsoft support team article http://support.microsoft.com/kb/2492381/en-us. Which stats that, it could be occurring due to a bug in SQL Server 2008 R2. On said production server, we have found that NO service pack is installed and it still contains RTM.
Without any second thought we have created a ticket for upgradation to ServicePack2 and after that we have found that problem is resolved and server start working normally.

Monday, November 19, 2012

SQL Server: Indexes List With Key and Involved Columns Name Alongwith Usage Statistics

A year back I have shared a script from query bank, which can be helpful to get indexes list of a database, with key and involved columns. Being a DBA, I never remember a day, without using this script. 
Getting detail of indexes on a database most of the time I also need indexes usage statistics, through which I can figure out which indexes are being used and which indexes can be discarded. 
To avoid to use two separate scripts, let me share following script which brings both, usage and structural information for all indexes of a database or a given table.


Script output

User Seek +  User Scans will decide which index are useful and which are just burden for database. Indexes with less seek + scan should be removed for better DML operations performance.

Monday, October 1, 2012

SQL Server Management Studio: Basic Startup Options



SQL Server Management Studio is a powerful tool to manage SQL Server databases. Let’s discuss its two very common properties which can make our daily life easy.
  • Why every time, a new query window is open with MASTER database.
On open a new query window, It opens it with MASTER database in use, because on creation of a new user, SQL Server sets default database as MASTER. You change it by opening properties window for your user and then change default database value to your desired one.

Now opening a new query window, your own database will be selected by default.
  • On opening SQL Server Management Studio, I need a new query window automatically.

SQL Server Management Studio gives you five options to change its startup behavior. You can select one of these options by moving your mouse to TOOLS….Options in top menu.
 


Open Object Explorer
Using this option, only Object Explorer will be opened on startup and will ask you to login to an instance
Open new query window
This option will help you to start SSMS with a new query window only.
Open Object Explorer and new query window
This option is the most common one, when you need both Object Explorer and Query Window
Open Object Explorer and Activity Monitor
This option will open Activity Monitor with Object Explorer


Open empty environment
Option, which is never used (at least I never used it). As it will just open SQL Server Management Studio, No query window, No object explore, just main menu with tool bars.

Friday, September 28, 2012

SQL Server: Why a Session With sp_readrequest Takes so Long to Execute



While applying, Long Running Sessions Detection Job on a production server, we start receiving alert that a session is taking more then 3 minutes. But what actually this session was doing. Here is the alert report.

SP ID
Stored Procedure Call
DB Name
Executing Since
58
msdb.dbo.sp_readrequest;1�
msdb
3 min
sp_readrequest is a system stored procedure, which basically reads a message request from the the queue and returns its  contents.
This process can remain active for a time we have configured for parameter DatabaseMailExeMinimumLifeTime, at the time of database mail profile configuration. 600 seconds is the default value for this external mail process. According to BOL DatabaseMailExeMinimumLifeTime is the The minimum amount of time, in seconds, that the external mail process remains active.
This can be changed, at the time of mail profile configuration or you can just use update query to change this time.

UPDATE msdb.dbo.sysmail_configuration
SET paramvalue = 60 --60 Seconds
WHERE paramname = 'DatabaseMailExeMinimumLifeTime'
We have changed this to 60 seconds to resolve our problem.

Thursday, September 27, 2012

SQL Server: Template Explorer, A Developer’s Close Friend



How many of us really memorize all create, update or drop/delete scripts. Very honestly, I just remember Create Procedure and Create Function scripts. But, reality is that, we need not to remember all these codes/scripts, especially when Template Explorer is there for our help.
If you can’t see Template Explorer  in your SQL Server Management Studio, then just move your mouse pointer to top menu, view , Template Explorer or if you are short keys fan then just press Ctrl+Alt+T from your keyboard.

See how quickly I can create a new trigger.

 

Wednesday, September 26, 2012

SQL Server Errors: ORDER BY items must appear in the select list if SELECT DISTINCT is specified



SQL Server force you to put columns in SELECT DISTINCT list which are part of ORDER BY clause. But what if we don’t want to add that column/s in SELECT list. Lets try it.
--create temporary table to hold records
CREATE TABLE #DistinctSortTest (Val1 INT, Val2 INT)
GO
--insert some records
INSERT INTO #DistinctSortTest
VALUES (1,100),(8,55),(3,33),(1,1),(9,999)
GO
--lets see what we have in table
SELECT * FROM #DistinctSortTest
GO
 
From this table we need only “Val1” column with distinct values BUT sorting output with “Val2”. Lets try simple query.
SELECT DISTINCT Val1
FROM #DistinctSortTest
ORDER BY Val2
Opps. Error
Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
To resolve this problem, we can use GROUP BY clause with MIN()or MAX() function in ORDER BY clause. 
SELECT  Val1
FROM #DistinctSortTest
GROUP BY Val1
ORDER BY MIN(Val2)
Through GROUP BY (all select columns) we will achive functionality of DISTINCT and MIN()/MAX() functions for sorting. MIN() in Order By clause can be used for ASC sort and MAX() for DESC sort.
--drop temporary table when not required
DROP TABLE #DistinctSortTest

Monday, September 17, 2012

SQL Server: Disable Logon Trigger Using DAC to Resolve Login Problem


Recently I have received a mail from one of blog reader, who explained his problem as following:
“I have tried scrip to create logon trigger from your blog post Restrict Login from Valid Machine IPs Only (Using Logon Trigger) BUT problem is that, I forgot to put localhost in my safe list, and now I am unable to login to my instance.”

Well, if same happened to you, then you need to login using Dedicated Administrator Connection. What is DAC and how to you use it Read This.
DAC can be established using sqlcmd or through SSMS. On command prompt, type this to establish connection.

Sqlcmd –S localhost –d master –A
You can provide instance name instead of localhost. Next thing is to disable our logon trigger, using following command.

DISABLE TRIGGER tr_LogOn_CheckIP ON ALL SERVER
Where “tr_LogOn_CheckIP” is the name of our logon trigger. On next line type GO to execute DISABLE command.


Now you can login to your database server. Once login, check out trigger is disabled.

You can achieve all this through SQL Server Management Studio. To establishing dedicated connection, click on  FILE----NEW----Database Engine Query

Login through valid SYSADMIN user, by providing server name with extra word and a colon, i.e. Admin:

In query window, type same tsql and execute to disable trigger.

And never forget to add your server IP or <localhost> in safe list, while creating logon trigger.

Wednesday, September 12, 2012

SQL Server: Keeping Log/Alert for Job Disable/Enable Status

To monitor production database servers, Database Administrators create different jobs and depends upon these jobs to work for them i.e. to check if server have enough space, database is not corrupt, queries are not running slow, index defragmentation and many more. BUT what if somehow, someone accidently disabled a job and forgot to enable it back. No alert will be created as job is disabled. Or it can be fatal when you need to restore a database and found that backup job was not working as it was disabled by someone ;)

Is there any way to get alert if someone changes any job status on production server?
YES, by creating following trigger on msdb.dbo.sysjobs can resolve this problem. It will detect any change in job status and will mail a message like following to your DBA team.

Job "Daily Full Backup" is recently DISABLED by user aasim.abdullah with session id 167 and host name IdeaWrox-DB01 at Sep 12 2012 4:00:03:673AM
 
 

Monday, September 10, 2012

SQL Server: Simple Way to Swap Columns values

To resolve a problem, sometime we start thinking at high level while, simple solutions of said problem are available. This is what happened to me, when one of my colleagues (Tehman) asked me how to swap two column values in a table.
My answer was, create a third column (temporary) and swap using this third column, which you can remove later on. Here was the plan.
  1. Move Col2 data to Col3
  2. Move Col1 data to Col2
  3. Move Col3 data to Col1
  4. Drop Col3

-- Create Temporary table to hold values
CREATE TABLE #ForSwappingTest ( Col1 VARCHAR(50), Col2 VARCHAR(50))
-- Insert test reocrds
INSERT INTO #ForSwappingTest (Col1,Col2)
VALUES ('A','X'),
('B','Y'),
('C','Z')
-- Check Results
SELECT * FROM #ForSwappingTest
-- Add third column to hold data temporarily
ALTER TABLE #ForSwappingTest ADD  Col3 VARCHAR(50)
-- Start Swaping
UPDATE #ForSwappingTest
SET COL3 = COL2

UPDATE #ForSwappingTest
SET COL2 = COL1

UPDATE #ForSwappingTest
SET COL1 = COL3
-- Remove additional temporary column
ALTER TABLE #ForSwappingTest DROP COLUMN Col3
--Drop temporary table when not required
DROP TABLE #ForSwappingTest

But he came with a very simple solution, by writing following simple query.
UPDATE #ForSwappingTest
SET Col2 = Col1,
Col1 = Col2