日期:2014-05-18  浏览次数:20577 次

怎样捕获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_insupd
ON employee
FOR INSERT, UPDATE
AS
/* 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 smallint
SELECT @@MIN_LVl = min_lvl, 
   @@MAX_LV = max_lvl, 
   @@ EMP_LVL = i.job_lvl,
   @@JOB_ID = i.job_id
FROM employee e, jobs j, inserted i 
WHERE e.emp_id = i.emp_id AND i.job_id = j.job_id
IF (@@JOB_ID = 1) and (@@EMP_lVl <> 10) 
BEGIN
   RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)
   ROLLBACK TRANSACTION
END
ELSE
IF 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 TRANSACTION
END


SQL中