简体   繁体   English

我将如何获取最后一个最大记录ID,增量ID,然后将记录添加到表C#应用程序中

[英]How would I Get last max record ID,Increment ID and then add record to table C# application

The following code enters a new record into a table. 以下代码将新记录输入到表中。 However, for some reason it is picking up 3126 and a record for that ID already exists. 但是,由于某种原因,它正在接收3126,并且该ID的记录已经存在。 Every time I run this function it increments by 1 but there is already a corresponding value for the id until 3198. How would I change and what changes would I make, so that it gets the max value that already exists in the record and increments the ID by 1 and then add the record. 每次我运行此函数时,它都会增加1,但id已有一个相应的值,直到3198。我将如何更改以及将进行哪些更改,以便它获取记录中已存在的最大值并递增记录。将ID乘以1,然后添加记录。

SqlConnection conn = new SqlConnection(Properties.Settings.Default.ConnectionString);
try
{
    conn.Open();

    SqlCommand sqlCMD = new SqlCommand("InsertNewDeal", conn);

    sqlCMD.CommandType = System.Data.CommandType.StoredProcedure;
    sqlCMD.Parameters.Add("@Title", System.Data.SqlDbType.VarChar, 100);
    sqlCMD.Parameters.Add("@Office", System.Data.SqlDbType.Char, 3);
    sqlCMD.Parameters.Add("@EntryBy", System.Data.SqlDbType.VarChar, 50);
    sqlCMD.Parameters.Add("@CSR1", System.Data.SqlDbType.VarChar, 50);
    sqlCMD.Parameters.Add("@id", System.Data.SqlDbType.Int);
    sqlCMD.Parameters["@id"].Direction = System.Data.ParameterDirection.Output;


    sqlCMD.Parameters["@Title"].Value = txtName.Text;
    sqlCMD.Parameters["@Office"].Value = cmbOffice.SelectedValue;
    sqlCMD.Parameters["@CSR1"].Value = cmbCSR.SelectedValue;
    sqlCMD.Parameters["@EntryBy"].Value = LisaDatabaseManager.CurrentCSR.Username;

    CSR user = CSR.LoadCurrentUser();
    sqlCMD.ExecuteNonQuery();
    this.newProductionID = (int)sqlCMD.Parameters["@id"].Value;


    SqlCommand cmd = new SqlCommand("UPDATE Productions SET CountryCode = 'CAN', ProvinceCode = '" + user.GetProvinceCode() + "' WHERE ID = " + newProductionID, conn);
    cmd.ExecuteNonQuery();

    AddOptionalFields(newProductionID);

    LisaDatabaseManager.DealsTable.Fill(LisaDatabaseManager.DSGlobal.LoadDeals);
    DialogResult = DialogResult.OK;
    Close();
}
catch (Exception ex)
{
    ExceptionHandler.LogException("New deal", ex, LogSource.CHECK);
}
finally
{
    conn.Close();
}
}
}

The stored Procedure to InsertNewdeal is the following: InsertNewdeal的存储过程如下:

ALTER PROCEDURE [dbo].[InsertNewDeal]
    @Title varchar(100),
    @EntryBy varchar(50),
    @Office char(3),
    @CSR1 varchar(50),
    @id int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    declare @CamProb int;
    IF @PSOffice = 'VAN'
        set @CamProb = 1;
    else
        set @CamProb = NULL;

    INSERT INTO Productions(Title, EntryDate, EntryBy, Camera, Light, Grip, Generator, Expendables,IsDead, Office, CSR1, Indie,ProbCam)
        VALUES (@Title, CURRENT_TIMESTAMP, @EntryBy, 0,0,0,0,0,0, @Office, @CSR1,0,@CamProb);

    SELECT @id = Scope_Identity();

    INSERT INTO PostMortems(ProductionID,Indie) VALUES (@id,0);

    INSERT INTO Deals(Production, Date, SubRentals,InsuranceOnFile,DealOnFile, ChargeDVan, Charge5Tonne, ChargeDVan_out, Charge5Tonne_out, ChargeBulbReplacement) VALUES(@id,CURRENT_TIMESTAMP, 'Cost+10%',0,0, 75.00, 100.00, 150.00, 200.00, 1);

    DECLARE ItemCursor Cursor FOR
        select item from dealitems where id in (46048, 46052, 46036, 1, 46054, 15, 46056, 46057, 46058)
        order by
        case
            when id = 46048 then 1
            when id = 46052 then 2
            when id = 46036 then 3
            when id = 1 then 4
            when id = 46054 then 5
            when id = 15 then 6
            when id = 46056 then 7
            when id = 46057 then 8
            else 9
        end

    DECLARE @Description varchar(100)
    DECLARE @count int
    Set @count = 0

    OPEN ItemCursor

    FETCH NEXT FROM ItemCursor INTO @Description

    WHILE @@FETCH_STATUS = 0
    BEGIN
        INSERT INTO DealMemoItems(Deal, Item, Ord)
        VALUES(@id, @Description, @count)

        SET @count = (@count + 1)

        FETCH NEXT FROM ItemCursor INTO @Description
    END
    CLOSE ItemCursor
    DEALLOCATE ItemCursor
END
(SELECT TOP 1 id FROM <yourtable> ORDER BY id DESC) + 1

This gets the last highest ID from the table, and increments it by one. 这将从表中获得最后的最高ID,并将其递增1。 You can put it right into your SQL insert statement, as a value, like below: 您可以将其作为值直接放入SQL插入语句中,如下所示:

INSERT INTO <YOURTABLE> (id, name)
values (
     (SELECT TOP 1 id FROM <yourtable> ORDER BY id DESC) + 1,
     'Goober fish'
);

Could you not change your stored procedure to use: 您是否可以更改存储过程以使用:

SELECT SCOPE_IDENTITY()

Which would return the id of the last inserted record. 这将返回最后插入的记录的ID。 You cannot rely on the id being equal to the largest id incremented by one, as ids can be reused overtime. 您不能依赖于等于最大ID乘以1的ID,因为ID可以超时使用。

Note this is a SQL Server solution, but there are usually equivalents in other database engines. 请注意,这是一个SQL Server解决方案,但是其他数据库引擎中通常也有等效项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM