Category Archives: SQLServerPedia Syndication

This category is for SQLServerPedia Syndication

T-SQL Tuesday: What’s Currently Running?

My good friend Allen White is hosting this months installment of #TSQL2sDay so I am motivated to jump in. #TSQL2sDay is the creation of Adam Machanic. The concept is simple, about a week before the second Tuesday of the month a theme will be posted.  Any blogger that wishes to participate is invited to write a post on the chosen topic and any post that is related to both SQL Server and the theme is fair game.The challenge for this month’s T-SQL Tuesday is: What T-SQL tricks do you use today to make your job easier?

What’s Currently Running?

One of my favorite tricks is actually just a little script I have in my toolbox to find out what queries are currently running right now. In fact I have had quite a few people ask me the for this script so I am glad to share it in this blog post.  With SQL Server 2005 and above  SQL Server provides Database Management Views that give you direct access to executing requests and running process. The following query uses sys.dm_exec_request, sys.sysprocesses. We will also use cross apply to get the query text from sys.dm_exec_sql_text and the execution plan from sys.dm_exec_query_plan.

The Good Stuff…

{UPDATE: 1/1/2012 – Replaced sysprocesses with sys.dm_exec_sessions as recommended by Phil in the comments}

-- Do not lock anything, and do not get held up by any locks.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT [Spid] = sp.session_Id
,er.request_id
,er.command
,[Database] = DB_NAME(er.database_id)
,[User] = login_name
,er.blocking_session_id
,[Status] = er.status
,[Wait] = wait_type
,CAST('<?query --'+CHAR(13)+SUBSTRING(qt.text,
(er.statement_start_offset / 2)+1,     ((CASE er.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.text)    ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1)+CHAR(13)+'--?>' AS xml) as sql_statement
,[Parent Query] = qt.text
,p.query_plan
,er.cpu_time
, er.reads
, er.writes
, er.Logical_reads
, er.row_count
, Program = program_name
,Host_name
,start_time
FROM sys.dm_exec_requests er INNER JOIN sys.dm_exec_sessions sp ON er.session_id = sp.session_id
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
cross apply sys.dm_exec_query_plan(er.plan_handle) p
WHERE sp.is_user_process = 1
/* sp.session_Id > 50
-- Ignore system spids. -- */
AND sp.session_Id NOT IN (@@SPID)
ORDER BY 1, 2

This years Christmas wish list for Microsoft

Once again its the first Monday of the month. This means its time for another #mememondy presented by Thomas LaRock . This months topic is what gift do you want Microsoft to leave for you under the tree this year? For this post I am going to list two items I would love to see in SQL Server 2012.

  1. Distributed Replay to be easy to configure, work as advertised and include the great reporting features I am used to seeing with RML Utilities.  Currently, I don’t see much for reporting with Distributed Replay in BOL.  No, need to convert SQL Traces multiple times.
  2. AlwaysOn to be included in SQL Server 2012  Standard Edition. Yes, I know this is a long shot but hey its my Christmas list :-)

WVPASS – Performance Tuning for Pirates!

If you are in the Pittsburgh, PA area take a trip down to Wheeling, WV this Thursday to catch me at the WVPASS SQL Server User Group.  Registration is free and there  are a few free seats available.  I will be breaking out a brand new presentation titled “Performance Tuning for Pirates.”

Abstract

If you follow baseball you will notice that my favorite team the Pittsburgh Pirates has to do more with less to be successful. Working as a consultant, I have also noticed this trend with several IT shops. If you need to improve the performance of SQL Server and cannot purchase 3rd party tools this session is for you.  I will help improve your performance tuning process while using several free tools. Through this presentation we will go over wait stats, dynamic management objects, perfmon, PAL, SQL Trace, ClearTrace, SQL Nexus and  SQLDiag.

My #sqlpass 2011 Member Summit Schedule

The following is my tentative plans for the SQL PASS Member Summit this week.  I have listed scheduled sessions to attend but may switch or do something else. You never know what will be going down on the #sqlpass or #sqlfun hash tag on twitter.

Isn’t it awesome that the sessions are recorded and available for playback after the event? I will get the sessions on DVD and will be able to watch them later.

Tuesday, October 11th 2011

* 7:30am to 1pm – Travel to Seattle for PASS Conference (Yes, I am actually writing this on the airplane)
* 1pm to 2pm – Regional Member Meeting (Hopefully, logistics work and I won’t miss this)
* 2:15pm to 5pm – Chapter Leaders Meeting
* 6:30pm to 8pm – Welcome Receptions and Quiz Bowl
* 8pm to 10pm – Red Gate Party

Wednesday, October 12th 2011

* 5:30am to 8am – Visit Pike Place Market or Top Hat Donuts Shop
* 8:15am to 10am – Attend Keynote
* 10:15am to 11:30am – This isn’t your fathers Cloud: Kevin Kline, Buck Woody
* 11:30am to 1:00pm – Chapter Leaders Lunch
* 1:30pm to  3:00pm – Visit and get know Vendors @ Vendor Expo
* 3:00pm to 4:15pm – Tips and Tricks for Writing Better Queries: Joe Webb (AD-314)
* 4:45pm to 6:00pm -  Characteristics of a Great Relational Database : Louis Davison (AD-318)
* 6:15pm to 8:00pm – Attend SQL PASS Vendor Reception
* 8:00pm to 10:00pm – SQLPeople Party & PUSS Party

Thursday, October 13th, 2011

* 8:15am to 10:00am – Keynote Bloggers Table @ Dell Ballroom
* 10:15am to 11:30am – Advanced SQL Server 2008 Troubleshooting: Klaus Aschenbrenner (DBA-403) @ 6E
* 11:30 am to 1:30pm – Women in Technology – Lunch @ 6B
* 1:30pm to 2:45pm – Lighting Talk (I am presenting) @ 201
* 3:00pm to 4:30pm – All the Magic Knobs: Cindy Gross @2AB
* 5pm to 7pm – Vendor Appreciation Party
* 7pm to 10pm – Microsoft Community Appreciation @ GameWorks

Friday, October 14th, 2011

* 7:00am to 8:00am – Breakfast
* 8:15am to 10am – Keynote Presentation or Microsoft Labs
* 10:15am to 11:45am – Query Tuning Mastery: Adam Machanic (AD-500) @ 6E
* 11:30am to 12:30 – Birds of a Feather – Lunch
* 12:15pm to 1:30pm – Board of Directors Meet and Greet
* 1:30pm to 2:30pm – Final review for my sessions
* 2:30pm to 3:45pm – Evaluate your Daily Checklist against 100+ Instances of SQL(ME) @602-604
* 4:15pm to 5:30pm – Best Practices for Deploying SQL Server on VMWare: Wanda He (DBA-310) @ 2AB

Speaking at SQL PASS Member Summit 2011

Last year I attended my first PASS Member Summit in 2010.  After attending the conference I made it a goal to make sure I return.  You see, not only was this the first time I attended but also the first time I was a presenter.  Last year I gave a lighting talk on how to use profiler and a chalk talk on SQL Server 2008 for Developers.

Two weeks ago I got a very cool email.  It asked if I would be interested in being an alternate speaker.  The answer was simple.  Hell yea! I would like to speak at the biggest and best conference for SQL Server Professionals.

My topic is Evaluate Your Daily Checklist against 100+ Instances While You Get A Cup Of Coffee. I will also give a lightning talk on Hosting A SQL Saturday.

Reciently, I downloaded screen flow. I hope to give everyone a teaser video to my session next week.

SQL Saturday #80 was a Success!

On Saturday July 23rd the WVPASS and Greater Wheeling Chapter of AITP joined forces to host the 2nd Annual SQL Saturday in Wheeling, WV. SQLSaturday is a one-day free training event for SQL Server professionals and those wanting to learn about SQL Server brought to you by the local SQL Server community and PASS (Professional Association for SQL Server).

The following is a quick run down of our stats for the event. We had 108 people signup, 85 attendees, 11 speakers covering 18 sessions on Saturday.   Many thanks goes out to the speakers, volunteers, sponsors and attendees for making this a successful SQL Saturday.

The Good

  • We had a great mix of MVP’s, experienced speakers and first time speakers. One of the greatest accomplishments for this event is giving Matt Velic (Check out his #sqlsat80 photo’s), Abi Chapagai and Shannon Lowder their first opportunity to speak at a SQL Saturday. The speakers all did a fantastic job. We received several comments from attendees thanking us for having fantastic speakers.
  • Registration was quick and smooth. Everyone was able to get in and get to the main room to socialize and enjoy a free breakfast. The volunteers did a fantastic job.
  • We took a step outside of the box with lunch and got burrito’s from Salsa Café. With only a few complaints this was a hit. Last year we did box lunches from Panera and it was expensive and we also got lukewarm reviews.
  • Speakers received their evaluation’s shortly after their sessions. Personally, I have spoken at a few events and never received my feedback so I completely understand how important it can be towards growing as a speaker.
  • WVNCC was a fantastic host facility. The staff was very friendly and able to get us everything we needed to be successful.
  • Hosted the event on a $2,400.00 budget. There will be more on this in a future blog post.

Stuff to work on Next year!

  • Speakers dinner might have been a little too early. We held our dinner at 6pm and a few speakers wanted to attend but couldn’t make it in time. We also had plans of following our dinner with a voyage of the Italian Festival but a rain storm quickly sidelined that plan.
  • SQLGolf was a great idea and fun until the heat kicked our butt around the fifth hole. Once we got to the eighteenth hole I forgot we were still playing golf.
  • We need more onsite sponsors next year.
  • Bacon was not included in breakfast.

Speaking at SQLRally today!

A few months ago I blogged that you don’t have to be an expert to speak. This fact is very true as I am speaking at #SQLRally  today about “Evaluating a daily checklist against 100+ instances of SQL Server while you get a cup of coffee.” Two years ago I would have never imagined that it would be possible for me to share my knowledge at SQLPASS events.

NOTE: If you are attending my session and have a camera please take photos and share them with me. I forgot my camera in Wheeling, West Virginia.

If you are at SQLRally or not at SQLRally you can access my slide deck here.  You can also find my references here. If you have any questions feel free to contact me.

Passed my #SQLUniversity PowerShell Midterm!

I am always up for learning something new so I jumped in on the free PowerShell training at SQL University. I saw that Aaron Nelson gave me the tools to loop through a Central Management Server and I was inspired. My main motivation came from learning that Policy-Based Management isn’t the ideal solution for evaluating a daily checklist. I started to notice that the time needed to evaluate full backups started to grow as more databases were added to the farm.

I passed the #SQLU exam and got extra credit!

With the following framework you can automate the process of collecting data from the system tables and DMV’s. In this example we are going to focus on automating the process of collecting failed full backups within the last 24 hours.

NOTE: Remember, you could apply this framework to automate the process of collecting any data from the system tables or DMV’s.

Below is the framework steps: (Steps 1 – 3 are need only for the first implementation)

  1. Configure your Central Management Server (We will assume you have this completed)
  2. Configure your server to run PowerShell with SQL. (Go to PowerShell week at SQLUniversity for the guide)
  3. Get and import the out-DataTable PowerShell function
  4. Create and save T-SQL query you want to run against your SQL farm.
  5. Create table to store results
  6. Create table type required with Table Value Parameters
  7. Create stored procedure to insert DataTable
  8. Automate with SQL Agent Job

PowerShell – Find failed backups in the last 24 hours.

In general the following block of PowerShell will allow you to collect results for any query executed against your SQL Farm with the Central Management Server. With that said, there are a few lines that will need to explain so it can be modified for the code to work in your shop.

  1. On line #1, the CMS for this example is PBMDEMO. You will need to switch this to your CMS server.
  2. On line #4, the T-SQL file is named “Missing Backups.sql” and its located at C:\Demos\CMS_PBM\Scripts\T-SQL. You will need to change this to T-SQL file you want to execute against your SQL farm.
  3. On line #7, the server name and database will need to be changed to your daily checklist repository. In this example I use PBMDEMO and PolicyManagement.
  4. On line #10, the stored procedure name will need to be the name for your stored procedure to input your collected date using Table Value Parameters.
  5. On line #17, The table type will need to match your table type used to strongly type the table parameter in your stored procedure (more on this below)

We will save the PowerShell script as FailedBackups.ps1 in the C:\demos\CMS_PBM\Scripts\PowerShell folder so the SQL Agent job will just load this file when we automate the data collection solution.

foreach ($RegisteredSQLs in dir -recurse SQLSERVER:\SQLRegistration\'Central Management Server Group'\PBMDEMO\ | where {$_.Mode -ne "d"} )
{

$dt = Invoke-sqlcmd -ServerInstance "$($RegisteredSQLs.ServerName)" -Database "tempdb" -InputFile "C:\Demos\CMS_PBM\Scripts\T-SQL\Missing backups.sql" | out-DataTable
$dt
# Write data table to database using TVP
$conn = new-Object System.Data.SqlClient.SqlConnection("Server=PBMDEMO;DataBase=PolicyManagement;Integrated Security=SSPI")
$conn.Open() | out-null
"Connected"
$cmd = new-Object System.Data.SqlClient.SqlCommand("dbo.usp_InsertFailedBackups", $conn)
$cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
#SQLParameter
$spParam = new-Object System.Data.SqlClient.SqlParameter
$spParam.ParameterName = "@TVP"
$spParam.Value = $dt
$spParam.SqlDbType = "Structured" #SqlDbType.Structured
$spParam.TypeName = "FailedBackups"

$cmd.Parameters.Add($spParam) | out-Null
$cmd.ExecuteNonQuery() | out-Null
$conn.Close() | out-Null
}

T-SQL Query to find failed backups. You will need to save it as “Missing Backup.sql” and place it in the C:\Demos\CMS_PBM\Scripts\T-SQL folder or modify the second line of code in the PowerShell example above to have the correct name and path.

BEGIN

DECLARE @BackupDB TABLE (database_name varchar(255), last_db_backup_date datetime, database_id integer)
INSERT INTO @BackupDB (database_name, last_db_backup_date, database_id)
SELECT
 msdb.dbo.backupset.database_name,
 MAX(msdb.dbo.backupset.backup_finish_date) AS last_db_backup_date,
 DB_ID(database_name)
FROM   msdb.dbo.backupmediafamily
 INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id
WHERE  msdb.dbo.backupset.type = 'D'
GROUP BY
 msdb.dbo.backupset.database_name
ORDER BY
 msdb.dbo.backupset.database_name

SELECT SERVERPROPERTY('ServerName') AS ServerName, name AS DatabaseName, last_db_backup_date
FROM master.dbo.sysdatabases  d LEFT JOIN @BackupDB b ON (DB_ID(d.name) = b.database_id)
WHERE (last_db_backup_date < DATEADD(hh, -24, getdate())
OR b.last_db_backup_date IS NULL)
AND dbid > 4
END

Create Table

The following table will be used to save the results for running the above t-sql query against the SQL Server farm.

CREATE TABLE [dbo].[FailedBackups](
[ServerName] [varchar](250) NULL,
[DatabaseName] [varchar](max) NULL,
[DateCaptured] [datetime] NULL,
[last_db_backup_date] [datetime] NULL
) ON [PRIMARY]

GO

Create Table Type

The table type is used as a requirement of using Table Value Parameters. This allows the stored procedure to know what table you are trying to pass to the stored procedure. The last five columns are required by the out-DataTable powershell function.

CREATE TYPE [dbo].[FailedBackups] AS TABLE(
[ServerName] [varchar](250) NOT NULL,
[DatabaseName] [varchar](max) NOT NULL,
[last_db_backup_date] [datetime] NULL,
[RowError] [varchar](1000) NULL,
[RowState] [varchar](1000) NULL,
[Table] [varchar](1000) NULL,
[ItemArray] [varchar](1000) NULL,
[HasErrors] [varchar](1000) NULL
)
GO

Create Insert Stored Procedure

The following stored procedure leverages Table Value Parameters to input a DataTable and do a insert select statement to populate the table.

CREATE PROCEDURE [dbo].[usp_InsertFailedBackups] @TVP FailedBackups readonly
AS
BEGIN

INSERT INTO dbo.FailedBackups (ServerName,DatabaseName, DateCaptured, last_db_backup_date)
SELECT  ServerName,
DatabaseName,
GETDATE(),
last_db_backup_date
FROM    @TVP
END

Automate Data Collection with SQL Agent and PowerShell

If you have used the Central Management Server you will notice quickly that you cannot schedule a query to run agains your farm. An easy work around is to use PowerShell to run your t-sql via a SQL Agent Job. Below is an simple scripted example that does that.

USE [msdb]
GO

/****** Object:  Job [Daily Checklist - Failed Backups]    Script Date: 05/11/2011 23:43:52 ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]]    Script Date: 05/11/2011 23:43:52 ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Daily Checklist - Failed Backups',
 @enabled=1,
 @notify_level_eventlog=0,
 @notify_level_email=0,
 @notify_level_netsend=0,
 @notify_level_page=0,
 @delete_level=0,
 @description=N'No description available.',
 @category_name=N'[Uncategorized (Local)]',
 @owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [PowerShell - Find Failed Backups]    Script Date: 05/11/2011 23:43:53 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'PowerShell - Find Failed Backups',
 @step_id=1,
 @cmdexec_success_code=0,
 @on_success_action=1,
 @on_success_step_id=0,
 @on_fail_action=2,
 @on_fail_step_id=0,
 @retry_attempts=0,
 @retry_interval=0,
 @os_run_priority=0, @subsystem=N'PowerShell',
 @command=N'. C:\Demos\CMS_PBM\Scripts\PowerShell\out-DataTable.ps1
. C:\Demos\CMS_PBM\Scripts\PowerShell\FailedBackups.ps1',
 @database_name=N'master',
 @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
 IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

GO

Intro to Central Management Server

Do you have a DBA team that consists of more than one dba? Do you have a windows authenticated account that has access to all the SQL Server instances in your farm? If so, you might really want to consider leveraging the Central Management Server (CMS) to do your heavy lifting.

Today, we will cover creating your first Central Management Server. Come back later in the week to see a great example to automate the process of verifying full daily backups.

image

 Step 1: You might not be able to registered serves or see Central Management Servers in SQL Server Management Studio. To view them click on view in the menu bar and click on Registered Servers.

image

 Step 2: Now that you can see Central Management Server folder right click on it and click on Register Central Management Server. This will allow you to designate a server as your Central Management Server.

image

 Step 3: Register your new CMS. In this example I am going to use PBMDEMO\SQL2008 as my Central Management Studio. Once you enter the name test the connection and then save your settings.

image

Step 4: Now that the PBMDEMO\SQL2008 Central Management Server is configured lets add a group to hold development and production instances. This is done by right clicking on the instance (PBMDEMO\SQL2008) and clicking on New Server Group.

image

Step 5: Configure a folder for your production servers. We will use Production as the group name. This will be shown as a folder in the screen shot below.

image

Step 6: Configure a folder group for your development servers. In this case we will add our SQL Express edition as a development server.

image

Step 7: Lets add our Express edition server to the development group. Right click on Development folder and select New Server Registration.

image

Step 8: Add PBMDEMO\SQLEXPRESS as the server name and test the connection. Once its successful save the connection. Lets now repeat steps 7 and 8 to add four instances of SQL Server to the production group (PBMDEMO, PBMDEMO,2008 and PBMDEMO\2005, PBMDEMO\2000)

image 

The screen shot above should be the final result for adding five production instances and one development instance. Come back later in the week as we show you how to leverage the CMS server to run and automate the execution of multi-server queries.

Get your learn on… May 2011

May is a great month for DBA’s and developers in Pittsburgh, PA and Wheeling, WV. Here are some great events you should attend this month.

Pittsburgh, PA and Wheeling, WV

Update 5/10/2011: Included SharePoint meeting as recommended by John Scott.

Date Host Meeting
May 11th Greater Wheeling Chapter of AITP Blogging – what is it and why should I?
May 11th Pittsburgh SharePoint User Group Upgrading to SharePoint 2010: A Panel Discussion
May 16th Pittsburgh .NET User Group Visual Studio Product Tour
May 24th Pittsburgh SQL Server User Group Virtualization and SAN Basics for DBAs
May 26th WVPASS –Wheeling SQL UG Database Mirroring: The Bear Necessities

SQL Rally!

This week I will be getting my connect, share and learn on in Orlando, Florida at SQL Rally(yes, you can still sign up!). I cannot wait to connect with my friends in the SQL Server community.  I also look forward to making some new ones. I will be sharing my knowledge on “Evaluating your Daily Checklist against 100+ instances of SQL Server while you get a cup of coffee.” I will also be participating in the Mock Interview Overdrive session hosted by Kevin Kline.  I also look forward to learning from the vendors and some of the best presenters in the SQL Server community.

Speaking of vendors, I look forward to catching up with Confio, Idera, SQLSentry (bonus points for being a WVPASS sponsor), Quest, RedGate and DELL.  I also look forward to meeting new vendors like entrinsik, Enterprise Software Solutions, Melissa DATA.

I am sure I will have some ad-hoc changes but I still want to share my schedule for next week.

Day Event Description
Wednesday Free Day! There are some really good pre-con sessions. I might jump in one of these sessions or see the sites of Orlando.
  After-Hours Activities Beer, Wings and SQL Networking  at Buffalo Wild Wings
  After-Hours Activities Pirate’s Cove for miniature golf.
Thursday Morning Session I The Dirty Dozen: PowerShell Scripts for the Busy DBA – Aaron Nelson
  Morning Session II Visit the SQL Rally vendors!
  Morning Session III Understanding Storage Systems and SQL Server – Wes Brown
  Lunch! WIT Luncheon and Panel Discussion
  Afternoon Session I T-SQL Code Sins: The Worst Things We Do to Code, and WhyJennifer McCown
  Afternoon Session II Writing faster queries – Tim Chatman
  Afternoon Session III SQL University: Lightning TalksJorge Segarra
  SQLRally OverDrive
Conducting an Interview – Participating
  After-Hours Activities meet up at nearby Old Town
Friday Morning Session I Big and Tall: When to Partition – Kendra Little
  Morning Session II Prepare for my presentation and visit vendors!
  Morning Session III Evaluate your daily checklist against 100+ instances of SQL Server while you get a cup of coffee – ME!
  LUNCH!!  
  Afternoon Session I Deadlocking for Mere MortalsJonathan Kehayias
  Afternoon Session II Windows PowerShell Best Practices for SQL DBA’s – Ed Wilson
  Afternoon Session III Fundamentals of SQL Server InternalsJeremiah Peschka
  Vendor Raffle