删除语句有问题

时间:2011-06-30 11:32:05

标签: c# asp.net sql

public static void DeleteThreads(int threadID)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("DELETE FROM dbo.Threads");
    sb.Append(" WHERE ThreadsID=@ThreadsID");

    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();

    }
}

它给了我这个错误:

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 ThreadsID=@ThreadsID");

    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();

    }
}

6 个答案:

答案 0 :(得分:3)

您没有空格,看起来您错过了FROM关键字。

尝试:

sb.Append("DELETE FROM dbo.Threads");    
sb.Append(" WHERE ThreadsID=@ThreadsID");

此外,对于记录:由于将应用程序与数据库紧密耦合,因此使用内联SQL通常很糟糕。如果此应用程序用于任何严重目的,您应该使用单独的数据访问层。

答案 1 :(得分:2)

包含“发件人”和空格

 StringBuilder sb = new StringBuilder();
        sb.Append("DELETE from  dbo.Threads ");
        sb.Append("WHERE ThreadsID=@ThreadsID");

答案 2 :(得分:2)

你忘记在第一个语句后给空格,忘记添加FROM那个。

StringBuilder sb = new StringBuilder();
sb.Append("DELETE FROM  dbo.Threads  ");
sb.Append(" WHERE ThreadsID=@ThreadsID");

答案 3 :(得分:2)

自己构建字符串以查看错误。结果将是

DELETE dbo.ThreadsWHERE ThreadsID=@ThreadsID

您在dbo.Threads之后缺少FROM关键字和空格。

sb.Append("DELETE FROM dbo.Threads ");    
sb.Append("WHERE ThreadsID=@ThreadsID");

答案 4 :(得分:0)

应该是

DELETE FROM ......

答案 5 :(得分:0)

ThreadsID作为注释和其他表上的forign键传递,您必须删除首先与该ThreadID关联的记录。您可以从SQL Server Management Stidio在主表上设置级联删除选项。