簡體   English   中英

從SQL Server數據庫表中檢索最后一個ID

[英]Retrieve the last id from the SQL Server database table

如何獲取在策略表中創建的最后一個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,請幫助...請幫助

使用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;

您可以使用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();

對於兩者之間的差異,我建議閱讀本文

如果首先執行INSERT INTO Policies()調用, lastid獲取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

然后繼續在主要查詢中使用該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM