SQL Server MVP Deep Dives- P9

40 333 0
SQL Server MVP Deep Dives- P9

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

276 CHAPTER 18 Getting and staying connected—or not Server directly via ports is OK but I beg to disagree as I’m concerned with hard-coding ports and network snooping Building any connection strategy is all about what works for your application architecture and security infrastructure In some cases the just-in-time connection strategy makes sense, but in others it incurs needless overhead Sometimes the connection pool 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 complicated than they have to be by overloading our readers and clients with a lot of unnecessary detail Considering that most SQL Server implementations are SQL Server Express, those that mold opinions need to remember to keep things simple whenever possible without compromising security or performance For the most part, the developers I work with want solutions, not options I hope this chapter has provided some of these solutions About the author William (Bill) Vaughn is an industry-recognized author, mentor, and subject-matter expert on Visual Studio, SQL Server, Reporting Services, and data access technologies He’s worked in the computer industry for over 37 years In 2000, after 14 years at Microsoft, 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 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross 19 Extending your productivity in 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 those T-SQL maniacs That’s why the ability to define custom keyboard shortcuts in SQL Server Management Studio (SSMS) in Microsoft SQL Server 2005 and 2008, and SQL Server Query Analyzer in Microsoft SQL Server 2000, is one of my favorite features of those applications I love the idea that during the development of my database, 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 the object definition, or finding dependencies between database objects If you spend some time on writing your own utils to fit your needs, I can promise you won’t regret it Custom keyboard shortcuts Both Query Analyzer and SSMS provide the ability to call T-SQL code with custom keyboard shortcuts You can define the shortcuts using the main menus of those applications (note that the way you define the shortcuts in both applications is slightly different) To define custom shortcuts in Query Analyzer: On the Tools menu, click Customize (see figure 1) Figure To define custom keyboard shortcuts in Query Analyzer, in the Tools menu, click Customize 277 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross 278 CHAPTER 19 Figure Extending your productivity in SSMS and Query Analyzer Keyboard shortcuts defined in the Customize window in Query Analyzer ƒ In the Customize window (shown in figure 2), add your T-SQL code next to the chosen keyboard shortcut and click OK To define custom shortcuts in SSMS: On the Tools menu, click Options (see figure 3) Figure To define custom keyboard shortcuts in SSMS, in the Tools menu, click Options In the Options window, in the Environment node, click Keyboard (see figure 4) 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 stored procedures—for example, sp_who and sp_help What makes this feature powerful is that you can use these shortcuts with the text selected in the query editor window You select the text, press the appropriate shortcut, and then the code assigned to the shortcut is concatenated with the text you’ve selected and the result of concatenation is executed Let’s see some examples By default, the Alt-F1 shortcut is reserved for the sp_help system stored procedure Open Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross Creating your custom utility to use with keyboard shortcuts Figure 279 Keyboard shortcuts defined in the Options window in SSMS 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 result should consist of the metadata of the sys.objects catalog view) NOTE In Query Analyzer, custom keyboard shortcuts also work with text selected in the Results or the Messages tabs In SSMS, you can’t use custom 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 custom 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 needed for writing some new T-SQL code Let’s create a sample util to demonstrate the idea How often you need to get the list of a table’s columns or procedure’s parameters? In my experience, this needs to be done on a regular basis Let’s write a utility named sp_getcolumns, which will return a list of columns or parameters of a database object of our choice NOTE The sample stored procedure sp_getcolumns demonstrated in this chapter will work in SQL Server 2005 and 2008 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross 280 CHAPTER 19 Extending your productivity in SSMS and Query Analyzer The prefix sp_ isn’t accidental here If you want the procedure to work with database objects 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 no matter what the current database of your session is (SQL Server will search the master database for objects prefixed with sp_) Listing shows an example of what the procedure’s code can look like You can add some improvements I’ll provide some suggestions later in this chapter Listing USE GO Creating sample utility sp_getcolumns master 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 = AS SET NOCOUNT ON DECLARE @lines TABLE ( line_id int identity(1,1) primary key, line nvarchar(4000) ) IF EXISTS (SELECT FROM sys.all_columns WHERE [object_id] = ➥OBJECT_ID(@object)) BEGIN IF @horizontal = 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 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross Creating your custom utility to use with keyboard shortcuts 281 First of all, note that I use the sys.all_columns catalog view to retrieve the column list (to retrieve the column list in SQL Server 2000, you should use the dbo.syscolumn system 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 production databases Also, it may be required to mark your newly created procedure as a system object with an undocumented stored procedure— sp_MS_MarkSystemObject Otherwise your procedure may not work properly with all databases within the SQL Server instance Remember that the sp_MS_MarkSystemObject system procedure is for internal use only and isn’t supported by Microsoft; therefore, never use it against objects in your production databases The procedure has two parameters: @object (the name of the database object for which the column list should be returned) and @horizontal—this parameter decides whether 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 procedure you write to limit the information messages (such as the number of rows affected by the query) sent by SQL Server to the applications My procedure uses a table variable called @lines A simple IF condition controls the way the column/parameter list is inserted into the @lines variable I wanted the result list to be comma separated; therefore, the comma is concatenated to every column/parameter name The last comma is unnecessary, so I remove it, either by using LEFT function (for column/parameter list returned horizontally) or by simple UPDATE statement (for the list returned vertically) Finally, all rows from the @lines table variable are returned in the appropriate order Simple, isn’t it? All you have to after you create the procedure is to assign a custom keyboard shortcut to it Then you can test the util Go to one of your databases, write the name of one of your database objects (if you use the fully qualified name of the object, put it in single quotes), and press the appropriate keys on your keyboard The example is shown in figure A parameter list of the Figure Sample use of the sp_getcolumns utility sp_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 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross 282 CHAPTER 19 Extending your productivity in SSMS and Query Analyzer ƒ Use nvarchar(max) data type for line column in the @lines table variable and for the @line variable (in SQL Server 2005/2008 only) ƒ Perform concatenation with FOR XML PATH clause (in SQL Server 2005/2008 only) or CLR aggregate function (this will let you avoid the nasty string concatenation 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 table This 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 immensely improve your productivity A skilled developer can avoid using the mouse in a graphical interface and just use a keyboard to execute T-SQL code As a result, some SQL Server developers are considered magicians because they can everything just by quickly tapping the keyboard About the author Pawel Potasinski is a database developer and consultant working for Asseco Business Solutions S.A corporation He’s been working with 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 MVP since 2008 In 2007, he founded the Polish SQL Server User Group Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross 20 Why every SQL developer needs a tools database Denis Gobo SQL isn’t an object-oriented language There’s no notion of inheritance The closest 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 a distance calculation algorithm in SQL Other developers copied this same code for use in their projects After some time, the original developer finds a small defect in the code he wrote He updates his code and contacts the other developers so that they 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 make the code change ƒ A lot more people have to make changes now; this will increase the chance of mistakes ƒ All the other developers have to update and test their code to make sure it works 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 should have 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 database shouldn’t format dates based on a calendar table from the human resources database; 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 283 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Licensed to Kerri Ross 284 CHAPTER 20 Why every SQL developer needs a tools database ƒ 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 the fly without having to store the data itself Using a numbers table, you can also setbased operations; this will speed up some operations dramatically because you aren’t looping anymore To find gaps in identity values, all you need to is left-join your table with a numbers table and select the rows that have no value Splitting off strings can 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 numbers table, you’ll need about 13 megabytes If you’re just doing date ranges and splitting off strings, then 10,000 rows might be enough; if you need to find identity gaps, then you need more rows than the maximum value in your identity column Let’s start by creating our numbers table We this by creating an empty table, into which we insert 251 rows with values between and 250 with the SQL script in listing Listing Script to create a numbers table CREATE TABLE Numbers(number int primary key not null) GO DECLARE @Loop int SET @Loop = SET NOCOUNT ON WHILE @Loop

Ngày đăng: 08/11/2013, 02:15

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan