我如何从SP获得SCOPE_IDENTITY()?

时间:2013-06-07 19:32:24

标签: sql-server vb.net stored-procedures dbnull scope-identity

我试图从存储过程中获取SCOPE_IDENTITY到我的vb.NET应用程序 但是我得到了DBNull异常。

这是我的SP:

ALTER PROCEDURE [dbo].[sp_XYZ] 
@ID INT,
@OtherID INT OUTPUT

AS
BEGIN

SELECT 
@Name = name,
FROM dbo.PERSON
WHERE  id = @ID

INSERT INTO [SERVERSOLMAR\TSW].TSWDATA.dbo.t_Employees
    (
    Name
    )
VALUES
    (
    @Name
    )
    SET @OtherID = SCOPE_IDENTITY() 
END

我的vb.NET代码:

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("CON").ConnectionString)
    Dim dataAdapter As New SqlDataAdapter("sp_XYZ", con)
    Dim ARLI As Integer
    Try
        con.Open()
        With dataAdapter.SelectCommand
            .CommandType = CommandType.StoredProcedure
            .Parameters.Add("@ID", SqlDbType.VarChar).Value = id

            Dim identity As New SqlParameter("@OtherID", SqlDbType.Int)
            valorInteger.Direction = ParameterDirection.Output
            .Parameters.Add(identity)
            .ExecuteNonQuery()
            ARLI = identity.Value
        End With
End try

insert语句正常工作。

问题是即将到来"转换类型' DBNull'输入'整数'无效。"

我正在使用链接服务器,这可能是问题吗?

1 个答案:

答案 0 :(得分:0)

尝试使用SCOPE_IDENTITY()而不是SCOPE_IDENTITY。