一段时间以来,我一直在尝试从存储过程中读取RETURN
的值,但是没有运气,在我以前的帖子中指出我应该使用OUTPUT
,并且有人在我该怎么做,因为我以前没有使用过OUTPUT
。
我现在正在尝试将OUTPUT
值添加到我的C#代码中。
该代码当前引发错误:
System.Data.SqlClient.SqlException:过程或函数'Votes'需要参数'@votecount',但未提供
我在这里和Google上浏览了很多帖子,但找不到答案,所以希望有人在这里可以帮助我找出我要去哪里
我的C#
command = new SqlCommand($@"EXECUTE dbo.Votes @VotedMember = @@VotedMember,
@VotedBy = @@VotedBy",
StaticObjects._connection);
if (Context.Guild.Users.Where(x => x.Username.ToLower() == member.ToLower() ||
x.Nickname?.ToLower() == member.ToLower()).Count() > 0)
{
SqlParameter GOTWParam = new SqlParameter
{
ParameterName = "@@VotedMember",
Value = //code here
}
command.Parameters.Add(GOTWParam);
SqlParameter VotedByParam = new SqlParameter
{
ParameterName = "@@VotedBy",
Value = //code here
};
command.Parameters.Add(VotedByParam);
command.Parameters.Add("@votecount", SqlDbType.Int).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
int response = Convert.ToInt32(command.Parameters["@votecount"].Value);
switch (response)
{
case 0:
// do something
case 1:
// do something
}
}
存储过程
CREATE PROCEDURE [dbo].[Votes]
@VotedMember BIGINT,
@VotedBy BIGINT,
@votecount INT OUTPUT
AS
BEGIN TRY
BEGIN TRANSACTION t_Transaction
SET @votecount = 0
IF NOT EXISTS(SELECT 1 FROM [dbo].[GOTWVotes]
WHERE [VotedBy] = @VotedBy)
BEGIN
INSERT INTO
[dbo].[GOTWVotes] ([VotedMember],[VotedBy])
VALUES
(@VotedMember, @VotedBy)
END
ELSE
BEGIN
SELECT @votecount = COUNT(*) FROM [dbo].[GOTWVotes]
WHERE [VotedBy] = @VotedBy
END
COMMIT TRANSACTION t_Transaction
END TRY
BEGIN CATCH
SET @votecount = -1
ROLLBACK TRANSACTION t_Transaction
END CATCH
答案 0 :(得分:1)
您缺少输出参数。
TSQL类似于:
command = new SqlCommand($@"EXECUTE dbo.Votes @VotedMember = @p_VotedMember,
@VotedBy = @p_VotedBy,
@p_votecount = @votecount output",
StaticObjects._connection);
和C#
var pVotecount = command.Parameters.Add("@p_votecount", SqlDbType.Int);
pVotecount.Direction = ParameterDirection.Output;
@ p_
是与存储过程参数名称区分开的参数名称。
如果使用存储过程的返回值(不是最佳实践),则调用将类似于:
command = new SqlCommand($@"EXECUTE @p_votecount = dbo.Votes @VotedMember = @p_VotedMember,
@VotedBy = @p_VotedBy",
StaticObjects._connection);
在两种情况下,@p_votecount
应该是ParameterDirection.Output
而不是ParameterDirection.ReturnValue
。 ReturnValue仅与CommandType.StoredProcedure一起使用。