Skip to content

Instantly share code, notes, and snippets.

@hoangnl
Created December 7, 2016 23:41
Show Gist options
  • Save hoangnl/bd51c78a964e5cc5a257eeed9d3335b2 to your computer and use it in GitHub Desktop.
Save hoangnl/bd51c78a964e5cc5a257eeed9d3335b2 to your computer and use it in GitHub Desktop.
Update
public static string ToDynamicUpdate(this DataRow dr, string tableName, string primaryKeyField, string primaryKeyValue)
{
var command = @"DECLARE
{3}
BEGIN
{4}
UPDATE {0} SET {1} WHERE {2};
END;";
var valueList = new List<string>();
var declareCommand = string.Empty;
var setCommand = string.Empty;
foreach (var item in dr.Table.Columns.Cast<DataColumn>())
{
if (dr[item] == DBNull.Value)
{
valueList.Add((item.ToString()).ConvertToStandardName() + "= NULL");
}
else
{
if (item.DataType == typeof(int))
{
valueList.Add((item.ToString()).ConvertToStandardName() + "= " + dr[item].ToString());
}
else if (item.DataType == typeof(bool))
{
valueList.Add((item.ToString()).ConvertToStandardName() + "= " + (dr[item] == Boolean.FalseString ? "0" : "1"));
}
else if (item.DataType == typeof(DateTime))
{
valueList.Add((item.ToString()).ConvertToStandardName() + "= " + String.Format("TO_DATE('{0}', 'MM/DD/YYYY HH:MI:SS AM')", dr[item]));
}
else if (item.DataType == typeof(Guid))
{
valueList.Add((item.ToString()).ConvertToStandardName() + "= '" + (dr[item].ToString()).ToUpper() + "'");
}
else if (item.DataType == typeof(byte[]))
{
var hex = Utility.ConvertByteArrayToString(((byte[])dr[item]));
declareCommand += String.Format("p{0} RAW(100000); ", item.ToString());
setCommand += String.Format("p{0} := hextoraw('{1}');", item.ToString(), hex);
valueList.Add(String.Format("{0} = p{1}", (item.ToString()).ConvertToStandardName(), item.ToString()));
}
else
{
var tmp = dr[item].ToString();
if (tmp.Length > 2000)
{
declareCommand += String.Format("p{0} varchar2(32767); ", item.ToString());
setCommand += String.Format("p{0} := {1};", item.ToString(), tmp.ConvertToSafeString());
valueList.Add(String.Format("{0} = p{1}", (item.ToString()).ConvertToStandardName(), item.ToString()));
}
else
{
valueList.Add((item.ToString()).ConvertToStandardName() + "= " + (dr[item].ToString()).ConvertToSafeString());
}
}
}
}
var condition = CreateCondition(primaryKeyField, primaryKeyValue, ChangeType.UPDATED);
return String.Format(command, tableName.ConvertToStandardName(), String.Join(",", valueList), condition, declareCommand, setCommand);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment