我想通过输出变量' @ RoleID'来阅读Scope_Identity
从我指定范围标识的值。
C#:
private static long createNewRoleInsert(ADB.Model.RolesModel roleModelObj, MSSQL sql)
{
bool killConnection = Utils.getConnection(ref sql);
long returnValue = 0;
try
{
sql.SetSProc("[dbo].[p_Role_dfn_createNew]");
sql.AddParam("@Title", roleModelObj.Title);
sql.AddParam("@Description", roleModelObj.Description);
sql.AddParam("@CreatedDate", roleModelObj.CreatedDate);
var RoleID = sql.ExecuteNonQuery();
if(RoleID!=0 && RoleID>0)
{
returnValue = RoleID;
}
}
finally
{
if (killConnection)
sql.Dispose();
}
return returnValue;
}
存储过程:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[p_Role_dfn_createNew]
@Title nvarchar(250),
@Description nvarchar(MAX) = NULL,
@CreatedDate DateTime,
@RoleID bigInt OUTPUT
AS
SET NOCOUNT ON;
SET XACT_ABORT ON
DECLARE @l_object AS SYSNAME = OBJECT_NAME(@@PROCID),
@l_error_msg AS NVARCHAR(2000)
BEGIN TRY
BEGIN TRAN
INSERT INTO [adb_TestDb].[dbo].[Role] ([Title], [Description], [CreatedDate])
VALUES (@Title, @Description, @CreatedDate)
COMMIT TRAN
SET @RoleID = SCOPE_IDENTITY();
RETURN @RoleID
END TRY
BEGIN CATCH
-- rollback any open/uncomitted transactions
IF XACT_STATE() IN ( -1, 1) ROLLBACK TRANSACTION
-- return an error containing the object, error number and error description
SELECT @l_error_msg = 'Error number : ' + CAST(ERROR_NUMBER()AS VARCHAR) + '. ' + ERROR_MESSAGE()
RAISERROR (@l_error_msg,16,1)
END CATCH
答案 0 :(得分:1)
ExecuteNonQuery
method不返回过程的返回值,它返回受影响的行数。
要获取返回值,您需要使用ParameterDirection.ReturnValue
添加参数,但这不会安全地获取@RoleID
中的值,因为过程的返回值不能是{{ 1}},它始终是bigint
。
由于您已经将int
作为输出参数,因此应该在命令中添加参数以获取值。例如:
@RoleID
答案 1 :(得分:0)
您需要在C#中添加输出参数以从存储过程中获取@RoleID的值。这是一个例子:
using System.Data.SqlClient;
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.p_Role_dfn_createNew";
// add other parameters...
cmd.Parameters.Add(new SqlParameter("@RoleID", SqlDbType.BigInt))
.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
returnValue = (long)cmd.Parameters["@RoleID"].Value;
}
答案 2 :(得分:0)
更改
RETURN @RoleID
到
SELECT @RoleID
或添加输出参数,如其他答案中所述