如何从C#代码的存储过程中获取@@ identity或SELECT SCOPE_IDENTITY()的值?

时间:2019-05-24 20:58:20

标签: c# sql-server sql-server-2012 identity sqlcommand

我使用SQL Server2012。在此存储过程中,我想获取@@identitySELECT SCOPE_IDENTITY()的值。 intMyIdentity是“身份”列。

CREATE PROCEDURE [spMyInsert] 
    (@vchVar AS VARCHAR(20), 
     @fltVar AS FLOAT)
AS
    SELECT TOP 1 intMyIdentity 
    FROM MyTbl  
    WHERE vchVar = @vchVar

    IF @@rowcount = 0
    BEGIN
        INSERT INTO MyTbl (vchVar, fltVar) 
        VALUES (@vchVar, @fltVar)

        SELECT @@identity AS intMyIdentity 
        -- SELECT SCOPE_IDENTITY()
    END

如何在C#中获取@@identitySELECT SCOPE_IDENTITY()的值?

使用ExecuteScalar时,它返回0,而不是正确的值。

SqlConnection oConn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
oConn.Open();

mCommand.CommandText = "spMyInsert";
mCommand.Parameters.Add(new SqlParameter("@vchVar", txtMyVar.Text));
mCommand.Parameters.Add(new SqlParameter("@fltVar", dblMyVar));
mCommand.Connection = oConn;
mCommand.CommandType = CommandType.StoredProcedure; 

intMyIdentity = Convert.ToInt32(mCommand.ExecuteScalar());  --> this always return 0
oConn.Close();

已编辑:此查询有效

IF NOT EXISTS (SELECT 1 FROM myTbl WHERE vchVar = @vchVar)
BEGIN
    INSERT INTO myTbl (vchVar, fltVar)
    VALUES (@vchVar, @fltVar)

    SELECT SCOPE_IDENTITY()
END

1 个答案:

答案 0 :(得分:-3)

使用ExecuteScalar时,您的存储过程必须返回@@ identity。类似于RETURN @@ IDENTITY;