我从另一个类中获取对象列表,并在我的插入查询中使用它。
不知怎的,我得到了一个奇怪的错误",因为列表中的第一个对象没有被插入。
如果有人能发现我的错误,我真的很开心!我一直在敲击键盘一段时间......
var ActNoParam = new SqlParameter();
ActNoParam.ParameterName = "@ActNo";
ActNoParam.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(ActNoParam);
var CustNoParam = new SqlParameter();
CustNoParam.ParameterName = "@CustNo";
CustNoParam.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(CustNoParam);
var DelpriParam = new SqlParameter();
DelpriParam.ParameterName = "@DelPri";
DelpriParam.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(DelpriParam);
var CustPrg3Param = new SqlParameter();
CustPrg3Param.ParameterName = "@CustPrg3";
CustPrg3Param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(CustPrg3Param);
var NmParam = new SqlParameter();
NmParam.ParameterName = "@Nm";
NmParam.SqlDbType = SqlDbType.VarChar;
cmd.Parameters.Add(NmParam);
var Gr6Param = new SqlParameter();
Gr6Param.ParameterName = "@Gr6";
Gr6Param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(Gr6Param);
var CreUsrParam = new SqlParameter();
CreUsrParam.ParameterName = "@CreUsr";
CreUsrParam.SqlDbType = SqlDbType.VarChar;
cmd.Parameters.Add(CreUsrParam);
var CreDtParam = new SqlParameter();
CreDtParam.ParameterName = "@CreDt";
CreDtParam.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(CreDtParam);
for (int i = 1; i < customers.Count; i++)
{
cmd.CommandText =
@"IF NOT EXISTS (SELECT 1 FROM dbo.Actor WHERE DelPri = @DelPri AND CustPrg3 = @CustPrg3)
INSERT INTO dbo.Actor(ActNo, CustNo, DelPri, CustPrg3, Nm, Gr6, CreDt, CreUsr)
VALUES(@ActNo, @CustNo, @DelPri, @CustPrg3, @Nm, @Gr6, @CreDt, @CreUsr);";
ActNoParam.Value = customers[i].ActNo; // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.
CustNoParam.Value = customers[i].CustNo; // <<< THIS IS WH ERE YOUR NUMERIC VALUE GOES.
DelpriParam.Value = Int32.Parse(customers[i].DelPri); // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.
CustPrg3Param.Value = customers[i].CustPrg3; // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.
NmParam.Value = customers[i].Nm; // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.
Gr6Param.Value = customers[i].Gr6; // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.
CreDtParam.Value = customers[i].CreDt; // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.
CreUsrParam.Value = customers[i].CreUsr; // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.
cmd.ExecuteNonQuery();
}
我知道第一个对象传递给了类,我已经尝试在循环中打印出当前对象的值,所以数据就在那里,但是在插入中跳过了。
此外,我非常确定这不是由于if not exists查询,因为我只有12位客户正在检查,我将它们运行以发现任何冲突。
我到底做错了什么?
感谢任何帮助! :)
答案 0 :(得分:7)
您在索引1处开始for循环,而c#是0索引语言。这意味着您实际上是从第二条记录开始的。
将for循环更改为:
for (int i = 0; i < customers.Count; i++)
答案 1 :(得分:3)
你可以尝试/确认这些事情:
表演员有记录吗?第一条记录是否已经存在于表格中(即使用Delpri和Custprg3值)?
正如您所说,这不是因为IF NOT EXIST
,您是否可以通过删除它来尝试运行它?
您的for循环以i = 1
开头。你确定你的序列正确吗?