SQL Server 2000 Stored Procedure Programming phần 7 pps

76 311 0
SQL Server 2000 Stored Procedure Programming phần 7 pps

Đ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

438 SQL Server 2000 Stored Procedure Programming Close curItems Deallocate curItems Return 0 Go The second stored procedure is generic and converts information from cursors into a single variable: Create Procedure prProcess_Cursor_Nested Process information from cursor initiated in calling sp. Convert records into a single varchar. ( @chvResult varchar(8000) OUTPUT, @debug int = 0 ) As Declare @intCountProperties int, @intCounter int, @chvItem varchar(255), @insLenItem smallint, @insLenResult smallint Fetch Next From curItems Into @chvItem While (@@FETCH_STATUS = 0) Begin If @debug <> 0 Select @chvItem Item check will new string fit Select @insLenItem = DATALENGTH(@chvItem), @insLenResult = DATALENGTH(@chvResult) If @insLenResult + @insLenItem > 8000 Begin Select 'List is too long (over 8000 characters)!' Return 1 End 440 SQL Server 2000 Stored Procedure Programming HOW TO PROCESS THE RESULTSET OF A STORED PROCEDURE From time to time, you will encounter stored procedures that return resultsets you need to process. This is not as simple as it sounds. One option is to receive the resultset in a client application or middleware component and to process it further from there. Sometimes this option is not acceptable for a variety of reasons. For example, the resultset might be too big and network traffic could be considerably increased in this way. Since the resultset needs to be transferred to the middleware server before it is processed, the performance of the system could be degraded. There might be security implications—for example, if a user should have access only to a segment of a resultset and not to the complete resultset. Another option is to copy the source code of the stored procedure into your stored procedure. This could be illegal. It will also reduce the maintainability of your code since you have two copies to maintain. If the other stored procedure is a system stored procedure, Microsoft can change its internals with the release of each new version of SQL Server. Your stored procedure will then need to be changed. It is possible to collect the resultset of a stored procedure in Transact-SQL code. You need to create a (temporary) table, the structure of which matches the structure of the resultset exactly, and then redirect (insert) the resultset into it. Then you can do whatever you want with it. The following stored procedure uses the sp_dboption system stored procedure to obtain a list of all database options and to obtain a list of database options that are set on the Asset database. Records that have a structure identical to that of the resultset as returned by the stored procedure are collected in temporary tables. The Insert statement can then store the resultset in the temporary table. The contents of the temporary tables are later compared and a list of database options not currently set is returned to the caller. Create Procedure prNonSelectedDBOption return list of non-selected database options @chvDBName sysname As Set Nocount On Create Table #setable ( name nvarchar(35) ) Create Table #current ( name nvarchar(35) ) collect all options Insert Into #setable Exec sp_dboption collect current options Insert Into #current Exec sp_dboption @dbname = @chvDBName return non-selected Select name non_selected From #setable Where name not in ( Select name From #current ) Drop Table #setable Drop Table #current Return 0 The only trouble with this method is that you need to know the structure of the resultset of the stored procedure in advance in order to create a table with the same structure. This is not a problem for user-defined stored procedures. It used to be a problem for system Chapter 10: Advanced Stored Procedure Programming 441 442 SQL Server 2000 Stored Procedure Programming stored procedures, but SQL Server Books Online now provides that information. NOTE: Unfortunately, it is not possible to collect information if a stored procedure returns more than one resultset, as is the case with sp_spaceused. This technique also works with the Exec statement. For example, if you try to collect a resultset from the DBCC command this way, SQL Server will return an error. But you can encapsulate the DBCC statement in a string and execute it from Exec. The following stored procedure returns the percentage of log space used in a specified database: Create Procedure prLogSpacePercentUsed return percent of space used in transaction log for specified database ( @chvDbName sysname, @fltPercentUsed float OUTPUT ) As Set Nocount On Declare @intErrorCode int Set @intErrorCode = @@Error If @intErrorCode = 0 Begin Create Table #DBLogSpace ( dbname sysname, LogSizeInMB float, LogPercentUsed float, Status int ) Set @intErrorCode = @@Error End Chapter 10: Advanced Stored Procedure Programming 443 get log space info. for all databases If @intErrorCode = 0 Begin Insert Into #DBLogSpace Exec ('DBCC SQLPERF (LogSpace)') set @intErrorCode = @@Error end get percent for specified database if @intErrorCode = 0 begin select @fltPercentUsed = LogPercentUsed from #DBLogSpace where dbname = @chvDbName set @intErrorCode = @@Error end drop table #DBLogSpace return @intErrorCode You can test this stored procedure from Query Analyzer, as shown on Figure 10-7. These techniques were extremely important before SQL Server 2000. It is now possible to use the table datatype as a return value for user-defined functions. We showed how can you use table-valued user-defined functions in Chapter 9. Unfortunately, it is (still) not possible to use a table variable as the output parameter of a stored procedure. You have another option when you want to pass a resultset (or multiple resultsets) to a calling stored procedure. You can use the cursor datatype as the output parameter of a stored procedure. In the following example, prGetInventoryProperties_CursorGet creates and opens a cursor. It is then returned as a cursor output parameter to the calling procedure: Create Procedure prGetInventoryProperties_CursorGet Return Cursor that contains properties that are describing selected asset. ( @intInventoryId int, @curProperties Cursor Varying Output ) As Set @curProperties = Cursor Forward_Only Static For Select Property, Value, Unit 444 SQL Server 2000 Stored Procedure Programming Figure 10-7. Percentage of log space used in a specified database Chapter 10: Advanced Stored Procedure Programming 445 From InventoryProperty inner join Property On InventoryProperty.PropertyId = Property.PropertyId Where InventoryProperty.InventoryId = @intInventoryId Open @curProperties Return 0 The nested stored procedure will be called from following stored procedure: Create Procedure prGetInventoryProperties_UseNestedCursor return comma-delimited list of properties that are describing asset. i.e.: Property = Value unit;Property = Value unit; Property = Value unit;Property = Value unit; ( @intInventoryId int, @chvProperties varchar(8000) OUTPUT, @debug int = 0 ) As Declare @intCountProperties int, @intCounter int, @chvProperty varchar(50), @chvValue varchar(50), @chvUnit varchar(50), @insLenProperty smallint, @insLenValue smallint, @insLenUnit smallint, @insLenProperties smallint Set @chvProperties = '' Declare @CrsrVar Cursor 446 SQL Server 2000 Stored Procedure Programming Exec prGetInventoryProperties_CursorGet @intInventoryId, @CrsrVar Output Fetch Next From @CrsrVar Into @chvProperty, @chvValue, @chvUnit While (@@FETCH_STATUS = 0) Begin Set @chvUnit = Coalesce(@chvUnit, '') If @debug <> 0 Select @chvProperty Property, @chvValue [Value], @chvUnit [Unit] check will new string fit Select @insLenProperty = DATALENGTH(@chvProperty), @insLenValue = DATALENGTH(@chvValue), @insLenUnit = DATALENGTH(@chvUnit), @insLenProperties = DATALENGTH(@chvProperties) If @insLenProperties + 2 + @insLenProperty + 1 + @insLenValue + 1 + @insLenUnit > 8000 Begin Select 'List of properties is too long (over 8000 chrs)!' Return 1 End assemble list Set @chvProperties = @chvProperties + @chvProperty + '=' + @chvValue + ' ' + @chvUnit + '; ' If @debug <> 0 Select @chvProperties chvProperties Fetch Next From @CrsrVar Into @chvProperty, @chvValue, @chvUnit End Close @CrsrVar Deallocate @CrsrVar Return 0 It is the responsibility of the caller to properly close and deallocate the cursor at the end. TIP: You should not use a cursor as an output parameter of a stored procedure unless you have to. Such a solution is inferior because procedures are coupled and prone to errors. If you are working with SQL Server 2000, you should use table-valued user-defined functions instead. USING IDENTITY VALUES In previous chapters, we introduced the function of identity values in a table. They are used to generate surrogate keys—unique identifiers often based on sequential numbers. A Standard Problem and Solution Identity values are similar to the Autocount datatype in Access tables. But there is one difference that generates many questions in Usenet newsgroups among developers who are used to Access/DAO behavior. When a developer uses a resultset to insert a record into a table, the value of the AutoNumber field is immediately available in Access. Unfortunately, due to the nature of the client/server environment, this is not the case with recordsets in SQL Server. Chapter 10: Advanced Stored Procedure Programming 447 [...]... prGetInventoryProperties stored procedure that uses a While statement with a Min() function 463 CHAPTER 11 Interaction with the SQL Server Environment 465 Terms of Use 466 SQL Server 2000 Stored Procedure Programming T his chapter focuses on the ways you can use system and extended stored procedures to interact with the SQL Server environment It also discusses the ways user-defined stored procedures can help... specify the @propertyvalue, the stored procedure returns it in the form of a single-column, single-row resultset 471 472 SQL Server 2000 Stored Procedure Programming sp_OADestroy When the OLE Automation object is no longer needed, you should use this stored procedure to destroy the instance of it: exec sp_OADestroy objecttoken sp_OAGetErrorInfo Each OLE Automation stored procedure returns a value that...448 SQL Server 2000 Stored Procedure Programming The best way to insert a record into a SQL Server table and obtain an identity key is to use a stored procedure The following stored procedure prInsertInventory is such a solution A new record is first inserted into a table and then the key is read using the @@identity function/global variable Create Procedure prInsertInventory... created in Visual Basic 4 67 468 SQL Server 2000 Stored Procedure Programming NOTE: Even if you run the object from the Visual Basic IDE (instead of compiling and installing it), you will still be able to access it from Transact -SQL code This is an important feature for debugging the object The following stored procedure first initiates the COM object using the sp_OACreate system stored procedure It obtains... SQL Server and solutions for loading timestamp values into client applications Microsoft Search Service is a search engine that allows full-text indexing and querying much like the services we use to query the Web The engine is not relational, but it is possible to use it from stored procedures and Transact -SQL It gives a new dimension to documents stored in SQL Server databases 461 462 SQL Server 2000. .. that the communications between Transact -SQL and Visual Basic code are working, you can use Visual Basic to write code that converts numbers to text Since this is not a book about Visual Basic, we will not go into detail on that subject Instead, we will examine system stored procedures that use OLE Automation in more detail 469 470 SQL Server 2000 Stored Procedure Programming sp_OACreate Before any code... you will have later in production SQL Server 2000 introduces extended properties Users can define extended properties, store them in the database, and associate them with database objects Each database object can have any number of extended properties An extended property can store a sql_ variant value up to 7, 500 bytes long SQL Server 2000 introduces three stored procedures and one function for managing... SQL Server environment By the end of this chapter you will be able to w Use OLE Automation in Transact -SQL s Run programs and operating system commands from the command shell s Manage jobs in Job Scheduler s Read and write Registry entries s Install a database on another server s Use the e-mail capabilities of SQL Server to notify users of events on the server s Use the e-mail capabilities of SQL Server. .. @@ERROR The stored procedure will also return a GUID to the caller A WHILE LOOP WITH MIN OR MAX FUNCTIONS It is possible to iterate through a table or recordset using a While statement with the aggregate function, which returns extreme values: MIN and MAX Take a look at the following batch: get first value Select @Value = MIN(Value) From aTable 4 57 458 SQL Server 2000 Stored Procedure Programming. .. Chapter 10: Advanced Stored Procedure Programming EXERCISES 1 Create a pair of stored procedures that use optimistic locking to obtain and update a record in the Inventory table Assume that the client application cannot handle the timestamp datatype and that you have to use the money datatype instead 2 Take a stored procedure from exercises 7 and 12 in Chapter 4 and exercise 6 in Chapter 7 and return the . a problem for system Chapter 10: Advanced Stored Procedure Programming 441 442 SQL Server 2000 Stored Procedure Programming stored procedures, but SQL Server Books Online now provides that information. NOTE: Unfortunately,. of the client /server environment, this is not the case with recordsets in SQL Server. Chapter 10: Advanced Stored Procedure Programming 4 47 448 SQL Server 2000 Stored Procedure Programming The. Property, Value, Unit 444 SQL Server 2000 Stored Procedure Programming Figure 10 -7. Percentage of log space used in a specified database Chapter 10: Advanced Stored Procedure Programming 445 From

Ngày đăng: 13/08/2014, 08:20

Từ khóa liên quan

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

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

Tài liệu liên quan