我正在尝试通过我的c#代码处理UPDATE语句。我使用以下内容......
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
cmd.Parameters.AddWithValue("@CUSTOMER", intCustomer);
cmd.Parameters.AddWithValue("@CONDITION", strCondition);
cmd.Parameters.AddWithValue("@BOOK", strBook);
cmd.Parameters.AddWithValue("@PAGE", strPage);
cmd.Parameters.AddWithValue("@ENDPAGE", strEndPage);
System.Diagnostics.Debug.WriteLine("Expanded query: " +
query.ExpandSqlQuery(cmd.Parameters));
int affectedRows = cmd.ExecuteNonQuery();
System.Diagnostics.Debug.WriteLine("Number of rows affected: " + affectedRows);
}
我尝试使用和不使用params进行调试,并且由于某种原因总是得到0
的返回值。
我做了一个小扩展方法,扩展了params以显示实际查询(没有变量)......
public static string ExpandSqlQuery(this String input, SqlParameterCollection sqlParams)
{
string results = input;
foreach (SqlParameter p in sqlParams)
results = results.Replace(p.ParameterName, p.Value.ToString());
return results;
}
...我在执行查询之前调用它以查看将要运行的内容。
System.Diagnostics.Debug.WriteLine("Expanded query: " +
query.ExpandSqlQuery(cmd.Parameters));
然后,我接受了在c#中返回0个受影响的行的SAME EXACT查询,并在Microsoft SQL Server Management Studio
中手动运行它以告诉我1
行受到影响!
使用params的查询是......
UPDATE
BookList
SET
Overdue=2
WHERE
Customer=@CUSTOMER
and Condition='@CONDITION'
and Book='@BOOK'
and Page='@PAGE'
and EndPage='@ENDPAGE'
and Overdue=1;
UPDATE
BookInfo
SET
Finished=0
WHERE
Customer=@CUSTOMER
and Condition='@CONDITION'
and Book='@BOOK';
扩展的查询是......
UPDATE
BookList
SET
Overdue=2
WHERE
Customer=85
and Condition='old'
and Book='00103'
and Page='00304'
and EndPage='00304'
and Overdue=1;
UPDATE
BookInfo
SET
Finished=0
WHERE
Customer=85
and Condition='old'
and Book='00103';
我有什么想法可以调试这个问题吗?
答案 0 :(得分:2)
您不得在参数周围加上引号。因此:
UPDATE
BookList
SET
Overdue=2
WHERE
Customer=@CUSTOMER
and Condition='@CONDITION'
and Book='@BOOK'
and Page='@PAGE'
and EndPage='@ENDPAGE'
and Overdue=1;
UPDATE
BookInfo
SET
Finished=0
WHERE
Customer=@CUSTOMER
and Condition='@CONDITION'
and Book='@BOOK';
应改为:
UPDATE
BookList
SET
Overdue=2
WHERE
Customer=@CUSTOMER
and Condition=@CONDITION
and Book=@BOOK
and Page=@PAGE
and EndPage=@ENDPAGE
and Overdue=1;
UPDATE
BookInfo
SET
Finished=0
WHERE
Customer=@CUSTOMER
and Condition=@CONDITION
and Book=@BOOK;