当前位置: 代码迷 >> Sql Server >> 怎样捕获sql server的错误
  详细解决方案

怎样捕获sql server的错误

热度:25   发布时间:2016-04-27 15:09:59.0
怎样捕获sql server的异常

比如一个主键已经存在,当我再插入这个主键时,数据库就有异常说违反了约束,怎么样捕获这个异常呢?   谢谢


------解决方案--------------------
create table test(id int primary key not null)
insert test select 1
insert test select 1
select description from master..sysmessages where error=@@error
drop table test
------解决方案--------------------
个人认为比较好的办法是在客户端使用try...catch结构,将执行SQL的语句放在try中,然后在catch中调取ADO的ERRORS集合对象中的错误信息.
------解决方案--------------------
SQL code
捕获错误还是在程序中好,TRY CATCH,A. 创建特定消息下例显示可能出现的两种错误。第一种错误很简单,生成的是静态消息。第二种错误则是在尝试修改的基础上动态生成的。CREATE TRIGGER employee_insupdON employeeFOR INSERT, UPDATEAS/* Get the range of level for this job type from the jobs table. */DECLARE @@MIN_LVL tinyint,   @@MAX_LVL tinyint,   @@EMP_LVL tinyint,   @@JOB_ID smallintSELECT @@MIN_LVl = min_lvl,    @@MAX_LV = max_lvl,    @@ EMP_LVL = i.job_lvl,   @@JOB_ID = i.job_idFROM employee e, jobs j, inserted i WHERE e.emp_id = i.emp_id AND i.job_id = j.job_idIF (@@JOB_ID = 1) and (@@EMP_lVl <> 10) BEGIN   RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)   ROLLBACK TRANSACTIONENDELSEIF NOT @@ EMP_LVL BETWEEN @@MIN_LVL AND @@MAX_LVL)BEGIN   RAISERROR ('The level for job_id:%d should be between %d and %d.',      16, 1, @@JOB_ID, @@MIN_LVL, @@MAX_LVL)   ROLLBACK TRANSACTIONENDSQL中
  相关解决方案