4
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”。我怎样才能以某种聪明的方式做到这一点..?

4

1 回答 1

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
于 2012-10-24T09:41:57.287 回答