我可以在INSERT期间重新使用AutoNumber值来填充另一个字段吗? C#&访问数据库

时间:2014-04-03 09:37:11

标签: c# database

我有一张componentID(AutoNumber)componentCode(string)的表,它是前缀字母和componentsndID的组合。我想获取componentID并添加前缀并将其写入componentCode

ie;
ComponentID: 123, ComponentCode: 10PT0123.
ComponentID: 124, ComponentCode: 10PT0124.
etc.

使用c#/ access数据库执行此操作的最简单方法是什么?感谢。

1 个答案:

答案 0 :(得分:1)

尤里卡!我不确定它是最简单或最优雅的解决方案,但对我有用:)

        OleDbConnection cnJetDB = new OleDbConnection(strDB);

        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = "INSERT INTO tableComponents (ComponentDesc) VALUES (@ComponentDesc)";
        cmd.Parameters.AddWithValue("@ComponentDesc", partDesc);

        cnJetDB.Open();

        cmd.Connection = cnJetDB;
        cmd.ExecuteNonQuery();

        cmd.CommandText = "SELECT @@IDENTITY";
        int newID = (int)cmd.ExecuteScalar();
        MessageBox.Show(newID.ToString());

        OleDbCommand cmd2 = new OleDbCommand();
        cmd2.CommandText = "UPDATE tableComponents SET ComponentCode=@CompCode WHERE ComponentID="+newID;
        cmd2.Parameters.AddWithValue("@CompCode", "PREFIX" + newID.ToString());

        cmd2.Connection = cnJetDB;
        cmd2.ExecuteNonQuery();

        cnJetDB.Close();