【问题标题】:Getting the auto_increment value in .NET在 .NET 中获取 auto_increment 值
【发布时间】:2013-01-30 17:38:03
【问题描述】:

我对 .NET 和 SQL Server 比较陌生。我正在尝试从 .NET 执行存储过程并取回 auto_increment 值。这是我在 .NET (VB.NET) 中的代码:

myComm.Parameters.AddWithValue("@newkey", newKey)
myComm.Parameters.AddWithValue("@newimg", DirectCast(imgByteArray, Object))
Dim resultReader As SqlDataReader = myComm.ExecuteReader
Dim resultId As Integer
While resultReader.Read
     resultId = resultReader.GetInt16("@returnid")
End While

这是我的存储过程:

-- Add the parameters for the stored procedure here
@newkey nvarchar(MAX),
@newimg varbinary(MAX),
@returnid integer = 0
AS
BEGIN

SET NOCOUNT ON;

INSERT INTO dbo.AmazonS3Preview(myKey,previewImage) VALUES (@newkey,@newimg)
SET @returnid=(SELECT @@IDENTITY AS [@@IDENTITY])
END

目前在 .NET 中,resultId 总是得到“0”,谁能告诉我我做错了什么?

【问题讨论】:

  • 我还建议使用 SCOPE_IDENTITY() 而不是其他任何东西来获取新插入的标识值。 See this blog post for an explanation as to WHY
  • 您在AmazonS3Preview 表上的主键设置正确吗?
  • @@IDENTITY 也不是 O(1)。直到真正的桌子才出现。基本上没有理由不使用 SCOPE_IDENTITY()。

标签: asp.net .net sql-server vb.net tsql


【解决方案1】:

您正在设置值但没有返回它。甚至不需要设置变量。做最后一行:

SELECT SCOPE_IDENTITY() as returnid

并查看使用ExecuteScalar 获取returnId:

myComm.Parameters.AddWithValue("@newkey", newKey)
myComm.Parameters.AddWithValue("@newimg", DirectCast(imgByteArray, Object))
Dim resultId As Integer    
resultId = Convert.ToInt32(myComm.ExecuteScalar())

【讨论】:

    【解决方案2】:

    在存储过程中,您将参数 returnid 设置为该值。但是在您的代码中,您正在捕获 select 语句的输出。我会将存储过程更改为:

    -- Add the parameters for the stored procedure here
    @newkey nvarchar(MAX),
    @newimg varbinary(MAX)
    AS
    BEGIN
    
       SET NOCOUNT ON;
    
       INSERT INTO dbo.AmazonS3Preview(myKey, previewImage) 
       OUTPUT Inserted.ID 
       VALUES (@newkey, @newimg)
    END
    

    两个变化。首先,删除 returnid 参数。其次,使用SP中的Output子句取回id。这应该可以在不需要对您的 vb.net 代码进行任何更改的情况下工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2013-03-27
      • 1970-01-01
      • 2013-07-27
      相关资源
      最近更新 更多