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

时间:2013-05-31 14:39:33

标签: c# sql sql-server-2008

以下代码将新记录输入表中。但是,出于某种原因,它正在拿起3126并且该ID的记录已经存在。每次运行此函数时,它都会递增1,但是在3198之前已经存在相应的id值。我将如何更改以及将进行哪些更改,以便它获取记录中已存在的最大值并递增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();
}
}
}

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

2 个答案:

答案 0 :(得分:0)

(SELECT TOP 1 id FROM <yourtable> ORDER BY id DESC) + 1

这将从表中获取最后一个最高ID,并将其递增1。您可以将其作为值放入SQL插入语句中,如下所示:

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

答案 1 :(得分:0)

您是否可以更改要使用的存储过程:

SELECT SCOPE_IDENTITY()

哪个会返回最后插入记录的id。你不能依赖id等于最大id增加1,因为id可以超时重用。

请注意,这是一个SQL Server解决方案,但在其他数据库引擎中通常有等价的。