BorderLayoutBoxedLayoutOpenLayoutMaximum textMedium textSmall text


Register
Thursday, November 20, 2008

SQL Server News & Information

tsql, performance tuning, industry trends, & bad jokes

exec spSubscribeMinimize
Print  
sp_help 'jmassie'Minimize

This site is maintained by Jason Massie. He has 10 years experience as a DBA and has specialized in performance tuning for the last five. He was recognized by Microsoft as a SQL Server MVP. Jason has spoken at the Professional Association of SQL Server Conference, the North Texas SQL Server Users Group, SQL Connections and TechED. He has worked at Terremark (formerly Data Return) for nearly a decade.

You can contact him at jason@statisticsio.com or 469.569.5965

Jason has the following certifications:
  • Microsoft Certified IT Professional Database Administrator (early adopter)
  • Microsoft Certified IT Professional Database Developer
  • MCDBA (7.0 and 2000)
  • MCSE
  • MCSD
Print  
tblTagCloudMinimize

Abstracts addition Affinity Aggregation allocation Always Analysis Announced another API Appending article Authentication backup be Behavior between Bootstrapper Breaking Build Cache Caching Check checksums Codeplex collection Connecting contest Controller Creating CTEs CTP CUBE cursors Data Database DATALENGTH Debugging Design Diagnosing Diagnostic Differences Documentation DTS Emergency enhancement Entity ETW Exchange execution Express Extensions Fall February Filestream Filtered group GROUPING have Hosting Idle impact Improvement Increase Index Indexes Inserts Instances Interoperability Introduction IO large Late LOB local Localized Magazine Maintaining Maintenance Management maps March Microsoft minutes missing Mix Never November Offline OLE Online operations operators optimizations Optimized Overlapping Package Page Paging Panacea parallel part Partial Partition partitioned Partitioning PASS Performance PFS plan Plans Practices problem Problems Procedure Program programmatically Programming Protection Queries query read recent Recursive Related released Reports Restore return ROLLUP ROWCOUNT Runtime Security Select Sequence sequential Server Services set SETS Shooting shorts sizes Solutions Sortable SPARSE Spool SQL SQLIOSim SSIS Stalled Star Statement Statements stats Stored strategy Stuck Studio Submission Subreports Suggested Summarizing system Table Tables Tampa Task Than there through Timeouts Total Traces Transaction transfer Tricks Trouble TSQL turning understand Understanding undocumented Unique unused upgrade Upgrading Useful Value variables VDI Vista Will Windows Wireless

Print  

Accessing OS performance counters from tsql through CLR, WMI, and WQL

Posted by Jason on Thursday, November 29, 2007 to WMI, CLR
442 Views | 2 Comments | Article Rating

A cool use of WMI data from within SQL that I have found is getting to OS perfmon data. There are several ways of doing it. I would say the best practice would be CLR if you need it in real time or SSIS if you are logging to a table for reporting purposes. You can also hit it through xp_cmdshell and powershell. This is what I do when I need it quick.

In this blog, we will look at an example of doing this in CLR.  We will be using % processor time but any perform counter is available. A list is here.

DISCLAIMER: I am definitely not a CLR guru. If you know of a better way to code this, please let me know.

Here are some uses. The first two I have in production.

  • A server dashboard with reporting services.
  • A resource governor to conditionally execute tasks like index\stats maintenance.
  • Home grown monitoring apps
  • Integration with your backup to dynamically choose drive based on space.
  • Insert your idea here.

So let’s do this.

--Create Database

create database WMITest01;

 

 

--Enable CLR

exec sp_configure 'clr enabled', 1

reconfigure with override

--Enable trust worthy computing

--This allows us to create assemblies that access resources outside of the database.

alter database WMITest01

set trustworthy  on

 

--This assemby allows us to use WMI in CLR functions and procs.

use wmitest01

go

CREATE ASSEMBLY [System.Management]

AUTHORIZATION [dbo]

FROM 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Management.dll'

WITH PERMISSION_SET = UNSAFE

 

Now, we are going create a new VB(or C# but the sample code is VB) database project in Visual Studio 2005. Now do the following steps:

1.       Add a reference to the WMITest database

2.       Set the project properties to unsafe so we can add a reference to System.Management

3.       Add a database reference to System.Management

4.       Create a new stored procedure

5.       Replace the code with the follow code.

6.       Deploy

 

 

Imports System

Imports System.Data

Imports System.Management

Imports System.Data.SqlClient

Imports System.Data.SqlTypes

Imports Microsoft.SqlServer.Server

 

 

Public Class ProcTimeStoredProcedures

   

    Public Shared Sub pnetWMIProcTime()

 

        Dim searcher As New ManagementObjectSearcher( _

            "root\CIMV2", _

            "select PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor where name = '_Total'")

        For Each queryObj As ManagementObject In searcher.Get()

 

            Dim record As New SqlDataRecord( _

            New SqlMetaData("PercentProcessorTime ", SqlDbType.VarChar, 100))

 

            SqlContext.Pipe.SendResultsStart(record)

 

            record.SetString(0, queryObj("PercentProcessorTime"))

            SqlContext.Pipe.SendResultsRow(record)

        Next

        SqlContext.Pipe.SendResultsEnd()

 

    End Sub

End Class

 

 

So now we can run pnetWMIProcTime and know what the current CPU usage is from within SQL.

email it! |   |   |   |  | 
Permalink     2 Comments  

Rate this Post:
COMMENTS:

Interesting - do you have to register the assembly as UNSAFE?

I ask be I've had one experience with supporting a 3rd party application that used CLR. All of their assemblies were UNSAFE, and this led to a cluster failing over ever 30 minutes, due to memory issues.
Eventually, while they re-coded the application, we reduced SQL memory from 6GB of 8GB, to 3 GB. That finally gave the server stability, even though it affected performance. Still, and application that is failing over can hardly be considered performant, eh?

posted @ Monday, February 25, 2008 5:29 PM by Wanderer


Yah, this is definitely not something to run in your OLTP app. I would keep it as an administrative tool. You can also use xp_cmdshell and powershell. I have a sample here:
http://statisticsio.com/Home/tabid/36/articleType/ArticleView/articleId/13/NTSSUG-Presentation-on-WMI.aspx

In SQL 2008, there are better ways :)

posted @ Monday, February 25, 2008 8:59 PM by JasonMassie


Name (required)

Email (required)

Website


Simple BBCode can be used like [URL]...[/URL] and [B]