2016-05-26 55 views
0

我有一個try...catchINSERT一張表。事情是這樣的:查看哪一行導致「INSERT語句與FOREIGN KEY衝突」?

try 
{ 
    sqlCommand.ExecuteNonQuery(conn, CommandType.Text, insertSql); 
} 
catch (Exception ex) 
{ 
    throw ex; 
} 

在我插入多行之一,有一個失敗,錯誤INSERT語句衝突與外鍵。

這很好,但可以返回更多信息嗎?Exception?也許它可以返回插入失敗的值?

據我所知,這可以做很多方法;我只想知道是否可以在不改變結構或stored procedure調用(即添加OUTPUT參數)和try...catch的情況下獲得有關違規行的一些信息。

再次感謝。

回答

0
try 
{ 
    sqlCommand.ExecuteNonQuery(conn, CommandType.Text, insertSql); 
} 
catch (Exception ex) 
{ 
    throw new Exception(insertSql + Environment.NewLine + ex.ToString()); 
} 
+0

這真的是最實用的解決方案。謝謝。 – rbhat

0

請嘗試以下操作。

BEGIN TRY 
     BEGIN 
     --Do your update here 
      SELECT @@ROWCOUNT 
      END 
    END TRY 
     BEGIN CATCH 
      BEGIN 
        DECLARE @ErrorMessage NVARCHAR(4000); 
        DECLARE @ErrorSeverity INT; 
        DECLARE @ErrorState INT; 

        SELECT 
         @ErrorMessage = ERROR_MESSAGE(), 
         @ErrorSeverity = ERROR_SEVERITY(), 
         @ErrorState = ERROR_STATE(); 

        RAISERROR (@ErrorMessage, -- Message text. 
           @ErrorSeverity, -- Severity. 
           @ErrorState -- State. 
           ); 
      END 
      END CATCH; 
0

嘗試 - 抓住是好的,但還不夠。你需要找到冒犯行。

begin try 
insert... 
select... 
end try 
begin catch 
declare @badFK nvarchar(max) 
select @badFK = (select fk_field from fk_table f 
left join pk_table p on p.pk_field = f.fk_field 
where p.pk_field is null 
for xml auto,elements,root) 
--raiserror as @vasmi recommend but include @badFK into message 
end catch 
0

你沒看到任何關於C#,但我想,你使用它。

在C#中,你可以使用這個:

try 
{ 
// bla bla bla 
} 
catch (SqlException ex) 
{ 
MessageBox.Show(es.ToString()); 
} 

此錯誤將繼續什麼樣的錯誤的是(也許一個主鍵複製,等等,等等)

+0

在這種情況下,'SqlException'將返回與'Exception'相同的錯誤,所以這不起作用。 – rbhat

相關問題