在SqlServer 2008R2上使用Try / Catch,是否有一些技巧可以从导致错误的行中获取一些信息?例如,
BEGIN TRY
INSERT INTO MyTable
SELECT *
FROM @MyTableVar
END TRY
BEGIN CATCH
-- In here, is there some way to know, for example, MyTable.SomeColumn for the offending row?
END CATCH
答案 0 :(得分:0)
这就是我最终做的事情:
DECLARE @MyResults TABLE (
Id INT IDENTITY( 1, 1 )
TheKey VARCHAR(20),
Success BIT
)
-- Initially set Success to 1 for all rows
INSERT INTO @MyResults
SELECT TheKey, 1
FROM @MyTableVar
DECLARE @CurrentKey VARCHAR(20)
DECLARE @CurrentId INT
DECLARE incoming CURSOR FOR SELECT Id, TheKey FROM @MyResults
OPEN incoming
FETCH incoming into @Id, @CurrentKey
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
INSERT INTO OfficialTable
SELECT *
FROM @MyTableVar TV
WHERE TV.TheKey = @CurrentKey
END TRY
BEGIN CATCH
-- On any failure, update the proper row in @MyResults
UPDATE @MyResults
SET Success = 0
WHERE TheKey = @CurrentKey AND Id = @CurrentId
END CATCH
FETCH NEXT FROM incoming INTO @Id, @CurrentKey
END
CLOSE incoming
SELECT * FROM @MyResults
在CATCH中,我知道@MyTableVar的关键,所以,我应该能够查找我需要的任何内容。