SQL Server 2000 Stored Procedure Programming phần 10 ppt

68 298 0
SQL Server 2000 Stored Procedure Programming phần 10 ppt

Đ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

Appendix B: Solutions to the Exercises 665 select @AcquisitionType = AcquisitionType from AcquisitionType where AcquisitionTypeId = @AcquisitionTypeid insert everything insert into #InventoryDenormalized( InventoryId, Make, Model, Location, Status , LeaseNumber , StartDate , EndDate , FirstName , LastName, Rent, Lease , Cost, AcquisitionType, AcquisitionDate) values ( @InventoryId, @Make, @Model, @Location, @Status, @LeaseNumber, @StartDate, @EndDate, @FirstName, @LastName, @Rent, @Lease, @Cost, @AcquisitionType, @AcquisitionDate) FETCH NEXT FROM @CrsrVar INTO @Inventoryid, @EquipmentId, @LocationId , @StatusId, @LeaseId , @LeaseScheduleId, @OwnerId, @Rent , @Lease , @Cost , @AcquisitionTypeID, @AcquisitionDate END CLOSE @CrsrVar DEALLOCATE @CrsrVar select * from #InventoryDenormalized drop table #InventoryDenormalized return 0 CHAPTER 5. FUNCTIONS Exercise 5.1 Create a Select statement that returns the quarter from the current date in the following format: ‘3Q2000’. Exercise 5.1 Solution Use the following code: Select DATENAME(q, GETDATE()) + 'Q' + DATENAME(yyyy, GETDATE()) Exercise 5.2 Create a table called ExpectedShippingDate that contains the following fields: ▼ ExpectedShippingDateId (offset from the starting date) ■ ExpectedShippingDate ■ ExpectedShippingDateOfMonth ■ ExpectedShippingMonth ■ ExpectedShippingYear ▲ ExpectedShippingQuarter The table should be filled with one record for each date since 1/1/2000. Create a stored procedure Setup_ExpectedShippingDate to fill it. Exercise 5.2 Solution Use the following statement to create the table: CREATE TABLE [dbo].[ExpectedShipDate] ( [ExpectedShipDateId] [smallint] NOT NULL , [ExpectedShipDate] [smalldatetime] NULL , [ExpectedShippingMonth] [tinyint] NULL , [ExpectedShippingDay] [tinyint] NULL , [ExpectedShippingYear] [smallint] NULL , 666 SQL Server 2000 Stored Procedure Programming [ExpectedShippingQuarter] [char] (6) NULL ) ON [PRIMARY] GO The table can be filled using the following stored procedure: CREATE PROCEDURE Setup_ExpectedShipDate @ExpectedShipDate smalldatetime = '1/1/2000', @day_number smallint = 5000 as declare @ExpectedShipDateId smallint declare @ExpectedShippingMonth tinyint declare @ExpectedShippingDay tinyint declare @ExpectedShippingYear smallint declare @ExpectedShippingQuarter char(6) not (4) anymore declare @ExpectedShipDatecurrent smalldatetime declare @intErrorCode int set nocount on select @intErrorCode = @@Error If @intErrorCode = 0 begin select @ExpectedShipDateId = 0, @ExpectedShipDatecurrent = @ExpectedShipDate select @intErrorCode = @@Error end while @intErrorCode = 0 and @day_number> 0 begin If @intErrorCode = 0 begin select @ExpectedShipDateId = @ExpectedShipDateId + 1, @ExpectedShippingMonth = datepart (mm, @ExpectedShipDatecurrent), @ExpectedShippingDay = datepart (dd, @ExpectedShipDatecurrent), @ExpectedShippingYear = datepart (yy, @ExpectedShipDatecurrent) select @intErrorCode = @@Error end Appendix B: Solutions to the Exercises 667 If @intErrorCode = 0 begin Set @ExpectedShippingQuarter = dateName (qq, @ExpectedShipDate) + 'Q' + dateName (yyyy, @ExpectedShipDate) select @intErrorCode = @@Error end insert row If @intErrorCode = 0 begin insert into ExpectedShipDate ( ExpectedShipDateId, ExpectedShipDate, ExpectedShippingMonth, ExpectedShippingDay, ExpectedShippingYear, ExpectedShippingQuarter) values (@ExpectedShipDateId, @ExpectedShipDatecurrent, @ExpectedShippingMonth, @ExpectedShippingDay, @ExpectedShippingYear, @ExpectedShippingQuarter) Select @intErrorCode = @@Error End If @intErrorCode = 0 Begin Select @day_number = @day_number - 1, @ExpectedShipDatecurrent = @ExpectedShipDatecurrent + 1 Select @intErrorCode = @@Error End End Return @intErrorCode Go Exercise 5.3 Create a table to store contact information. The last column should contain a binary checksum value so that you can later see if the record has changed. 668 SQL Server 2000 Stored Procedure Programming Appendix B: Solutions to the Exercises 669 Exercise 5.3 Solution The following code snippet shows a new contact table with the BC field reserved for a binary checksum: CREATE TABLE [Contact_with_BC] ( [ContactId] [int] IDENTITY (1, 1) NOT NULL , [FirstName] [varchar] (30) NOT NULL , [LastName] [varchar] (30) NOT NULL , [Phone] [typPhone] NULL , [Fax] [typPhone] NULL , [Email] [typEmail] NULL , [OrgUnitId] [smallint] NOT NULL , [UserName] [varchar] (50) NULL , BC int null ) ON [PRIMARY] GO The value in the BC column can be managed from a trigger: CREATE TRIGGER trContact_with_BC_IU ON [dbo].[Contact_with_BC] FOR INSERT, UPDATE AS update Contact_with_BC set BC = BINARY_CHECKSUM(FirstName, LastName, Phone, Fax, Email, OrgUnitId, UserName) where ContactId in (select ContactId from inserted) GO You can test the table, function, and trigger in the following manner: insert Contact_with_BC (FirstName, LastName, Phone, OrgUnitId) values('Tom', 'Jones', '123-4567', 1) select * from Contact_with_BC update Contact_with_BC set Phone = '313-1313' where ContactId = 1 select * from Contact_with_BC CHAPTER 6. COMPOSITE TRANSACT-SQL CONSTRUCTS—BATCHES, SCRIPTS, AND TRANSACTIONS Exercise 6.1 Create a database script for the Asset database. Exercise 6.1 Solution 1. Open Enterprise Manager. 2. Right-click the Asset database in the Console Tree pane. 3. Select All Tasks | Generate SQL Scripts. 4. Optionally make changes to default parameters, then click OK to accept. 5. When the application prompts you, specify a name for the script file to store the result. Exercise 6.2 Create a database script for a single stored procedure in the Asset database. Add a line of comment into the script and execute it. Exercise 6.2 Solution 1. Open Enterprise Manager. 670 SQL Server 2000 Stored Procedure Programming 2. Right-click the stored procedure in the Asset database for which you want to generate code. 3. Select All Tasks | Generate SQL Scripts. 4. The application displays a dialog box with a single stored procedure selected in the Objects To Be Scripted list (see Figure B-4). Click OK to accept the default parameters. 5. When the application prompts you, specify a name for the script file to be used to store the result. 6. Start Query Analyzer. 7. Open the script file (see the result of File | Open in Figure B-5). 8. Add a line of comment (place ‘ ’ at the beginning of the line). 9. Execute the script (Query | Execute). Appendix B: Solutions to the Exercises 671 Figure B-4. Generating a script for a single stored procedure 672 SQL Server 2000 Stored Procedure Programming Exercise 6.3 What is the problem with the following script? select * from Eq /* Go delete Eq where EqId > 100 Go */ select * from EqType Figure B-5. A script for prListLeasedAssets How can you fix it? Exercise 6.3 Solution The problem is that this script contains a comment that spans multiple batches. If you execute this script from Query Analyzer, it is divided into three batches. The first and the last batch do not execute because they contain incomplete comments. The second batch executes (contrary to expectations) and will purge a good portion of the Eq table. You can fix the problem by changing the location of the comment markers: select * from Eq Go /* delete Eq where EqId > 100 */ Go select * from EqType You can also “comment-out” the Go command by placing two dashes at the beginning of the line with the Go statement: select * from Eq /* Go delete Eq where EqId > 100 Go */ select * from EqType Appendix B: Solutions to the Exercises 673 Exercise 6.4 How do the Rollback Transaction and Commit Transaction statements affect @@trancount? Exercise 6.4 Solution Commit Transaction decreases @@trancount by one. If @@trancount then equals 1, it also commits changes to the database. Rollback Transaction discards all changes and sets @@trancount to 0. Exercise 6.5 Create a table with bank account information and then a stored procedure for transferring funds from one account to another. The stored procedure should contain transaction processing. Exercise 6.5 Solution Use the following code: CREATE TABLE [dbo].[Account] ( [AccountId] [char] (10) NOT NULL , [Balance] [money] NOT NULL , [AccountTypeId] [int] NOT NULL ) GO ALTER TABLE [dbo].[Account] WITH NOCHECK ADD CONSTRAINT [PK_Account] PRIMARY KEY NONCLUSTERED ( [AccountId] ) GO CREATE PROCEDURE prTransferFunds @From char(20), 674 SQL Server 2000 Stored Procedure Programming [...]... 99, 99, 99, 1) CHAPTER 10 ADVANCED STORED PROCEDURE PROGRAMMING Exercise 10. 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 693 694 SQL Server 2000 Stored Procedure Programming Exercise 10. 1 Solution The record... @intErrorCode = @@Error end return @intErrorCode Exercise 10. 2 Take a stored procedure from Exercise 4.7, 4.12, or 7.6 and return the results in a single resultset 695 696 SQL Server 2000 Stored Procedure Programming Exercise 10. 2 Solution I have taken prSpaceUsedByTables_1 from Exercise 4.7 Solution and changed it into the following procedure: Alter Procedure prSpaceUsedByTables_3 loop through table... reserved varchar(18) , data varchar(18) , index_size varchar(18) , unused varchar(18) ) 697 698 SQL Server 2000 Stored Procedure Programming At the end of the stored procedure, results are sent to the caller: select * from #SpaceInfo Exercise 10. 3 Create a new version of the prGetInventoryProperties stored procedure that uses a While statement with a Min() function NOTE: Do not feel frustrated if you... transaction over multiple batches, because SQL Server records them on the level of the user connection However, it is not a recommended practice, because SQL Server blocks resources until the transaction is completed It is important to complete the transaction as quickly as possible to release the blocked resources 675 676 SQL Server 2000 Stored Procedure Programming CHAPTER 7 DEBUGGING AND ERROR HANDLING... stored procedure through TSQL Debugger to try debugging Exercise 7.3 Solution Right-click the procedure in the Object Browser of Query Analyzer Click Debug and the program will prompt you to specify the parameters values, as shown in Figure B-7 Appendix B: Solutions to the Exercises Figure B-6 Executing a stored procedure in Query Analyzer Figure B-7 Debug Procedure dialog box 679 680 SQL Server 2000. .. Solutions to the Exercises T -SQL Debugger window Exercise 7.5 Change the stored procedure from Exercise 6.5 so that it complies with the error handling solution proposed in this chapter Exercise 7.5 Solution Use the following code: CREATE PROCEDURE prTransferFunds_2 @From char(20), @To char(20), @Amount money, @debug int = 0 AS 681 682 SQL Server 2000 Stored Procedure Programming set nocount on Declare... table @debug int = 0 As set nocount on Declare @intErrorCode int, @intTransactionCountOnEntry int, @chvProcedure sysname, @MaxCounter int, @Counter int, @TableName sysname set @chvProcedure = 'prSpaceUsedByTables_2' 683 684 SQL Server 2000 Stored Procedure Programming if @debug 0 select '**** '+ @chvProcedure + ' START ****' Select @intErrorCode = @@Error If @intErrorCode = 0 Begin Create table #Tables... @TableName set @Counter = @Counter + 1 end drop table #Tables if @debug 0 select '**** '+ @chvProcedure + ' END ****' return @intErrorCode CHAPTER 9 SPECIAL TYPES OF PROCEDURES Exercise 9.1 Create a function that returns the last date of a month containing a specified date 685 686 SQL Server 2000 Stored Procedure Programming Exercise 9.1 Solution Use the following code: CREATE FUNCTION fnLastDateOfMonth... @debug 0 677 678 SQL Server 2000 Stored Procedure Programming select @MaxCounter MaxCounter while @Counter . NULL , 666 SQL Server 2000 Stored Procedure Programming [ExpectedShippingQuarter] [char] (6) NULL ) ON [PRIMARY] GO The table can be filled using the following stored procedure: CREATE PROCEDURE. a single stored procedure 672 SQL Server 2000 Stored Procedure Programming Exercise 6.3 What is the problem with the following script? select * from Eq /* Go delete Eq where EqId > 100 Go */ select. Exercises 675 676 SQL Server 2000 Stored Procedure Programming CHAPTER 7. DEBUGGING AND ERROR HANDLING Exercise 7.1 Add debugging code to the following stored procedure: Alter Procedure prSpaceUsedByTables_1

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