更新SQL Server数据库数据

 static void UpdateFilingToTable()
        {
            if (Filings.Count > 0)
            {
                string server = ConfigurationManager.AppSettings["SqlServer"].ToString();
                string database = ConfigurationManager.AppSettings["SqlDatabase"].ToString();
                string uid = ConfigurationManager.AppSettings["SqlUserID"].ToString();
                string pwd =  string uid = ConfigurationManager.AppSettings["Password"].ToString();

                string connectionString = @"server=" + server + ";database=" + database + ";uid=" + uid + ";pwd=" + pwd;

                //存在按条件更新不存在就新增                
                string updateString = "if exists(select 1 from [Eform_Data_Output].[dbo].[SP_Filing] where ReportID=@ReportID)"
                                    + " UPDATE [Eform_Data_Output].[dbo].[SP_Filing] SET ReportKey=@ReportKey,ReportName=@ReportName,EmployeeID=@EmployeeID,EmployeeName=@EmployeeName output '1' WHERE ReportID=@ReportID and (ReportKey!=@ReportKey or Status!=@Status)"
                                    + " else"
                                    + " Insert Into [Eform_Data_Output].[dbo].[SP_Filing] (ReportID,ReportKey,ReportName,EmployeeID,EmployeeName) output '2' Values(@ReportID,@ReportKey,@ReportName,@EmployeeID,@EmployeeName)";
                try
                {
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        SqlCommand command = new SqlCommand();
                        connection.Open();
                        foreach (var filing in Filings)
                        {
                            try
                            {
                                command = new SqlCommand(updateString, connection);
                                command.Parameters.AddWithValue("@ReportID", filing.ReportID);
                                command.Parameters.AddWithValue("@ReportKey", filing.ReportKey);
                                command.Parameters.AddWithValue("@ReportName", filing.ReportName);
                                command.Parameters.AddWithValue("@EmployeeID", filing.EmployeeID);
                                command.Parameters.AddWithValue("@EmployeeName", filing.EmployeeName);
                                command.ExecuteScalar();
                            }
                            catch (Exception ex)
                            {
                                Log("InsertError- ItemID:" + filing.ReportID, ex);
                            }
                        }

                        connection.Close();
                    }
                }
                catch (Exception ex)
                {
                    Log("Connect SQL Error:", ex);
                }
            }
        }
原文地址:https://www.cnblogs.com/learning-life/p/10722987.html