Created
July 24, 2017 20:33
-
-
Save drewchapin/538cd740f724195952e452e26e3b2324 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static int Update( SqlConnection sql, DataTable table, string tableName = null ) | |
{ | |
int count = 0; | |
tableName = tableName ?? table.TableName; | |
if( String.IsNullOrWhiteSpace(tableName) ) throw new NullReferenceException("tableName cannot be null or empty"); | |
if( sql.State != ConnectionState.Open ) | |
sql.Open(); | |
using( SqlCommand cmd = sql.CreateCommand() ) | |
{ | |
List<string> keys = table.PrimaryKey.Select(x=>x.ColumnName).ToList(); | |
List<string> cols = table.Columns.Cast<DataColumn>().Where(x=>String.IsNullOrWhiteSpace(x.Expression)).Select(x=>x.ColumnName).ToList(); | |
string insert = String.Join(",",cols); | |
string values = String.Join(",",cols.Select(x=>String.Format("@{0}",x))); | |
string where = String.Join(" AND ",keys.Select(x=>String.Format("[{0}]=@{0}",x))); | |
string set = String.Join(",",cols.Select(x=>String.Format("[{0}]=@{0}",x))); | |
cmd.CommandText = String.Format(Properties.Settings.Default.Command,tableName,where,insert,values,set); | |
foreach( DataColumn x in table.Columns ) | |
if( String.IsNullOrWhiteSpace(x.Expression) ) | |
cmd.Parameters.Add(String.Format("@{0}",x.ColumnName),SqlDbTypeMap.Convert(x.DataType),x.MaxLength); | |
foreach( DataRow row in table.Rows ) | |
{ | |
cols.ForEach(x=>{cmd.Parameters[String.Format("@{0}",x)].Value=row[x];}); | |
Debug.WriteLine(cmd.CommandText); | |
count += cmd.ExecuteNonQuery(); | |
} | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment