在SQL中执行多个Update语句,忽略某些查询中的错误
本文关键字:错误 查询 语句 执行 SQL Update | 更新日期: 2023-09-27 18:08:21
我在asp.net和c#中创建了一个项目,我在SQL Server中一个接一个地编写了10个更新查询
我在多个表上执行查询每个表相似但不完全相似
有一些更新语句不适用于某些表,所以我想忽略该错误并执行其他查询并获得最终输出
我将创建一个包含所有更新语句的存储过程,每个语句都包含在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
你可以这样做,
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
}