I've been trying to read RETURN value from my stored procedure for a while with no luck, in my previous post it was pointed out I should be using OUTPUT and someone provided some code on how I would do that as I've not used OUTPUT before.
I am now trying to get the OUTPUT value into my C# code.
- Return 0 if the vote didn't already exist
- Return 1 if the vote exists
The code currently throws an error:
System.Data.SqlClient.SqlException: Procedure or function 'Votes' expects parameter '@votecount', which was not supplied
I've viewed quite a lot of posts on here and google and not found my answer, so hoping someone on here can help me out to where i am going wrong
My 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
}
}
stored procedure
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