Custom keyboard shortcuts Both Query Analyzer and SSMS provide the ability to call T-SQL code with customkeyboard shortcuts.. Creating your custom utility to use with keyboard shortcuts
Trang 1Server directly via ports is OK but I beg to disagree as I’m concerned with hard-codingports and network snooping.
Building any connection strategy is all about what works for your application tecture and security infrastructure In some cases the just-in-time connection strategymakes sense, but in others it incurs needless overhead Sometimes the connectionpool helps improve performance, but at other times it just gets in the way
Sometimes we as writers, consultants, and pundits make things a lot more cated than they have to be by overloading our readers and clients with a lot of unnec-essary detail Considering that most SQL Server implementations are SQL ServerExpress, those that mold opinions need to remember to keep things simple wheneverpossible without compromising security or performance For the most part, the devel-opers I work with want solutions, not options I hope this chapter has provided some
compli-of these solutions
About the author
William (Bill) Vaughn is an industry-recognized author, mentor,and subject-matter expert on Visual Studio, SQL Server, Report-ing Services, and data access technologies He’s worked in thecomputer industry for over 37 years In 2000, after 14 years atMicrosoft, Bill stepped away to work on his books, consulting,mentoring, and independent training seminars He’s written
over a dozen books, including Hitchhiker’s Guide to Visual Studio and SQL Server (7th Edition) and Hitchhiker’s Guide to SQL Server Compact Edition He and Peter Blackburn also wrote the critically acclaimed Hitchhiker’s Guide to SQL Server 2000 Reporting Services
Trang 2in SSMS and Query Analyzer Pawel Potasinski
Many SQL Server developers and administrators prefer to use T-SQL code instead of
a graphical interface to perform their common duties I’m definitely one of thoseT-SQL maniacs That’s why the ability to define custom keyboard shortcuts in SQLServer Management Studio (SSMS) in Microsoft SQL Server 2005 and 2008, andSQL Server Query Analyzer in Microsoft SQL Server 2000, is one of my favorite fea-tures of those applications I love the idea that during the development of my data-base, which contains more than 100,000 objects at the moment, I can use my utils
to easily perform everyday tasks such as searching for a specific object, showing theobject definition, or finding dependencies between database objects If you spendsome time on writing your own utils to fit your needs, I can promise you won’tregret it
Custom keyboard shortcuts
Both Query Analyzer and SSMS provide the ability to call T-SQL code with customkeyboard shortcuts You can define the shortcuts using the main menus of thoseapplications (note that the way you define the shortcuts in both applications isslightly different)
To define custom shortcuts in Query Analyzer:
1 On the Tools menu, click Customize (see figure 1)
Figure 1 To define custom keyboard shortcuts in Query Analyzer, in the Tools menu, click Customize
Trang 3 In the Customize window (shown in figure 2), add your T-SQL code next to thechosen keyboard shortcut and click OK.
To define custom shortcuts in SSMS:
1 On the Tools menu, click Options (see figure 3)
2 In the Options window, in the Environment node, click Keyboard (seefigure 4)
3 Add your T-SQL code next to the chosen keyboard shortcut and click OK
In both applications, some shortcuts are reserved by default for system storedprocedures—for example, sp_who and sp_help
What makes this feature powerful is that you can use these shortcuts with the textselected in the query editor window You select the text, press the appropriate short-cut, and then the code assigned to the shortcut is concatenated with the text you’veselected and the result of concatenation is executed Let’s see some examples Bydefault, the Alt-F1 shortcut is reserved for the sp_help system stored procedure Open
Figure 2 Keyboard shortcuts defined in the Customize window in Query Analyzer
Figure 3 To define custom keyboard shortcuts in SSMS, in the Tools menu, click Options
Trang 4Creating your custom utility to use with keyboard shortcuts
a new query window in SSMS (or Query Analyzer), connect to any SQL Server 2005 or
2008 instance, and type the following:
'sys.objects'
Then select the text you’ve just written and press Alt-F1 This should display the result
of the sp_help procedure executed with 'sys.objects' as a parameter (the resultshould consist of the metadata of the sys.objects catalog view)
NOTE In Query Analyzer, custom keyboard shortcuts also work with textselected in the Results or the Messages tabs In SSMS, you can’t use cus-tom shortcuts with text selected in any of the mentioned tabs
Creating your custom utility
to use with keyboard shortcuts
When you know how to define your own keyboard shortcuts, you can create some
cus-tom stored procedures to use with the feature I call those procedures utilities or—shorter—utils, probably because of their frequent use in my everyday work Most
of my utils are procedures to query the metadata and return some information neededfor writing some new T-SQL code Let’s create a sample util to demonstrate the idea How often do you need to get the list of a table’s columns or procedure’s parame-ters? In my experience, this needs to be done on a regular basis Let’s write a utilitynamed sp_getcolumns, which will return a list of columns or parameters of a databaseobject of our choice
NOTE The sample stored procedure sp_getcolumns demonstrated in this ter will work in SQL Server 2005 and 2008
chap-Figure 4 Keyboard shortcuts defined in the Options window in SSMS
Trang 5The prefix sp_ isn’t accidental here If you want the procedure to work with databaseobjects in every single database in your SQL Server instance, the best way is to create it
in the master database and name it with an sp_ prefix so that you can easily call it nomatter what the current database of your session is (SQL Server will search the master
database for objects prefixed with sp_).
Listing 1 shows an example of what the procedure’s code can look like You canadd some improvements I’ll provide some suggestions later in this chapter
USE master GO
IF OBJECT_ID('dbo.sp_getcolumns','P') IS NOT NULL DROP PROC dbo.sp_getcolumns
GO CREATE PROC [dbo].[sp_getcolumns]
@object sysname,
@horizontal tinyint = 0 AS
SET NOCOUNT ON DECLARE @lines TABLE ( line_id int identity(1,1) primary key, line nvarchar(4000)
)
IF EXISTS (SELECT 1 FROM sys.all_columns WHERE [object_id] =
➥OBJECT_ID(@object)) BEGIN
IF @horizontal = 1 BEGIN DECLARE @line nvarchar(4000) SET @line = N''
SELECT @line = @line + [name] + N', ' FROM sys.all_columns
WHERE [object_id] = OBJECT_ID(@object) ORDER BY column_id
INSERT @lines (line) SELECT LEFT(@line,LEN(@line)-1) END
ELSE BEGIN INSERT @lines (line) SELECT [name] + N',' FROM sys.all_columns WHERE [object_id] = OBJECT_ID(@object) ORDER BY column_id
UPDATE @lines SET line = LEFT(line,LEN(line)-1) WHERE line_id = @@IDENTITY END
END SELECT line AS ' ' FROM @lines ORDER BY line_id GO
Listing 1 Creating sample utility sp_getcolumns
Trang 6Creating your custom utility to use with keyboard shortcuts
First of all, note that I use the sys.all_columns catalog view to retrieve the columnlist (to retrieve the column list in SQL Server 2000, you should use the dbo.syscolumnsystem table)
NOTE Normally you should avoid the sp_ prefix for your stored procedures.
Use it only in development or for testing, and not in your tion databases Also, it may be required to mark your newly createdprocedure as a system object with an undocumented storedprocedure—sp_MS_MarkSystemObject Otherwise your procedure maynot work properly with all databases within the SQL Server instance.Remember that the sp_MS_MarkSystemObject system procedure is forinternal use only and isn’t supported by Microsoft; therefore, neveruse it against objects in your production databases
produc-The procedure has two parameters: @object (the name of the database object forwhich the column list should be returned) and @horizontal—this parameter decideswhether the columns are returned as a single line (@horizontal = 1) or each column
is returned as a single line in a result set (@horizontal <> 1)
The SET NOCOUNT ON line should be used as a best practice in every stored dure you write to limit the information messages (such as the number of rows affected
proce-by the query) sent proce-by SQL Server to the applications
My procedure uses a table variable called @lines A simple IF condition controlsthe way the column/parameter list is inserted into the @lines variable I wanted theresult list to be comma separated; therefore, the comma is concatenated to every col-umn/parameter name The last comma is unnecessary, so I remove it, either by usingLEFT function (for column/parameter list returned horizontally) or by simple UPDATEstatement (for the list returned vertically)
Finally, all rows from the @lines table able are returned in the appropriate order
vari-Simple, isn’t it?
All you have to do after you create theprocedure is to assign a custom keyboardshortcut to it Then you can test the util Go
to one of your databases, write the name ofone of your database objects (if you use thefully qualified name of the object, put it insingle quotes), and press the appropriatekeys on your keyboard The example is shown
in figure 5 A parameter list of thesp_getcolumns stored procedure is returned(current database: master)
Some thoughts on how you can improve the procedure presented in this chapter:
Add an option to return the data types of the columns/parameters
Figure 1 Sample use of the
sp_getcolumns utility
Trang 7 Use nvarchar(max) data type for line column in the @lines table variable andfor the @line variable (in SQL Server 2005/2008 only).
Perform concatenation with FOR XML PATH clause (in SQL Server 2005/2008only) or CLR aggregate function (this will let you avoid the nasty string concate-nation performed on the @line variable)
Use the NOLOCK hint to avoid unnecessary locking on the system objects
Some ideas for utilities to implement
Here are some ideas of other utilities that might be useful for you:
Searching for database objects by name
Searching for database objects depending on the given object
Scripting database objects
Selecting sample rows from a tableThis is a call to action! Create your own utilities, assign them to the custom shortcuts,and make your everyday work more efficient than ever before
Summary
With custom keyboard shortcuts and your own stored procedures, you can immenselyimprove your productivity A skilled developer can avoid using the mouse in a graphi-cal interface and just use a keyboard to execute T-SQL code As a result, some SQLServer developers are considered magicians because they can do everything just byquickly tapping the keyboard
About the author
Pawel Potasinski is a database developer and consultant workingfor Asseco Business Solutions S.A corporation He’s been workingwith SQL Server since 2000 His focuses are data transfer processes,performance troubleshooting, and dynamic code generation.Pawel holds MCT certification since 2004 and is a SQL Server MVPsince 2008 In 2007, he founded the Polish SQL Server User Group
Trang 8needs a tools database Denis Gobo
SQL isn’t an object-oriented language There’s no notion of inheritance The est thing that SQL has to objects are views, user-defined functions, and stored pro-cedures Picture a developer at a software shop; this developer has written adistance calculation algorithm in SQL Other developers copied this same code foruse in their projects After some time, the original developer finds a small defect inthe code he wrote He updates his code and contacts the other developers so thatthey can make the modification in their code
This approach has a few problems; here are three of them:
The original developer could forget to contact another developer to makethe code change
A lot more people have to make changes now; this will increase the chance ofmistakes
All the other developers have to update and test their code to make sure itworks as expected
As you can imagine, it’s much easier to change and test the code in one place This
is the primary reason you need a tools database Ideally, the tools database shouldhave loosely coupled code and data; it shouldn’t have data and code that depend
on another user-created database To give you an example, the tools databaseshouldn’t format dates based on a calendar table from the human resources data-base; the calendar table should be stored in the tools database itself
What belongs in the tools database?
The following are examples of what should go in a tools database:
ZIP code and address tables
Auxiliary table of numbers
Maintenance procedures for the database server
Trang 9 Reporting procedures showing connected users, free space, or file sizes
ISO country and currency code tables
Region- and country-specific calendar tables
Creating the tools database
Begin by creating the following database on your server:
CREATE DATABASE Tools GO
USE Tools GO
Using an auxiliary table of numbers
A numbers table can be useful for a variety of reasons You can create result sets on thefly without having to store the data itself Using a numbers table, you can also do set-based operations; this will speed up some operations dramatically because you aren’tlooping anymore To find gaps in identity values, all you need to do is left-join yourtable with a numbers table and select the rows that have no value Splitting off stringscan also be accomplished fairly easy with a numbers table, as you’ll see later on How big should a numbers table be? To store a million numbers in a numberstable, you’ll need about 13 megabytes If you’re just doing date ranges and splittingoff strings, then 10,000 rows might be enough; if you need to find identity gaps, thenyou need more rows than the maximum value in your identity column
Let’s start by creating our numbers table We do this by creating an empty table,into which we insert 251 rows with values between 0 and 250 with the SQL script inlisting 1
CREATE TABLE Numbers(number int primary key not null) GO
DECLARE @Loop int SET @Loop = 0 SET NOCOUNT ON WHILE @Loop <=250 BEGIN
INSERT Numbers(number) VALUES (@Loop) SET @Loop = @Loop + 1
END GO
Generating a calendar on the fly
Let’s look at how you can use a numbers table to create a result set of dates Whenworking with dates and number tables, you’ll use the DATEADD function The syntax forDATEADD function looks like this: DATEADD ( datepart , number, date )
Listing 1 Script to create a numbers table
Trang 10Using an auxiliary table of numbers
The first argument is datepart; if we use mm for datepart, we’re telling the tion to use months The second argument is number; this tells the function what to add
func-to the date You can also pass in negative values for subtraction
The third argument is date; this is a valid date or something that can be converted
to a date To see how this works, run the following piece of code:
SELECT DATEADD(mm,1,'20090501') (Result set)
2009-06-01 00:00:00.000
As you can see after passing a value of 1 for the number argument, the date was mented by a month If we pass in a negative number, we’ll get a date that’s a monthearlier than we passed in, as the following code demonstrates:
incre-SELECT DATEADD(mm,-1,'20090501') (Result set)
2009-04-01 00:00:00.000
Now it’s time to use our numbers table to create some dates The query in listing 2will add one month multiplied by the number in the numbers table to today’s dateand return the next 100 months, beginning with today’s date
SELECT DATEADD(mm,number,CONVERT(varchar(8),GETDATE(),112)) FROM dbo.Numbers
WHERE number < 100 ORDER BY number
The query creates the dates in the result set in listing 3
2008-10-29 00:00:00.000 2008-11-29 00:00:00.000 2008-12-29 00:00:00.000 2009-01-29 00:00:00.000
2017-01-29 00:00:00.000
If you add a minus sign in front of number, it’ll go back in time As shown in listing 4,
we can use the minus sign before a number to go back in time
SELECT DATEADD(mm,-number,CONVERT(varchar(8),GETDATE(),112)) FROM dbo.Numbers
WHERE number < 100 ORDER BY number
The query creates the dates in the result set in listing 5
Listing 2 Query to create dates from the numbers table
Listing 3 Abridged result set of dates created from the numbers table
Listing 4 Query to create dates in the past from the numbers table
Trang 112008-10-29 00:00:00.000 2008-09-29 00:00:00.000 2008-08-29 00:00:00.000
WHERE number < 100
The result set of the query is listed in listing 7
2000-01-01 00:00:00.000 2000-03-31 00:00:00.000 2000-04-01 00:00:00.000 2000-06-30 00:00:00.000 2000-07-01 00:00:00.000 2000-09-30 00:00:00.000
2024-10-01 00:00:00.000 2024-12-31 00:00:00.000
Splitting strings with a numbers table
Numbers tables are also handy if you need to split delimited strings Take, for ple, the following string: 'Z,X,A,B,D,F,Z,Z,Z,Z,A,V,S,Q,L,B,B,B,B,B' You want
exam-to get all the characters in that string without duplicates This is easily accomplishedwith a numbers table First, create the stored procedure in listing 8
CREATE PROCEDURE SplitString
@StringToSplit varchar(1000),
@Delimiter varchar(10) AS
SELECT DISTINCT SUBSTRING(@Delimiter + @StringToSplit + @Delimiter, number
➥+ 1, CHARINDEX(@Delimiter, @Delimiter + @StringToSplit + @Delimiter, number + 1)
➥- number -1) As StringItem FROM Numbers
WHERE number <= LEN(@Delimiter + @StringToSplit + @Delimiter) - 1 AND SUBSTRING(@Delimiter + @StringToSplit + @Delimiter, number, 1) =
➥@Delimiter ORDER BY StringItem GO
Listing 5 Abridged result set of dates created in the past from the numbers table
Listing 6 Query to return the first and last day of every quarter from 2000 to 2024
Listing 7 Abridged result set of query in listing 6
Listing 8 Stored procedure to split delimited strings with the numbers table
Trang 12Using an auxiliary table of numbers
Here’s how you’d call that stored procedure with a string delimited with commas:
EXEC SplitString 'Z,X,A,B,D,F,Z,Z,Z,Z,A,V,S,Q,L,B,B,B,B,B',','
The result set of unique characters in a string is shown in listing 9
A B D F L Q S V X Z
Here’s an example with a pipe symbol as delimiter:
EXEC SplitString 'Z|X|A', '|' (Result set)
A X Z
The same code from the stored procedure, but with comments explaining how itworks, is shown in listing 10
This will hold the delimited string DECLARE @StringToSplit varchar(1000) SELECT @StringToSplit ='Z|X|A' This is the delimiter DECLARE @Delimiter varchar(10) SELECT @Delimiter= '|'
Return unique values SELECT DISTINCT Add the delimiters to the string and add 1 to the start position SUBSTRING(@Delimiter + @StringToSplit + @Delimiter, number + 1, Until you find the next delimiter
CHARINDEX(@Delimiter, @Delimiter + @StringToSplit + @Delimiter, number + 1)
➥- number -1) As StringItem Use the numbers table to loop FROM Numbers
Keep going until you arrive at the end of the string WHERE number <= LEN(@Delimiter + @StringToSplit + @Delimiter) - 1 Return only positions between delimiters
AND SUBSTRING(@Delimiter + @StringToSplit + @Delimiter, number, 1) =
➥@Delimiter ORDER BY StringItemListing 9 Result set of unique characters in a string
Listing 10 Stored procedure with comments
Trang 13As you can see, I created a stored procedure and made it accept different delimiters;this provides flexibility and also one codebase I don’t need to have a stored proce-dure for every delimiter that can possible be used.
Placing common code in the tools database
Common code is code that typically can be written and consumed only one way
Convert-ing from Celsius to Fahrenheit, convertConvert-ing from miles to kilometers, and calculatConvert-ingsales tax are some examples
Let’s look at a sales tax calculation example; each state will have a current tax rateand a previous tax rate in a table The row where the EndDate is NULL is the currenttax rate; the row where the EndDate isn’t NULL is a previous tax rate When we add anew tax rate, we simply update the row where the EndDate column has a NULL valuewith the current date and insert a new row with a NULL value for the EndDate
Create the StateTaxRates table in listing 11 and insert four rows for state tax rates
CREATE TABLE StateTaxRates(StateCode char(2) NOT NULL, StartDate datetime NOT NULL,
EndDate datetime, TaxRate decimal(4,4) NOT NULL) GO
INSERT StateTaxRates VALUES('NJ','20010101','20070101',.07) INSERT StateTaxRates VALUES('NJ','20070102',NULL,.08) INSERT StateTaxRates VALUES('CA','20010101','20080101',.0825) INSERT StateTaxRates VALUES('CA','20080102',NULL,0.09)
The user-defined function that calculates the tax is shown in listing 12
CREATE FUNCTION CalculateStateTax(@Value decimal(20,8),@StateCode
➥char(2),@Date datetime) RETURNS decimal(20,4) AS
BEGIN DECLARE @TaxRate decimal(4,4) Grab latest tax rate
IF @Date IS NULL BEGIN
SELECT @TaxRate = TaxRate FROM StateTaxRates WHERE StateCode = @StateCode AND EndDate IS NULL
END ELSE Grab tax rate for a specific day BEGIN
SELECT @TaxRate = TaxRate FROM StateTaxRatesListing 11 Table for state tax rates
Listing 12 User-defined function to calculate tax
Trang 14Formatting
WHERE StateCode = @StateCode AND @Date >= StartDate AND @Date < EndDate END
Do the calculation by multiplying the tax with the amount RETURN @Value * @TaxRate
END GO
Four example calls and their results are shown in listing 13
SELECT dbo.CalculateStateTax(100,'NJ',null) (Result set)
8.0000 SELECT dbo.CalculateStateTax(100,'NJ','20020101') (Result set)
7.0000 SELECT dbo.CalculateStateTax(10000,'CA',null) (Result set)
900.0000 SELECT dbo.CalculateStateTax(100000,'CA','20020101') (Result set)
8250.0000
Formatting
In general, formatting should be done in the presentation layer, but sometimes youneed to generate a file and the recipient needs certain values to be in a specific for-mat Take a date for example; what if you want a date in the format YYYY-MM-DD? SQLServer has a bunch of formats built in, but it doesn’t have that one Create the func-tion in listing 14
CREATE FUNCTION FormatDateDash(@Date datetime) RETURNS varchar(10)
AS BEGIN RETURN CONVERT(varchar(10),@Date,120) END
GO
Now call it like this:
SELECT dbo.FormatDateDash(getdate()),dbo.FormatDateDash('20010101') (Result set)
2008-10-29 2001-01-01Listing 13 Four example calls and their results
Listing 14 Function to format a date
Trang 15Calling code from a different database
In order to call code that resides in a different database, you’ll need to use three-partnotation Three-part notation looks like this:
DatabaseName.Schema.Object
A stored procedure named SplitString exists in the tools database within the dboschema In order to execute this stored procedure from the temp database, your codewould look like this:
USE tempdb GO
EXEC Tools.dbo.SplitString 'Z|X|A', '|' GO
You need to have appropriate permissions in order to call objects in a database fromanother database!
About the author
Denis Gobo resides in Princeton, New Jersey, with his wife andthree kids For the last four years, Denis has been working forDow Jones, where his task is to optimize the storage and retrieval
of a good amount of data; most of this data is stored in SQLServer Denis is a cofounder of http://lessthandot.com, a com-munity site for tech professionals, where he also blogs andanswers questions in the forums In his free time, Denis likes toread, watch horror movies, and spend time with his family
Trang 16Cristian Lefter
With every release of SQL Server, new features are added Also, some features are
discontinued or marked as deprecated, which means that they’ll be removed in a
future version of SQL Server Starting with SQL Server 2008, the deprecation policy
is taken very seriously How seriously? Seriously enough to mention that the firstpublic CTP of the product came with a feature that allows you to monitor usage ofdeprecated functionality You may ask yourself: why would I need to track the usage
of deprecated features?
Among the possible reasons are the following two:
You can obtain greater longevity for an application if you’re an applicationdeveloper
You can identify possible upgrade problems for your existing applicationsbefore the next release of SQL Server hits the shops
The deprecation feature consists of two components:
The SQLServer:Deprecated Features object performance counter
The Deprecation category of trace events, including the DeprecationAnnouncement event class (indicates that a feature will be removed in a futureversion of SQL Server) and the Deprecation Final Support event class (indi-cates that a feature will be removed in the next major release of SQL Server) The complete list of deprecated features can be found in Books Online and hasmore than nine printed pages Table 1 displays a few of them
Table 1 Deprecated features
Deprecated feature Replacement DATABASEPROPERTY DATABASEPROPERTYEX
The 80 compatibility level and upgrade from version 80
Only compatibility levels for the last two versions of the uct available
Trang 17prod-A simple usage example
To get a feel for how the deprecation feature works, listing 1 shows how to read theperformance counter SQLServer:Deprecated Features before and after using theDATABASEPROPERTY function (which will be replaced by the DATABASEPROPERTYEX func-tion) Note that if you run the sample on a named instance, you have to change thecounter name
Declare a variable to hold the current value of the counter DECLARE @CurrentCount bigint;
SELECT @CurrentCount = cntr_value FROM sys.dm_os_performance_counters WHERE
object_name='SQLServer:Deprecated Features' AND instance_name='DATABASEPROPERTY';
Increase the value of the counter by 1 using the deprecated feature the function DATABASEPROPERTY SELECT DATABASEPROPERTY('master','IsTruncLog') AS IsTruncLog;
Retrieve the difference between the current counter value and the original value
The value returned is 1 (or greater if another session used the DATABASEPROPERTY function after saving the counter value SELECT
(cntr_value - @CurrentCount) AS SessionUsage FROM sys.dm_os_performance_counters
WHERE object_name='SQLServer:Deprecated Features' AND instance_name='DATABASEPROPERTY';
The example in the listing reads the performance counters from T-SQL by using thesys.dm_os_performance_counters dynamic management view A more attractiveimage can be obtained using the Performance Monitor From the SQLServer:Depre-cated Features performance object, select and add the DATABASEPROPERTY counter.Then back in the SQL Server Management Studio, run again the next statement:
SELECT DATABASEPROPERTY('master','IsTruncLog') AS IsTruncLog;
text , ntext , image data types varchar(max) , nvarchar(max) , varbinary(max)
data types sp_attach_db CREATE DATABASE statement with the FOR ATTACH
Trang 18Methods of tracking deprecated features
Figure 1 shows the SQLServer:Deprecated Features performance object in mance Monitor
Perfor-Methods of tracking deprecated features
Probably the most useful scenario based on tracking deprecated features is to collectdata and save it on a data store, and then build a report over the data store andoptionally include the report in SQL Server Management Studio The frequency ofcollection, the synchronous or asynchronous mode of collection, and the data storeused are a matter of choice (personally I prefer using Extended Events) Some of thepossible tracking methods follow:
Performance Monitor—Can be used to display graphically the values of counters
for the SQLServer:Deprecated Features performance object
The sys.dm_os_performance_counters Dynamic Management View—Based on the
same SQLServer:Deprecated Features performance object, it allows takingsnapshots for the current values of the counters
The performance logs and alerts—Use the same object as for Performance
Moni-tor; the difference is that the values can be tracked over time
SQL Profiler and SQL Trace—This method is based on the Deprecation
Announcement and the Deprecation Final Support event classes
Figure 1 Tracking deprecated features using Performance Monitor
Trang 19 Event notifications—This method consists of creating an event notification for
the DEPRECATION_ANNOUNCEMENT and DEPRECATION_FINAL_SUPPORT events Astored procedure can be used to log the events
Extended Events—The sqlserver.deprecation_announcement and the
sql-server.deprecation_final_support events support this method An example
is provided later on
SQL Trace Collector—If you need automation for collecting deprecation events,
the SQL Trace Collector part of the Data Collector architecture can be helpful
WMI—This method consists of creating SQL Agent alerts based on WMI ries It’s mentioned only as a possible option, not as a suggestion, because itdoesn’t bring any advantages over the other methods
que-The next section highlights two of the mentioned methods First, a simple skeletonfor the event notifications method is displayed in listing 2
Create a queue CREATE QUEUE DeprecationFeatures_Queue;
GO Create a service CREATE SERVICE DeprecationFeatures_Service
ON QUEUE DeprecationFeatures_Queue([http://schemas.microsoft.com/SQL/
Notifications/P
➥ostEventNotification]);
GO Create a route CREATE ROUTE DeprecationFeatures_Route WITH SERVICE_NAME = N'DeprecationFeatures_Service', ADDRESS = N'LOCAL';
GO Create the actual event notification CREATE EVENT NOTIFICATION DeprecationFeatures_Notification
ON SERVER FOR DEPRECATION_ANNOUNCEMENT, DEPRECATION_FINAL_SUPPORT
TO SERVICE 'DeprecationFeatures_Service', 'current database';
GOListing 2 Event notification method
Listing 3 Extended Events method
Trang 20Methods of tracking deprecated features
Add a the ring buffer target and configure it to retain 1000 events
ALTER EVENT SESSION TrackDF
ON SERVER ADD TARGET package0.ring_buffer (
SET occurrence_number = 1000 );
GO Start the session and begin event collection ALTER EVENT SESSION TrackDF
ON SERVER STATE = start GO
Use a deprecated feature SELECT DATABASEPROPERTY('master','IsTruncLog') AS IsTruncLog;
View the collected events SELECT CAST(xet.target_data as xml) FROM sys.dm_xe_session_targets xet JOIN sys.dm_xe_sessions xe
ON (xe.address = xet.event_session_address) WHERE xe.name = 'TrackDF'
GO Stop the event session and remove it from the server ALTER EVENT SESSION TrackDF
ON SERVER STATE = STOP;
GO DROP EVENT SESSION TrackDF
ON SERVER GO
The result of the previous SELECT query is displayed in listing 4
<RingBufferTarget eventsPerSec="0" processingTime="0"
➥totalEventsProcessed="1" eventCount="1" droppedCount="0"
<type name="unicode_string" package="package0" />
<value>DATABASEPROPERTY will be removed in the next version of SQL ➥Server Avoid using this feature in new development work, and plan to ➥modify applications that currently use it.</value>
<text />
Listing 4 XML result