确定在SQL中导致约束违规的值/列?

时间:2012-10-24 05:58:26

标签: sql sql-server sql-server-2008

DECLARE @temp AS TABLE (id INT NOT NULL PRIMARY KEY CLUSTERED, name VARCHAR(10))
BEGIN TRY
declare @Source table (id int not null, name varchar(10))
insert @Source
    SELECT 11,'ABC' union all
    SELECT 12,'CDE' union all
    SELECT 13,'FGH' union all
    SELECT 11,'IJK'

INSERT INTO @temp
SELECT * from @Source
SELECT * FROM @temp

END TRY
BEGIN CATCH
 EXEC msdb.dbo.sp_send_dbmail
 @profile_name = 'Profile Name', 
 @recipients = 'email@email.com', 
 @body = Error_Message, 
 @subject = Error_Message ; 
END CATCH;
GO

这是我的代码工作正常..但我想要包含在邮件中的是ID,这导致错误作为某些电子邮件ID的提醒,在这种情况下它是“11”。 我怎么能以聪明的方式做到这一点..?

1 个答案:

答案 0 :(得分:3)

正如Martin评论的那样,2008 SP3以后显示了重复的键值 对于早期版本,您必须检测可能的主键冲突并自行引发错误,例如为您的具体示例

DECLARE @temp AS TABLE (id INT NOT NULL PRIMARY KEY CLUSTERED, name VARCHAR(10))
BEGIN TRY
declare @Source table (id int not null, name varchar(10))
insert @Source
    SELECT 11,'ABC' union all
    SELECT 12,'CDE' union all
    SELECT 13,'FGH' union all
    SELECT 11,'IJK'

declare @duplicate_key nvarchar(1000);
SELECT TOP(1) @duplicate_key = ID
FROM @Source
GROUP BY ID
HAVING COUNT(*) > 1;
if @duplicate_key is not null
begin
  set @duplicate_key = 
    'Violation of PRIMARY KEY constraint. '+
    'Cannot insert duplicate key in object ''dbo.@temp''. '+
    'The duplicate key value is (' + right(@duplicate_key,10) + ')';
  RAISERROR(@duplicate_key,
            16,
            1);
end;

INSERT INTO @temp
SELECT * from @Source

SELECT * FROM @temp

END TRY
BEGIN CATCH
 select Error_Message() ; 
END CATCH;
GO