2011-06-30 114 views
1
public static void DeleteThreads(int threadID) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append("DELETE FROM dbo.Threads"); 
    sb.Append(" WHERE [email protected]"); 

    string myConnectionString = AllQuestionsPresented.connectionString; 

    using (SqlConnection myConnection = new SqlConnection(myConnectionString)) 
    { 
     myConnection.Open(); 
     SqlCommand sqlCommand = new SqlCommand(sb.ToString(), myConnection); 
     sqlCommand.Parameters.Add("@ThreadsID", SqlDbType.Int); 
     sqlCommand.Parameters["@ThreadsID"].Value = threadID; 
     sqlCommand.ExecuteNonQuery(); 

    } 
} 

它給了我這個錯誤:問題用delete語句

The DELETE statement conflicted with the REFERENCE constraint "FK_Comments_Threads". The conflict occurred in database "model", table "dbo.Comments", column 'ThreadsID'. 

該語句已終止。

如果這種修復的錯誤:

enter code here public static void DeleteComments(int threadID) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append("DELETE FROM dbo.Comments"); 
    sb.Append(" WHERE [email protected]"); 

    string myConnectionString = AllQuestionsPresented.connectionString; 

    using (SqlConnection myConnection = new SqlConnection(myConnectionString)) 
    { 
     myConnection.Open(); 
     SqlCommand sqlCommand = new SqlCommand(sb.ToString(), myConnection); 
     sqlCommand.Parameters.Add("@ThreadsID", SqlDbType.Int); 
     sqlCommand.Parameters["@ThreadsID"].Value = threadID; 
     sqlCommand.ExecuteNonQuery(); 

    } 
} 
+0

你正在使用哪些DBMS? –

+1

是不是錯過了「dbo.Threads」和「WHERE」之間的空格? – Jacob

+0

全部問題已更新 –

回答

3

您沒有空間,看起來好像缺少FROM關鍵字。

嘗試:

sb.Append("DELETE FROM dbo.Threads");  
sb.Append(" WHERE [email protected]"); 

而且,備案:使用嵌入式SQL是普遍不好,由於您的應用程序緊密耦合到您的數據庫。如果此應用程序用於任何嚴肅的目的,您應該使用單獨的數據訪問層。

+0

FROM不是必需的,但是關鍵字和標識符之間的空格是。 –

+0

查看回答更新 –

+0

@ypercube - 夠公平的。我一直使用「FROM」,所以我必須說服自己,在某些時候它不是可選的。 –

0

它應該是

DELETE FROM ...... 
+0

我看到一些代碼,不使用word .. –

2

包括 「從」 航天

StringBuilder sb = new StringBuilder(); 
     sb.Append("DELETE from dbo.Threads "); 
     sb.Append("WHERE [email protected]"); 
2

你忘了第一條語句後,得到的空間和忘記添加它即可。

StringBuilder sb = new StringBuilder(); 
sb.Append("DELETE FROM dbo.Threads "); 
sb.Append(" WHERE [email protected]"); 
+0

他已經在使用參數。 –

+0

你錯過了'FROM'關鍵字。 –

+0

嘿已經包括2分鐘回來,現在我已經highlited在回答也 –

2

只是自己建立字符串,看看有什麼不對。其結果將是

DELETE dbo.ThreadsWHERE [email protected] 

你缺少FROM關鍵字和dbo.Threads後的空間。

sb.Append("DELETE FROM dbo.Threads ");  
sb.Append("WHERE [email protected]"); 
0

ThreadsID作爲註釋和其他表上的forign鍵傳遞,您必須刪除與該ThreadID首先關聯的那些記錄。您可以在SQL Server Management Stidio的主表上設置級聯刪除選項。