Select Cast (Scope_identity) and executescalar

本文关键字:and executescalar identity Cast Scope Select | 更新日期: 2023-09-27 18:14:46

为什么不行?我得到一个错误,说这个数不可能是无穷大。然而,我不得不从插入语句中去掉这一点,这样它就不会两次发布条目。我必须在哪里合并这段代码,让它允许我的代码循环作为一个新的ID?

            cmd = new SqlCommand(@"SELECT CAST(scope_identity() as int)", con);
            int aID = Convert.ToInt32(cmd.ExecuteScalar());

Select Cast (Scope_identity) and executescalar

一般来说,您可以使用一个存储过程来执行INSERT并返回带有out参数的最后插入的标识,如下面的示例所示:http://www.objectreference.net/post/SCOPE_IDENTITY()-return-the-id-from-the-database-on-insert.aspx

CREATE PROCEDURE [dbo].[Customer_Insert]
    @Name VARCHAR(255),
    @Email VARCHAR(255),
    @Phone VARCHAR(255),
    @CustomerID INT OUTPUT
AS
BEGIN
    INSERT INTO dbo.Customer ([Name], Email, Phone)
    VALUES (@Name,@Email,@Phone)
    SET @CustomerID = CAST(SCOPE_IDENTITY() AS INT)
END