我使用SQL Server2012。在此存储过程中,我想获取@@identity
或SELECT 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#中获取@@identity
或SELECT 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
答案 0 :(得分:-3)
使用ExecuteScalar时,您的存储过程必须返回@@ identity。类似于RETURN @@ IDENTITY;