我有以下简单的存储过程:
create or alter procedure dbo.spAddAccount
@AccountName varchar(100),
@OpeningBalance money,
@AccountTypeId tinyint,
@AccountId tinyint output
as
begin
insert into dbo.Accounts (AccountName, OpeningBalance, AccountTypeId)
output inserted.AccountId
values (@AccountName, @OpeningBalance, @AccountTypeId);
end
我通过Dapper从c#使用以下代码调用它:
var parameters = new DynamicParameters();
parameters.Add("AccountName", dbType: DbType.String, direction: ParameterDirection.Input, value: account.AccountName);
parameters.Add("OpeningBalance", dbType: DbType.String, direction: ParameterDirection.Input, value: account.OpeningBalance);
parameters.Add("AccountTypeId", dbType: DbType.Byte, direction: ParameterDirection.Input, value:account.AccountTypeId);
parameters.Add("AccountId", dbType: DbType.Byte, direction: ParameterDirection.Output);
await using var sqlConnection = new SqlConnection(ConnectionString);
await sqlConnection.ExecuteAsync(
"spAddAccount",
param: parameters,
commandType: CommandType.StoredProcedure);
return parameters.Get<byte>("@AccountId");
这不起作用,因为@AccountId
总是空的。
如果我像这样通过SQL shell运行存储过程:
declare @accountId tinyint;
exec spAddAccount 'Foo', 0, 1, @accountId output
select @accountId;
然后,@accountId
总是空的。
我认为这是因为我需要将output inserted.AccountId
的结果分配给@accountId
,因为将其分配给我声明的输出参数不够聪明。但是我不知道怎么做。
我知道我可以使用scope_identity()
,但我想知道如何在插入语句中使用output
来工作。
我也试过
output inserted.AccountId as '@AccountId`
但这也不好。
感谢这适用于存储过程的主体
DECLARE @insertResult table (accountId tinyint)
insert into dbo.Accounts
(AccountName, OpeningBalance, AccountTypeId)
OUTPUT INSERTED.AccountId into @insertResult
values
(@AccountName, @OpeningBalance, @AccountTypeId);
set @AccountId = (select accountId from @insertResult);