gpt4 book ai didi

c# - SQL INSERT 奇怪地跳过第一条记录

转载 作者:行者123 更新时间:2023-11-30 13:36:27 24 4
gpt4 key购买 nike

我正在从另一个类中获取对象列表,并在我的插入查询中使用它。

不知怎么的,我得到了一个奇怪的“错误”,因为列表中的第一个对象没有被插入。

如果有人能发现我的错误,我会很高兴!一段时间以来,我一直在用头敲打键盘......

        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 位客户,我跑过他们来发现任何冲突。

我到底做错了什么?

感谢任何帮助! :)

最佳答案

您从索引 1 开始 for 循环,而 c# 是一种索引为 0 的语言。这意味着您实际上是从第二条记录开始的。

将您的 for 循环更改为:

for (int i = 0; i < customers.Count; i++)

关于c# - SQL INSERT 奇怪地跳过第一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com