Asp.net 在.NET中获取自动增量值

Asp.net 在.NET中获取自动增量值,asp.net,.net,sql-server,vb.net,tsql,Asp.net,.net,Sql Server,Vb.net,Tsql,我对.NET和SQL Server比较陌生。我正在尝试从.NET执行一个存储过程,并获取自动增量值。这是我在.NET(VB.NET)中的代码: 这是我的存储过程: -- 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.Amaz

我对.NET和SQL Server比较陌生。我正在尝试从.NET执行一个存储过程,并获取自动增量值。这是我在.NET(VB.NET)中的代码:

这是我的存储过程:

-- 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”,有人能告诉我我做错了什么吗?

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

SELECT SCOPE_IDENTITY() as returnid
并查看如何使用获取returnId:

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

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

SELECT SCOPE_IDENTITY() as returnid
并查看如何使用获取returnId:

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

在存储过程中,将参数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代码进行任何更改的情况下工作

在存储过程中,将参数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代码进行任何更改的情况下工作

我还建议使用
SCOPE\u IDENTITY()
而不是其他任何东西来获取新插入的标识值。您在
AmazonS3Preview
表上有主键设置是否正确?@@IDENTITY也不是O(1)。直到真正的桌子才出现。基本上没有理由不使用SCOPE_IDENTITY()。我还建议使用
SCOPE_IDENTITY()
而不是其他任何东西来获取新插入的标识值。您在
AmazonS3Preview
表上有主键设置是否正确?@@IDENTITY也不是O(1)。直到真正的桌子才出现。基本上没有理由不使用SCOPE_IDENTITY()。