【问题标题】:Retrieve the last id from the SQL Server database table从 SQL Server 数据库表中检索最后一个 id
【发布时间】:2026-02-01 13:20:06
【问题描述】:

如何获取策略表中创建的最后一个 id 并将其存储到一个变量中,以便我可以将它用于另一个名为 backupspec 表的表。

System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
            dataConnection.ConnectionString =
                @"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";

            System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
            dataCommand.Connection = dataConnection;

            //tell the compiler and database that we're using parameters (thus the @first, @last, @nick)  
            dataCommand.CommandText = ("Insert Policies ( PolicyName, PolicyDesc, TimeAdded,OSFlag, CreateVSSSnapshot, CreateAuditLogForRecoveries, AllowUsersToOverwriteFiles, AutoHandleEnvErrors, NotifyOnEnvErrorCount, NotifyOnFileFailure, NotifyOnFileFailureCount, NotifyOnLackOfPCContact, NotifyOnLackOfPCContactDays, NotifyOnRecoveryFailures, NotifyOnRecoveryFailureReason) values (@pn,@pd,@TimeAdded,@os,@vss,@al,@uow,@hee,@oeec,@off,@offc,@oloc,@olocd,@orf,@orfr)");




        dataCommand.Parameters.AddWithValue("@pn",pn);
        dataCommand.Parameters.AddWithValue("@pd",pd);
        dataCommand.Parameters.AddWithValue("@TimeAdded",TimeAdded);
        dataCommand.Parameters.AddWithValue("@os",os);
        dataCommand.Parameters.AddWithValue("@vss",vss);
        dataCommand.Parameters.AddWithValue("@al",al);
        dataCommand.Parameters.AddWithValue("@uow",uow);
        dataCommand.Parameters.AddWithValue("@hee",hee);
        dataCommand.Parameters.AddWithValue("@oeec",oeec);
        dataCommand.Parameters.AddWithValue("@off",off);
        dataCommand.Parameters.AddWithValue("@offc",offc);
        dataCommand.Parameters.AddWithValue("@oloc",oloc);
        dataCommand.Parameters.AddWithValue("@olocd",olocd);
        dataCommand.Parameters.AddWithValue("@orf",orf);
        dataCommand.Parameters.AddWithValue("@orfr",orfr);

        dataConnection.Open();

        dataCommand.ExecuteNonquery();


        dataConnection.Close();


        ArrayList jaja = (ArrayList)Session["BackupSpecList"];


        for (int i = 0; i < jaja.Count; i++)
        {
            BackupSpecEntry bsp = (BackupSpecEntry)jaja[i];
            string path = bsp.path;
            string inclExcl = bsp.inclExcl;
            byte inclExclFlags = bsp.inclExclFlags;
            bool indexContents = bsp.indexContents;
            int serverBackupSpecId = bsp.serverBackupSpecId;
            int freq = bsp.freq;
            int retention = bsp.retention;
            int policyID =DONT KNOW HOW TO GET THIS VALUE;
            long specChangeTime = 0;
            long backupTime = 0;

            dataCommand.CommandText = ("Insert BackupSpec (PolicyID, Path, ServerBackupSpecID, Freq, Retention, InclExclFlags, InclExcl, IndexContents, SpecChangeTime, BackupTime) values (@policyID,@path,@serverBackupSpecId,@freq,@retention,@inclExclFlags,@inclExcl,@indexContents,@specChangeTime,@backupTime)");

            dataCommand.Parameters.AddWithValue("@policyID", policyID);
            dataCommand.Parameters.AddWithValue("@path", path);
            dataCommand.Parameters.AddWithValue("@serverBackupSpecId", serverBackupSpecId);
            dataCommand.Parameters.AddWithValue("@freq", freq);
            dataCommand.Parameters.AddWithValue("@retention", retention);
            dataCommand.Parameters.AddWithValue("@inclExclFlags", inclExclFlags);
            dataCommand.Parameters.AddWithValue("@inclExcl", inclExcl);
            dataCommand.Parameters.AddWithValue("@indexContents", indexContents);
            dataCommand.Parameters.AddWithValue("@specChangeTime", specChangeTime);
            dataCommand.Parameters.AddWithValue("@backupTime", backupTime);


            dataConnection.Open();
            dataCommand.ExecuteNonQuery();
            dataConnection.Close();

        }

我收到标签 ID 错误...

有人可以帮我解决这个问题吗??

我没有得到插入后创建的最后一个 policyID 请帮助... 请帮忙

【问题讨论】:

  • 您是否首先创建了INSERT INTO Policies 来创建新的“lastid”值?在你的代码中看不到......

标签: c# asp.net visual-studio-2008 sql-server-2005 scope-identity


【解决方案1】:

使用 scope_identity:

strSQL = "INSERT INTO Policies (...) VALUES (@vals....);SELECT @result = scope_identity()"
SQLCommand.CommandText = strSQL;
SQLCommand.Parameters.Add("@result", SqlDbType.Int);
SQLCommand.ExecuteScalar();
int id = SQLCommand.Parameters["@result"].Value;

【讨论】:

  • +1,你的回答比我的好。不知道这个功能
  • 这不适用于我上面的代码我已经尝试了所有可能的方法...请帮助
【解决方案2】:

您可以使用 SCOPE_IDENTITY@@IDENTITY

SCOPE_IDENTITY:

strSQL = "INSERT INTO Policies (...) VALUES (@vals....);SELECT SCOPE_IDENTITY()";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();

@@IDENTITY:

strSQL = "INSERT INTO Policies (...) VALUES (@vals....);SELECT @@Identity";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();

对于两者之间的差异,我建议阅读此article

【讨论】:

  • 不,使用 Scope_identity() 代替。
  • 这没有得到实现......你能告诉我如何将 id 值放入变量中......那么我没有问题......
  • @erikkallen --- 你能告诉我如何使用 Scope_identity() 并将值放入变量中..??
  • 为了完整起见,您也可以包含 IDENT_CURRENT,尽管有一些警告
【解决方案3】:

如果你先调用INSERT INTO Policies(),为了得到lastid,你可以这样做:

int lastId = 0;
using(SqlConnection Connection = new SqlConnection("(connection string)"))
{
  string queryStatement = 
    "INSERT INTO dbo.Policies(fields) OUTPUT Inserted.LastID VALUES(....)";

  using(SqlCommand Command = new SqlCommand(queryStatement, Connection))
  {
     Connection.Open();
     lastId = Command.ExecuteScalar();
     Connection.Close();
  }
}

使用OUTPUT ....... 子句返回新插入的lastId

然后继续在主查询中使用该值。

马克

【讨论】:

  • 只是一个问题,最后一个 id 是否只包含我最后输入的 PolicyID 或最后插入的所有值......就像它如何从它创建的策略 id 中获取一样......我有修改了我的代码请看看..谢谢
最近更新 更多