I am analyse and making windows service application.
When I make Insert query, I add the columns using List<SqlParameter>
and AddRange.
In List<SqlParameter> pmlist = new List<SqlParameter>(keys);
line, it contains {@DeptCode}.
Then pmlist.AddRange(pms);
line, pms parameters added.
Bus I mentioned earlier pmslist already has {@DeptCode}
, so pmlist have a value like this
pmlist = [0] {@DeptCode} [1] {@DeptCode} [2] {@DeptName}
[3] {@ParentDeptName} [4] {@ParentDeptCode} [5] {@DeptLevel}
DeptCode is duplicated. So, it tries to insert query to ShadowDeptTable,
it also has 5 columns, Sql Exception was occurred.
How can I remove or not to get duplicate value? Please help me...
code is below.
//table : ShadowDeptTable , keys = {@DeptCode},
//pms = [0] {@DeptCode} [1] {@DeptName} [2] {@ParentDeptName}
// [3] {@ParentDeptCode} [4] {@DeptLevel}
public static int InsertOrUpdate(string table, SqlParameter[] keys, params SqlParameter[] pms)
{
int st = 0;
string constr = Util.GetPropVal(Words.PropConnectionString);
var obj = SqlHelper.ExecuteScalar(constr,CommandType.Text,sb.ToString(),keys);
StringBuilder sb=new StringBuilder();
sb = sb.Append("insert into " + table + "(");
//columns
string cols = null;
//values
string vals = null;
List<SqlParameter> pmlist = new List<SqlParameter>(keys);
pmlist.AddRange(pms);
cols = string.Join(",", pmlist.Select(a => "["+a.ParameterName.Substring(1, a.ParameterName.Length-1)+"]"));
vals = string.Join(",", pmlist.Select(a => "'" + a.Value + "'"));
sb = sb.Append(cols);
sb = sb.Append(") values(");
sb = sb.Append(vals);
sb = sb.Append(")");
obj = SqlHelper.ExecuteScalar(constr, CommandType.Text, sb.ToString());
return Convert.ToInt32(obj);
}