Модераторы: Akina
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Сообщение об ошибке 
:(
    Опции темы
Vit
Дата 9.2.2006, 17:23 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Vitaly Nevzorov
****


Профиль
Группа: Экс. модератор
Сообщений: 10964
Регистрация: 25.3.2002
Где: Chicago

Репутация: 5
Всего: 207



Отловил я @@Error, хочу получить нормальное сообщение обошибке. Как? В справке написано что описание взять в sysmessages, там описание конечно есть, но не полное, типа:

Цитата
Must declare the variable '%.*ls'.


или

Цитата
The %S_MSG '%.*ls' is out of the range of computer representation (%d bytes).


А как из него получить сообщение с подставленными правильными сообщениями?



--------------------
With the best wishes, Vit
I have done so much with so little for so long that I am now qualified to do anything with nothing
Самый большой Delphi FAQ на русском языке здесь: www.drkb.ru
PM MAIL WWW ICQ   Вверх
boevik
Дата 9.2.2006, 21:55 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник Клуба
Сообщений: 1452
Регистрация: 31.5.2004
Где: Израиль

Репутация: 15
Всего: 35



Занимался я этой проблемой, но так и не нашел решения.
Пока удовлетворяюсь номером ошибки.

Если найдешь, что либо стоящее - поделись.


--------------------
Никогда не говори никогда
PM MAIL WWW   Вверх
SergeBS
Дата 10.2.2006, 13:37 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1111
Регистрация: 10.6.2005
Где: Владимир

Репутация: 5
Всего: 22



Vit
А откуда ловишь? ODBC/ADO/...?
PM MAIL   Вверх
Vit
Дата 10.2.2006, 13:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Vitaly Nevzorov
****


Профиль
Группа: Экс. модератор
Сообщений: 10964
Регистрация: 25.3.2002
Где: Chicago

Репутация: 5
Всего: 207



Из самого сервера


--------------------
With the best wishes, Vit
I have done so much with so little for so long that I am now qualified to do anything with nothing
Самый большой Delphi FAQ на русском языке здесь: www.drkb.ru
PM MAIL WWW ICQ   Вверх
SergeBS
Дата 10.2.2006, 15:56 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1111
Регистрация: 10.6.2005
Где: Владимир

Репутация: 5
Всего: 22



Vit
Все равно не понял. Из Query Analyserа, что ли? Пример какой-нибудь есть?
PM MAIL   Вверх
Vit
Дата 14.2.2006, 16:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Vitaly Nevzorov
****


Профиль
Группа: Экс. модератор
Сообщений: 10964
Регистрация: 25.3.2002
Где: Chicago

Репутация: 5
Всего: 207



Например нужна такая SP:

Код

Create procedure SureExec
@sql varchar(8000)
As
begin
  Declare @Error int
  Exec(@sql)
  Set @error=@@error
  if @Error=0
    Insert into MyLogTable (Result) Values ('Operation was completed successfully') 
  else
    Insert into MyLogTable (Result) Values ('Operation was faled with the error message:'+
{Вот тут что писать?})                                                                                         

end



--------------------
With the best wishes, Vit
I have done so much with so little for so long that I am now qualified to do anything with nothing
Самый большой Delphi FAQ на русском языке здесь: www.drkb.ru
PM MAIL WWW ICQ   Вверх
SergeBS
Дата 16.2.2006, 19:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1111
Регистрация: 10.6.2005
Где: Владимир

Репутация: 5
Всего: 22



Vit,
По-моему, ничего. Это уже дело провайдера - получить ошибку и строку ее объясняющую.

BOL:
Цитата

Handling Errors and Messages in Applications
Errors raised either by Microsoft® SQL Server™ or the RAISERROR statement are not part of a result set. Errors are returned to applications through an error handling mechanism separate from the processing of result sets.

Each database API has some set of functions, interfaces, methods, objects or structures through which they return errors and messages. Each API function or method typically returns a status code indicating the success of that operation. If the status is anything other than success, the application can call the error functions, methods, or objects to retrieve the error information.
...
Applications using APIs such as ADO and OLE DB cannot generally distinguish between errors and messages. In ODBC applications, messages generate a SQL_SUCCESS_WITH_INFO function return code, and errors usually generate a SQL_ERROR return code. The difference is most pronounced in DB-Library, in which errors are returned to the application error handler function, and messages are returned to the application message handler function.

ODBC Error Handling
The ODBC specification introduced an error model that has served as the foundation of the error models of the generic database APIs such as ADO, OLE DB, and the APIs built over ODBC (RDO, DAO, and the MFC Database Classes). In the ODBC model, errors have the following attributes:
...
SQLSTATE
The SQLSTATE is a five-character error code defined originally in the ODBC specification. SQLSTATEs are common across all ODBC drivers and provide a way for applications to code basic error handling without testing for all the various error codes returned by various databases. The ODBC SQLSTATE has nothing to do with the state attribute of SQL Server error messages.

ODBC 2.x returns one set of SQLSTATE codes, and ODBC 3.x returns a set of SQLSTATE codes aligned with the X/Open Data Management: Structured Query Language (SQL), version 2 standard. Because all ODBC drivers return the same sets of SQLSTATE codes, applications basing their error handling on SQLSTATE codes are more portable.

Native error number
The native error number is the error number from the underlying database. ODBC applications receive the SQL Server error numbers as native error numbers.

Error message string
The error message is returned in the error message string parameter.

When an ODBC function returns a status other than SQL_SUCCESS, the application can call SQLGetDiagRec to get the error information. For example, if an ODBC application gets a syntax error (SQL Server error number 170), SQLGetDiagRec returns:

szSqlState = 42000, pfNative = 170

szErrorMsg =

'[Microsoft][ODBC SQL Server Driver][SQL Server]

                                    Line 1: Incorrect syntax near *'

 

The ODBC SQLGetDiagField function allows ODBC drivers to specify driver-specific diagnostic fields in the diagnostic records returned by the driver. The SQL Server ODBC driver specifies driver-specific fields to hold SQL Server error information such as the SQL Server severity and state codes.

For more information about retrieving error messages in ODBC applications, see Handling Errors and Messages.

ADO Error Handling
ADO uses an Errors object and Errors collection to return standard error information such as SQLSTATE, native error number, and the error message string. These are the same as their ODBC counterparts. ADO does not support any provider-specific error interfaces, so SQL Server-specific error information such as the severity or state are available to ADO applications.

For more information about retrieving error messages in ADO applications, see Errors Collection and Error Object.

Для ADO:
Код


procedure TForm1.Button1Click(Sender: TObject);
var
    Ret_val,
    i : integer;
    s : string;
begin
  ADOCommand1.Parameters.Clear;
  ADOcommand1.CommandText := 'update inval'#13#10+'set data_uch = ''abcd'' ';
  ADOcommand1.Execute;
  Ret_val  := ADOcommand1.Parameters.ParamByName('RETURN_VALUE').Value;
  for i := 0 to ADOconnection1.Errors.Count - 1 do
  begin
    s := Format('failed with code %d Number %d and Message %s ',
        [Ret_val,
        ADOconnection1.Errors[i].Number,
        ADOconnection1.Errors[i].Description]);
    showmessage(s);
  end;
end;

вернет
syntax error converting character string to smalldatetime data type

Строка точь в точь как от QA
Кинь пример SP, возвращающей код ошибки (чтобы ошибалась). Воткну и посмотрю что вернет. Фантазии не хватает.

PM MAIL   Вверх
Vit
Дата 16.2.2006, 23:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Vitaly Nevzorov
****


Профиль
Группа: Экс. модератор
Сообщений: 10964
Регистрация: 25.3.2002
Где: Chicago

Репутация: 5
Всего: 207



В том то и дело что никакой клиентской программы нет, есть набор SP, есть навороченная конфигурация процессов засунутая в десяток таблиц, и автоматический вызов процессов в MS SQL Agent... Всё это работает вполне успешно без каких-либо клиентских приложений, но если случаются ошибки то надо бы отловить нормальное описание и сохранить в таблице. Уж не знаю как запускает запросы MS SQL Agent... наверное используя то же OLE DB, но как повлиять на этот процесс не имею ни малейшего понятия...


--------------------
With the best wishes, Vit
I have done so much with so little for so long that I am now qualified to do anything with nothing
Самый большой Delphi FAQ на русском языке здесь: www.drkb.ru
PM MAIL WWW ICQ   Вверх
SergeBS
Дата 17.2.2006, 10:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1111
Регистрация: 10.6.2005
Где: Владимир

Репутация: 5
Всего: 22



Vit,
Работа с журналом событий SQL Server
Посмотри. В этот журнал можно писать откуда хочешь. Больше пока ничего в голову не приходит. На работе авральчик.

PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "MS SQL"
Akina

Akina

Запрещается!

Публиковать ссылки и обсуждать взлом чего бы то ни было.

  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы составления неспецифических запросов рассматриваются здесь
  • Используйте теги [code=sql][/code] для подсветки кода. Используйтe чекбокс "транслит" (возле кнопок кодов) если у Вас нет русских шрифтов.

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Zloxa, Akina.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | MS SQL Server | Следующая тема »


 




[ Время генерации скрипта: 0.0478 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.