我在asp.net和c#中创建了一个项目,我在SQL Server中一个接一个地写了10个更新查询
我在多个表上执行查询,这些表与每个表相似但不完全相似
有一些更新语句不适用于某些表,所以我想忽略该错误并执行其他查询并获得最终输出 是否有可能
如果是,请帮助我
答案 0 :(得分:0)
我会创建一个包含所有更新语句的存储过程,每个更新语句都包含在TRY..CATCH块中。
这应该是这样的:
CREATE PROCEDURE [MyProc]
AS
BEGIN
TRY
BEGIN
[STATEMENT 1]
END
CATCH
BEGIN
[DO SOMETHING... OR NOT]
END
TRY
BEGIN
[STATEMENT 2]
END
CATCH
BEGIN
[DO SOMETHING... OR NOT]
END
TRY
BEGIN
[STATEMENT 3]
END
CATCH
BEGIN
[DO SOMETHING... OR NOT]
END
(...and so on)
END
答案 1 :(得分:0)
你可以这样做,
try
{
//get values from text boxes for values you want to update in a string array queryarr
//here it has 4 fields id, name, address and tablename.
for(int i=0; i<5; i++)
{
try
{
string connectionString =
"server=myown;" +
"initial catalog=something;" +
"user id=somebody;" +
"password=secret";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE "+queryarr[i,4]+" SET Name=@NewName, Address=@NewAddress" +
" WHERE Id=@Id", conn))
{
cmd.Parameters.AddWithValue("@Id", queryarr[i,0]);
cmd.Parameters.AddWithValue("@Name", queryarr[i,1]);
cmd.Parameters.AddWithValue("@Address", queryarr[i,2]);
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Log the exception but do not display any message.
}
}
}
catch (Exception ex)
{
//display error message
}