I wrote a stored procedure:
CREATE PROCEDURE [dbo].[GetAudioBookStats]
@UserId NVARCHAR(450) = NULL
,@ArtistId BIGINT = 0
,@PublisherId BIGINT = 0
,@AudioBookId BIGINT = 0
,@SubscriptionType INT = 0
,@ResultStat BIGINT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT DISTINCT
@ResultStat = COUNT (*)
FROM dbo.AudioBookDownload AS d
LEFT JOIN dbo.AudioBooks AS b ON d.AudioBookId = b.Id
WHERE ( @ArtistId IS NULL
OR b.WriterArtistId = @ArtistId
OR b.TranslatorArtistId = @ArtistId
OR b.NarratorArtistId = @ArtistId)
AND (@PublisherId IS NULL
OR b.PublisherId = @PublisherId)
AND (@AudioBookId IS NULL
OR b.Id = @AudioBookId)
AND (@SubscriptionType IS NULL
OR d.SubscriptionType = @SubscriptionType)
AND (@UserId IS NULL
OR d.UserId = @UserId);
END;
I call it in a service in this way:
var outDownloadCount = new SqlParameter("ResultStat", SqlDbType.BigInt)
{
Direction = ParameterDirection.Output
};
const string sql = "EXECUTE dbo.[GetAudioBookStats] @UserId, @ArtistId, @PublisherId, @AudioBookId, @SubscriptionType, @ResultStat OUTPUT";
await context
.Database
.ExecuteSqlCommandAsync(sql, userId, artistId, publisherId, audioBookId, subscriptionType, outDownloadCount);
var result = (int)outDownloadCount.Value;
All parameters are set to null
in execution, but I get this error:
SqlException: Must declare the scalar variable "@UserId".
The project is developed with ASP.net core 2.2 if it helps.
What am I doing wrong?
@
character, ie it should be@UserID
and@ResultStat
, notUserId
orResultStat
. Post the code that creates the other parameters.Where
calls in code as needed