如何获取 SQL Server 2005 和 ASP 中使用的下一个标识号?

发布于 2024-07-09 07:13:26 字数 570 浏览 14 评论 0原文

我之前通过执行一个简单的查询来获取 Access 中使用的下一个可用自动编号,如下所示:

SELECT RecordNumber, Info 
FROM myTABLE 
WHERE 0 = 1

我可以创建一个变量来保存 currentRecord,它将使用与我更新行时 Access 将使用的相同自动编号

这样

rs.AddNew
currentRecord = rs("RecordNumber")

rsInfo = "SomeFormData" & currentRecord
rs.Update
rs.Close

现在,它可以在 MS Access 上工作,但在 SQL Server 2005 中,我无法取回新记录创建的身份。 “SomeFormData”已正确插入,SQL 中的 RecordNumber 字段已由新的自动编号填充,但我的变量中没有 RecordNumber,我需要它继续填写相关表单,将数据保存到相关表并需要保存当前记录号。

问题:有没有办法在进行新插入时取回这个唯一的编号?

I was previously getting the next available autonumber used in Access by doing a simple query like so:

SELECT RecordNumber, Info 
FROM myTABLE 
WHERE 0 = 1

This way I could create a variable to hold the currentRecord and it will use the same autonumber that Access was going to use when I was updating the row

Example

rs.AddNew
currentRecord = rs("RecordNumber")

rsInfo = "SomeFormData" & currentRecord
rs.Update
rs.Close

Now this use to work on MS Access, but in SQL Server 2005, I am not getting back the Identity created by the new record. "SomeFormData" is been inserted correctly, the RecordNumber field in SQL is been populated by the new auto number but I don't have the RecordNumber in my variables and I need it to continue filling related forms, that save data to related tables and need to save the currentRecord number.

Question: is there a way to get this unique number back when doing a new insert?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

帅气称霸 2024-07-16 07:13:26

IDENT_CURRENT('tableName')(包括单引号)返回给定表的当前标识值。 该值应该是表中使用的最后分配的标识值。 换句话说,表中已存在具有此标识值的行,除非该行已被删除。 将在下一个 INSERT 上分配的标识值将为 IDENT_CURRENT('tableName') + IDENT_INCR('tableName')

不过,我不建议依赖于此。 如果您以这种方式预先确定下一个标识值,那么您必然会遇到这样的情况:另一个进程在您之前执行插入操作,实际上会先获取该 ID,因此您的进程最终会使用错误的 ID 值。

最好先进行插入(即使您还没有所有数据),然后使用 SCOPE_IDENTITY() 来获取分配的实际 ID。

您可能想知道为什么 SCOPE_IDENTITY()IDENT_CURRENT('tableName') 更好。 顾名思义,前者将为您提供在当前范围(您的批次、存储过程等)内分配的最新身份值,而后者将为您提供任何人在表上分配的最新身份。 即使您可能在“INSERT”之后立即调用 IDENT_CURRENT,但仍有可能其他人的 INSERT 发生在两者之间,并且 IDENT_CURRENT code> 将为您提供由他们插入而不是您的插入产生的身份值,而 SCOPE_IDENTITY 将始终为您提供您的身份值。

编辑

还值得一提的是,SCOPE_IDENTITY() 比功能类似的 @@IDENTITY 更受欢迎。 虽然两者都返回当前批次中分配的最新标识值,但 @@IDENTITY 会受到触发器内发生的插入的影响; SCOPE_IDENTITY() 不是。

IDENT_CURRENT('tableName') (include the single quotes) returns the current value of the identity for the given table. This value should be the last-assigned identity value used in the table. In other words, you will have a row with this identity value already in the table, unless that row has been deleted. The identity value that will be assigned on the next INSERT will be IDENT_CURRENT('tableName') + IDENT_INCR('tableName').

I don't recommend relying on this, though. If you pre-determine the next identity value this way, you're bound to end up in a situation where another process makes the insert that actually gets that ID before yours does, so your process ends up using the wrong ID value.

It's much better to make your insert first (even if you don't have all the data yet), and use SCOPE_IDENTITY() to get the actual ID assigned.

You might wonder why SCOPE_IDENTITY() is better than IDENT_CURRENT('tableName'). As the name implies, the former will give you that most recent identity value assigned within your current scope (your batch, your stored proc, whatever), whereas the latter will give you the most recent identity assigned on the table, by anyone. Even though you might call IDENT_CURRENT right after 'INSERT, it's still possible that someone else's INSERT occurs in between, and IDENT_CURRENT will give you the identity value that resulted from their insert instead of yours, whereas SCOPE_IDENTITY will always give you yours.

EDIT:

It's also worth mentioning that SCOPE_IDENTITY() is favored over the similarly-functioning @@IDENTITY. While both return the latest identity value assigned within the current batch, @@IDENTITY is affected by inserts that occur within triggers; SCOPE_IDENTITY() is not.

奶茶白久 2024-07-16 07:13:26

选择 CAST(Scope_Identity() AS INT)

SELECT CAST(Scope_Identity() AS INT)

白色秋天 2024-07-16 07:13:26

我知道这个问题很老了......但是您可以通过使用输出参数来获取插入的记录 ID。

这是我的存储过程的示例

IF object_id('spOrganizationAdd') IS NOT NULL
    DROP PROCEDURE spOrganizationAdd;
GO

CREATE PROCEDURE dbo.spOrganizationAdd
    @OrganizationName VARCHAR(50),
    @ReturnIdentityValue INT OUTPUT
AS
BEGIN
    DECLARE @TempOrganizationIdentity TABLE (TempOrganizationID INT)

    INSERT INTO Organization (OrganizationName)
    OUTPUT INSERTED.OrganizationID INTO @TempOrganizationIdentity
    VALUES (@OrganizationName)

    SELECT @ReturnIdentityValue = (SElECT TempOrganizationID FROM @TempOrganizationIdentity)
END
GO

这里是调用它的 C# 代码的示例...注意 ParameterDirection.Output

public static int AddOrganization(Organization oOrganization)
{
    int iRetVal = 0;

    using (SqlConnection conn = Connection.GetConnection())
    {
        using (SqlCommand cmd = new SqlCommand("spOrganizationAdd", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@OrganizationName", oOrganization.OrganizationName);
            cmd.Parameters.Add("@ReturnIdentityValue", SqlDbType.Int).Direction = ParameterDirection.Output;

            conn.Open();
            cmd.ExecuteNonQuery();
            iRetVal = Convert.ToInt32(cmd.Parameters["@ReturnIdentityValue"].Value);
        }
    }

    return iRetVal;
}

类示例

public class Organization
{
    public Organization() { }
    public Organization(int organizationID) { OrganizationID = organizationID; }

    public int OrganizationID { get; set; }
    public string OrganizationName { get; set; }

    public string Display()
    {
        return OrganizationID.ToString() + " " + OrganizationName;
    }
}

I know this question is old...but you can get the inserted records ID by using an output parameter.

Here an example of a stored procedure I have

IF object_id('spOrganizationAdd') IS NOT NULL
    DROP PROCEDURE spOrganizationAdd;
GO

CREATE PROCEDURE dbo.spOrganizationAdd
    @OrganizationName VARCHAR(50),
    @ReturnIdentityValue INT OUTPUT
AS
BEGIN
    DECLARE @TempOrganizationIdentity TABLE (TempOrganizationID INT)

    INSERT INTO Organization (OrganizationName)
    OUTPUT INSERTED.OrganizationID INTO @TempOrganizationIdentity
    VALUES (@OrganizationName)

    SELECT @ReturnIdentityValue = (SElECT TempOrganizationID FROM @TempOrganizationIdentity)
END
GO

Here an example of the C# code that calls it...note ParameterDirection.Output:

public static int AddOrganization(Organization oOrganization)
{
    int iRetVal = 0;

    using (SqlConnection conn = Connection.GetConnection())
    {
        using (SqlCommand cmd = new SqlCommand("spOrganizationAdd", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@OrganizationName", oOrganization.OrganizationName);
            cmd.Parameters.Add("@ReturnIdentityValue", SqlDbType.Int).Direction = ParameterDirection.Output;

            conn.Open();
            cmd.ExecuteNonQuery();
            iRetVal = Convert.ToInt32(cmd.Parameters["@ReturnIdentityValue"].Value);
        }
    }

    return iRetVal;
}

Class example

public class Organization
{
    public Organization() { }
    public Organization(int organizationID) { OrganizationID = organizationID; }

    public int OrganizationID { get; set; }
    public string OrganizationName { get; set; }

    public string Display()
    {
        return OrganizationID.ToString() + " " + OrganizationName;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文