Отправляет email-рассылки с помощью сервиса Sendsay

MS SQL Server

  Все выпуски  

MS SQL Server - дело тонкое...


Информационный Канал Subscribe.Ru

#208<<  #209

СОДЕРЖАНИЕ

1.Обработка исключений в SQL Server 2000 и Yukon
2.ССЫЛКИ НА СТАТЬИ
2.1.Англоязычные статьи
3.ФОРУМ SQL.RU
3.1.Самые популярные темы недели
3.2.Вопросы остались без ответа
4.ПОЛЕЗНОСТИ
4.1.Настройка SQL. Для профессионалов

СОВЕТЫ

Обработка исключений в SQL Server 2000 и Yukon

По материалам статьи Amol Kulkarni: Exception Handling in SQL Server 2000 and Yukon
Перевод Виталия Степаненко

Обработка ошибок играет жизненно важную роль при создании хранимых процедур или скриптов. В этой статье я рассмотрю обработку ошибок в SQL Server 2000 и SQL Server Yukon. Перед рассмотрением обработки ошибок я познакомлю вас с компонентами сообщения об ошибке. Вот типичное сообщение об ошибке, которое вы можете получить, работая в SQL Server 2000 Query Analyzer:

Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__test__08EA5793'. Cannot insert duplicate key in object 'test'.
The statement has been terminated.

Это сообщение состоит из нескольких компонентов, таких, как Msg, Level, State и Line. Рассмотрим подробно каждый из этих компонентов:

Msg - номер сообщения об ошибке. Каждое сообщение об ошибке имеет свой номер, начиная с 0. В предыдущем примере номер сообщения об ошибки - 2627, и каждое такое сообщение имеет свой собственный текст. Вы можете найти информацию по всем сообщениям об ошибках в таблице sysmessages базы данных master. Создавая ваши собственные скрипты, вы можете добавить свои сообщения об ошибках, используя системную хранимую процедуру sp_addmessage. Сообщения с номерами от 50001 зарезервированы для пользователей. Сообщения с меньшими номерами - системные.

Severity Level - определяет серьезность ошибки. Имеет значение от 0 до 25.

Номера от 0 до 10 указывают на информационные сообщения или предупреждения; номера от 11 до 16 указывают на ошибки в программировании (при создании скриптов); уровень серьезности ошибки от 17 и выше обозначает проблемы с отсутствием ресурсов сервера или проблемы с аппаратным обеспечением. Любая ошибка выше 20 уровня прерывает соединение.

State - имеет значение от 0 до 127. Об этом компоненте Microsoft распространила слишком мало информации, поэтому я не буду рассматривать значения компонента State в этой статье.

Line - определяет номер строки в процедуре, функции, триггере или пакете, где возникла ошибка.

Обработка ошибок в SQL Server 2000 и Yukon.

Существуют две причины возникновения сообщений об ошибках в SQL Server 2000 или Yukon; SQL Server может вызвать ошибку, или вы можете сгенерировать ее лично, используя команду RAISERROR. Рассмотрим команду RAISERROR подробнее. Ниже приведен пример:

RAISERROR('This error is raised by me', 16, 1)
В команде вы указываете текст сообщения, уровень серьезности ошибки и ее состояние. Результат выглядит следующим образом:
Server: Msg 50000, Level 16, State 1, Line 1
This error is raised by me

Кроме текста, передаваемого в команду RAISERROR, можно также указать номер сообщения об ошибке, созданного при помощи хранимой процедуры sp_addmessage. Номер пользовательского сообщения об ошибке должен иметь значение от 13000 до 2147483647. Если указывается номер, отсутствующий в таблице sysmessages, то вы получите предупреждение о том, что текст сообщения об ошибке не найден.

Теперь, зная основы работы сообщений об ошибках в SQL Server, давайте рассмотрим обработку ошибок в Transact-SQL. SQL Server позволяет обрабатывать ошибки, используя глобальную переменную @@ERROR. Если генерируется ошибка, то переменная @@ERROR содержит соответствующий номер ошибки, в случае же успеха она возвращает 0. Хранящееся значение номера ошибки может быть положительным, отрицательным, или равным 0. Значение переменной @@ERROR непостоянно, т.е. оно изменяется при выполнении каждой команды. Рассмотрим следующий пример:

Запустив этот код, получим сообщение об ошибке:

Msg 515, Level 16, State 2, Line 2
Cannot insert the value NULL into column 'a', table 'AdventureWorks.dbo.ErrorTest '; column does not allow nulls. INSERT fails.
The statement has been terminated.
Error is 0

По результату можно видеть, что возникла ошибка, но значение переменной @@error равно 0, что означает успешное выполнение. Действительно, 3 строка вызвала ошибку и значение переменной @@error стало равным номеру возникшей ошибки. Но 4 строка выполнилась успешно, поэтому и значение @@error сбросилось в 0. Соответственно, и результат выполнения скрипта равен 0. Поэтому можно заключить, что значение @@error изменяется после выполнения каждой команды. Т.к. значение @@error изменяется так часто, можно воспользоваться локальной переменной для хранения значения @@error, чтобы использовать это значение, когда потребуется, как показано ниже:

В этом случае я использовал локальную переменную @err для хранения значения @@error. Когда я выполнил код, появилось сообщение об ошибке:

Msg 515, Level 16, State 2, Line 2
Cannot insert the value NULL into column 'a', table 'AdventureWorks.dbo.ErrorTest '; column does not allow nulls. INSERT fails.
The statement has been terminated.
Error is 515

Другим возможным способом обработки ошибок является использование глобальных переменных @@rowcount и @@trancount. Как и @@error, эти переменные также часто изменяют свое значение.

@@rowcount - это глобальная переменная, которая хранит количество строк, обработанных последней выполненной командой. Как я уже упоминал, ее значение также постоянно изменяется; значение этой переменной необходимо сохранять в локальных переменных для последующего использования. В определенных случаях возникает необходимость обработать какую-то ситуацию как ошибку, даже если SQL Server все успешно выполнил. Например, вы выполняете команду UPDATE и ожидаете, что она обработает n строк. Однако если она не обработала ни одну строку, то это не вызывает ошибку T-SQL. Такие ситуации могут быть обработаны при помощи переменной @@rowcount. Можно сгенерировать ошибку, используя RAISERROR, если значение @@rowcount не равно ожидаемому.

@@trancount - это глобальная переменная, которая показывает уровень вложенности транзакции. Каждая команда BEGIN TRANSACTION увеличивает значение @@trancount на 1, и каждая команда COMMIT TRANSACTION уменьшает значение @@trancount на 1. На самом деле транзакции не выполняются, пока значение @@trancount не достигнет 0. Команда ROLLBACK TRANSACTION откатывает все изменения до самой первой команды BEGIN TRANSACTION (если только вы не использовали достаточно экзотическую команду SAVE TRANSACTION), и устанавливает @@trancount в 0, независимо от предыдущего значения.

Рассмотрим следующий код:

Вот результаты запуска скрипта:

(1 row(s) affected)

(1 row(s) affected)

Transaction count is :1

(1 row(s) affected)

(1 row(s) affected)

Transaction count is :2

Msg 547, Level 16, State 0, Line 1
INSERT statement conflicted with CHECK constraint 'stud_ck'. The conflict occurred in database 'AdventureWorks', table 'student', column 'marks'.
The statement has been terminated.

(1 row(s) affected)

Error is 547

Transaction count is :3
Transaction count is :2
Transaction count is :1
Transaction count is :0

Из результата выполнения скрипта видно, что значение @@trancount увеличивалось с каждым выполнением BEGIN TRANSACTION, и уменьшалось с каждым выполнением COMMIT TRANSACTION.

Последняя команда COMMIT TRANSACTION установила значение @@trancount в 0, указывая на успешное выполнение скрипта.

Т.к. мы уже обсудили разные пути обработки ошибок в SQL Server 2000, то можно видеть, что такой путь обработки ошибок в SQL Server 2000 неудобен, т.к. для каждой команды должна храниться локальная переменная, что уменьшает ясность кода и увеличивает его сложность и размер.

Новая функциональность при обработке ошибок в SQL Server Yukon.

В Yukon произведено глобальное улучшение обработки ошибок в транзакциях T-SQL. Помимо всей функциональности, присутствующей в SQL Server 2000, теперь можно перехватывать ошибки прерывания транзакции, используя модель TRY/CATCH без потери контекста транзакции. Взглянем на следующий код:

В этом примере я использовал один блок TRY/CATCH и не использовал переменную @@error. Это улучшает читабельность кода и сильно упрощает его написание. Основное правило использования TRY/CATCH состоит в том, что блок CATCH должен сразу следовать за блоком TRY.

Все, что здесь обсуждалось до этого момента, применимо при XACT_ABORT в OFF (по умолчанию). Если XACT_ABORT устанавливается в ON, то большинство ошибок, прерывающих выполнение команды, становятся ошибками, прерывающими выполнение пакета. Рассмотрим следующий код:

Ниже приведен результат выполнения скрипта:

(1 row(s) affected)

(1 row(s) affected)

Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__YukonTest__5E1FF51F'. Cannot insert duplicate key in object 'YukonTest'.
Msg 3903, Level 16, State 1, Line 9
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.

В примере 4, когда XACT_ABORT был установлен в OFF, выполнение вставок не прервалось при возникновении ошибки в строке 6. Была прервана только команда, в которой произошла ошибка. Это называется прерыванием команды. В примере 5, когда XACT_ABORT был установлен в ON, выполнение скрипта прервалось. Т.к. выполнение скрипта прервалось в строке 7, то команда в строке 8 не вставила верное значение.

Работаете ли вы с SQL Server 2000 или хотите узнать Yukon, умение писать хороший код с обработкой всех возможных ошибок является важным условием для достижения вершин мастерства.

Amol Kulkarni является сотрудником Tata Consultancy Services (TCS), Hyderabad, India.

[В начало]

ССЫЛКИ НА СТАТЬИ

Англоязычные статьи

Conditional Statements in WHERE Clauses
Sotiris Filippidis
Ever had a query where you wished you could be able to specify the operator (equal, not equal, greater than, etc.) for each column contained in your WHERE clause, without having to use ugly string concatenations and the infamous EXEC keyword? Here we'll see an example of how this can be achieved with the use of a plain SQL query together with some CASE statements
How To Interact With SQL Server's Data And Procedure Cache
Randy Dyess
As you have worked with SQL Server, you probably have run across the terms data cache and procedure cache, and may have wondered what exactly a cache was. SQL Server is configured to use a physical pool of memory on the server, and it will allocate the majority of this memory pool to hold data pages that have been read, along with the compiled execution plans for all previously-run Transact-SQL statements. It is this dynamic pool of memory that is being referred to by the data cache and procedure cache. Before SQL Server 7.0, the data cache and procedure cache were two separate pools of memory and could be controlled separately. In SQL Server 7.0 and SQL Server 2000, one pool of memory is used both for data and execution plans
Lookup Table Design
Leo Peysakhovich
When I begin to design a new database for a client, one of the dilemmas facing me is how to construct lookup tables
SQL Server 2005 Beta 2 Is Out!!!
Steve Jones
Microsoft quietly announced the release of SQL Server 2005 (Yukon) Beta 2 today in a presspass article on their site. All MSDN customers also were notified that the MSDN download would be available later today. Good luck getting bandwidth from MSDN downloads tonight and tomorrow! I'm sure lots of ISVs as well as us regular geeks are hitting it hard
MDX in Analysis Services: Create a Cube-Based Hierarchical Picklist
William Pearson
As most of us who work in the Business Intelligence community are aware, parameters (sometimes known as "prompts" or "parameter prompts") are a staple of enterprise reporting, because they enable information consumers to quickly find the information they need from a report. These filters can be put in place "on the fly," and are typically enacted when the consumer types or selects a value, or a series of values, at run time
SQL Server 2000 Security - Part 8 - Introduction to Replication Security
Marcin Policht
So far in our series of articles, we have been discussing relatively generic SQL Server 2000 security related issues that every database administrator is likely to encounter on a daily basis. Now it is time to look into less common scenarios that deal with one specific area of management - database replication. We will start by presenting its architecture and implementation options, and follow with their security implications
Microsoft Announces SQL Server 2005 Support For AMD Extended System
Customers and Partners Invited to Start Testing Expanded 64-Bit Functionality With SQL Server 2005 Beta 2 Today
Waiting for Yukon
Tim DiChiara
Picture a barren landscape. Two forlorn and confused SQL Server DBAs wait. And wait. And wait. They try to pass the time. And wait. For something that doesn't come
Sql Server 2005 CLR Native Methods
Peter A. Bromberg
Sql Server 2005 BETA 1 "SQLEXPRESS" was released to the MSDN Subscriber community on July 1, 2004. One of the most interesting new features (and there are many) is the ability to host the CLR runtime and assemblies with code for functions, stored procedures and UDTs (User-Defined Types) written in C# or VB.NET, right inside SQL Server. Once you get the various syntax issues out of the way (there is an extreme lack of good documentation as of this writing in early July, 2004), a whole new world opens up to you as a developer
How to Performance Tune the Microsoft SQL Server tempdb Database
SQL-Server-Performance.Com
If your SQL Server's tempdb database is heavily used by your application(s), consider locating it on an array of its own (such as RAID 1 or RAID 10). This will allow disk I/O to be more evenly distributed, reducing disk I/O contention issues, and speeding up SQL Server's overall performance
Analysis Services Comparison: SQL 2000 vs. SQL 2005
Mark Frawley
Major changes to Business Intelligence (BI) features in SQL Server 2005 promise (or threaten) to alter the way you develop BI applications. Read this comparison article to find out what's changed and start planning today
Unleashing the Power of Data
Howard Goldberg
Ever since the dot.com bust, IT departments have taken some blame for bloated budgets, missed delivery dates, and questionable returns. Leave it to Merrill Lynch to demonstrate how to get IT investments right. After developing a flexible, extensible data warehousing model, Merrill Lynch is reaping returns in cost savings and unexpected benefits - including support for Sarbanes-Oxley compliance efforts and other emerging priorities
Readying SQL Server for an SMS 2003 Installation
Buck Woody
Installing System Management Server 2003 is a daunting task. Here's how to get started. Microsoft's new flagship product for enterprise desktop management, Systems Management Server (SMS) 2003, has several factors to consider for an installation or an upgrade. If you've looked through all 600-plus pages of the planning guide, you've found there are a myriad of choices to make even in the planning stages
Select/Unselect Rows in a Web DataGrid
Dino Esposito
When you have a select command row in a Web DataGrid, the change of the selected item is signaled with the SelectedIndexChanged event. However, before this event is fired, the application can handle the related ItemCommand. Note that the value of the DataGrid’s SelectedIndex property has not been changed yet when ItemCommand arrives. It is set to the new index when SelectedIndexChanged reaches the application
Closing Data Readers Faster
Dino Esposito
The data reader and the connection are distinct objects and should be managed and closed indipendently. Both objects provide a Close method that should be called twice: once on the data reader (first) and once on the connection
Compute Expressions on a DataTable
Dino Esposito
The Compute method of the DataTable class calculates a value by applying a given expression to the table rows that match a specified filter. Expressions can include any sort of boolean and arithmetic operators, but they can also include more interesting aggregate functions such as Min, Max, Count, and Sum, plus a few more statistical operators such as average, standard deviation, and variance. The following code counts the rows in which the Name column begins with A
64-Bit Computing Comes Of Age
John Yacono and John Roberts
64-bit computing is now A reality, and solution providers must begin evaluating how their customers can benefit from this new technology
Database Change Management: An Automated Approach
Darren Fuller
In this first article of a 4 part series, Darren Fuller discusses the need for database change management and problems with current approaches. Future articles in the series will examine an automated methodology, the requirements to implement such an approach and describe the benefits that can be realised
Microsoft SQL Server 2000 Index Defragmentation Best Practices
Mike Ruthruff
As Microsoft SQL Server 2000 maintains indexes to reflect updates to their underlying tables, these indexes can become fragmented. Depending on workload characteristics, this fragmentation can adversely affect workload performance. This white paper provides information to help you determine whether you should defragment table indexes to benefit workload performance. To defragment indexes, SQL Server 2000 provides several statements. This white paper compares two of those statements: DBCC DBREINDEX and DBCC INDEXDEFRAG
Think like a DBA
Andy Warren
I've been managing a small development team for a few months now and one of the more interesting comments has been that I think like a DBA, not a developer. This usually comes about whenever I offer a solution that is more sql based than 'code' based. This article will take about one particular instance. Will be interesting to see what comments are posted!
Collecting and Storing Performance Monitor Counter Data into a SQL Server Table
Gregory A. Larsen
When you are monitoring the performance of your SQL Server machines, what tools do you use? I’m guessing most DBAs use the Windows Performance console to graphically display performance counters for their SQL Server machines. But how do you determine the performance trends over time on your SQL Server machines? Where do you store all the performance data that you gathered when monitoring SQL Server machines? Do you save it in SQL Server database tables? This article will show you how to use the Performance console to set up a counter log to gather performance data for SQL Server 2000. I will discuss how to load the performance data into a SQL Server database table. And I will also cover how to use some Windows XP modules to automatically start your performance counter logs on a Windows 2000 server
Bad SQL: Byting the Hand that Feeds You
Joe Celko
Foundations: Fields and columns are totally different concepts. One reason you came up with a magnetic tape file solution is that you think of SQL as a file system and are mixing physical and logical levels. I keep pounding people on this point, but it really makes a difference
View from the Top — Part 2
Chris Foot
In part two of this article, Chris Foot continues in his interview with three DBA “true technicians” on the current state of database and server technologies and what we can look forward to in the future. This month, find out what each expert would like to see implemented in his respective software platform’s release, which advancements have had the greatest impact on database technologies, what was each vendor’s greatest blunder, and then, there’s that Linux question
The End User Component of Database Administration
James F. Koopmann
If you continually gauge database performance from a strictly database-internal point of view, you are missing the boat. Begin watching your database end users and performance will begin to take on a whole new meaning
Get SQL Server table structure in XML format
Baya Pavliashvili
Developers often ask me if there is a built-in stored procedure in SQL Server 2000 that returns the table structure in XML format. If the front-end or middle-tier code passes data to the stored procedures in XML format, a table structure similar to the following is useful
Verifying input to be passed to a SQL statement
Serdar Yegulalp
Web pages are commonly used as front-ends for input to be passed to a SQL query, as well as ways to return results from a query. Many Web programmers are not accustomed to how input should be passed to a SQL statement, however, and often forget that data cannot be passed as-is to a SQL statement without some pre-processing
DBMS Learning Guides
TechTarget
Our popular Learning Guides are packed with high quality tutorials, expert advice and tips that will help you get up to speed on the most critical topics in data management
DBA resumes that make the cut
Robert Westervelt
Check your spelling. Be specific. And don't lie -- or even exaggerate. Those resume tips might sound obvious, but IT managers and database administrators said the biggest mistakes they see on technical resumes could have been easily avoided
Managed code in SQL Server Yukon: A big deal?
Nick Wienholt
This article attempts to answer the question of when managed code makes sense inside the database
Using Different Techniques for SQL Server Automation
Haidong Ji
In my previous articles (Using xp_cmdshell, Using WMI, Using VBScript, Automate DTS Logging, among others), I talked about various technologies you can use to automate SQL Server management. Different situations call for different techniques. Many times, you may find yourself using a combination of those techniques to achieve your objective

[В начало]

ФОРУМ SQL.RU

Самые популярные темы недели

Крик души типа
выполнить truncate table
Справочник, отдельные таблицы или текстовые поля для небольших перечислений?
Как обратиться к базам на linked server?
Timestamp вдруг перестал означ. при update, insert
Текст ошибки по ее номеру? (@@error)
Какая винда лучше подходит?
База встает в Loading
генерация случайного числа
Создать триггер и избежать рекурсии
DTS. Массовая Загрузка и обработка данных в DWH. (тормоза с SP:Recompile)
Как из ADO вызывать server-side cursors?
А есть ли аналог DECODE из оракла в MSSQL
Помогите с запросом ошибка Server: Msg 303, Level 16, State 1, Line 1
создать таблицу dbo.table а не user.table
Функция или Вьюшка?
Обновление данных на клиенте в реальном времени
Проблемы с датой
выборка по датам
Ошибка при инсталяции Report Service: IIS is either not installed or ...

[В начало]

Вопросы остались без ответа

Microsoft Search Service
SQLCE
отсутствие доступа на SELECT к таблице
Какое соединение быстрее отрабатывает
OFF: Excel и чужой host_name()
обновление подписчика
есть ли инструменты для отладки процедур
Оперативная память или дополнительные RAID?

[В начало]

ПОЛЕЗНОСТИ

Настройка SQL. Для профессионалов

Тоу Д.

Издание: 1-е, 2004 год. ISBN: 5-94723-959-0. Формат: 17x24 см. Объем: 336 стр. Переплет: твердая обложка. Срок выхода: в продаже. Цена: 255 руб

В реальных приложениях, работающих с серверами баз данных, перед разработчиками очень часто встает проблема улучшения производительности SQL-запросов. В этой книге детально и на многочисленных примерах описывается метод, позволяющий кардинально повысить скорость выполнения запросов к базам данных. Прочитав книгу, вы сможете не тратить долгие часы на перебор различных вариантов кода, а максимально быстро найти оптимальный способ построения запроса. Метод настройки SQL-запросов не опирается на случайный или итеративный перебор вариантов кода, а основан на четких и понятных правилах, которые достаточно просты для понимания и основаны на принципах работы SQL-серверов. Книга будет полезна разработчикам систем, взаимодействующих с базами данных, и всем интересующимся аспектами работы SQL-серверов.

[В начало]

#208<<  #209

Вопросы, предложения, коментарии, замечания, критику и т.п. присылайте Александру Гладченко на адрес: mssqlhelp@km.ru

sql.ru Описание рассылки

СЕМИНАРЫ
КОНФЕРЕНЦИИ

МИНИФОРМА
ПОДПИСКИ



ПУБЛИКАЦИИ
АРХИВ


http://subscribe.ru/
http://subscribe.ru/feedback/
Адрес подписки
Отписаться

В избранное