繁体   English   中英

在插入时从SQL Server获取SCOPE_IDENTITY

[英]Getting SCOPE_IDENTITY from SQL Server on Insert

我想为时已晚,我太累了,看不到我在做什么错。 这是我正在尝试的:

int imageId = imageDal.AddImage(new SqlParameter[]
        {
            new SqlParameter("@IMAGE_ID", 
        SqlDbType.Int, Int32.MaxValue, ParameterDirection.Output,
        true, 0, 0,"IMAGE_ID", DataRowVersion.Current,DBNull.Value),

        new SqlParameter("@IMAGE", 
        SqlDbType.Image, 11, ParameterDirection.Input,
        true, 0, 0,"IMAGE", DataRowVersion.Current,image)
        });

public int AddImage(SqlParameter[] spParams)
{
    SqlHelper.ExecuteNonQuery(BaseDAL.ConnectionStringImages, INSERT_IMAGE_SQL, spParams);
    return Convert.ToInt32(spParams[0].Value);
}

存储过程:

[dbo].[sp_insert_image]
    -- Add the parameters for the stored procedure here
    @IMAGE_ID int OUT,
    @IMAGE image
AS
BEGIN
    INSERT INTO images
    (IMAGE)
    VALUES
    (@IMAGE)
    SELECT @IMAGE_ID = SCOPE_IDENTITY();
END
GO

我将DBNull作为spParams [0] .Value获得。 我已经尝试在存储过程中将@IMAGE_ID的值设置为常量,但是它没有任何改变,因此问题出在我的存储过程中(这就是我的想法)。

当我从sql Management Studio执行该过程时,我看到了insert_id返回。

我结束了SCOPE_IDENTITY()并直接从SP返回SCOPE_IDENTITY()

如果还有另一种方法可以从sqlparameter中获取值,那么我很乐意听到。

我想,问题出在ExecuteNonQuery方法中。 它返回对象数组,而不是sqlparam的数组。

只需在输出sqlparam对象上获得一个引用,并从该引用获取值。

祝好运!

PS还有另一种解决方案。 检查链接

http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-distributed-apps/160/Data-Access-Application-Block-Output-Parameters

你把这样...

[dbo].[sp_insert_image]
    -- Add the parameters for the stored procedure here
    @IMAGE_ID int OUT,
    @IMAGE image
AS
BEGIN
    INSERT INTO images (IMAGE) VALUES (@IMAGE)
    SET @IMAGE_ID  = SCOPE_IDENTITY();
END
GO

暂无
暂无

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

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