I'm working with SQL Server 2014 and I'm trying to execute a (dynamic) stored procedure from entity framework.
My stored procedure has the following input parameters:
@Username NVARCHAR(100),
@Number DECIMAL,
@PageIndex INT = 1,
@PageSize INT = 20,
@Field1 NVARCHAR(12) = NULL,
@Field2 NVARCHAR(60) = NULL,
@Field3 NVARCHAR(60) = NULL,
@Field4 NVARCHAR(60) = NULL,
@Field5 NVARCHAR(60) = NULL,
@Field6 NVARCHAR(60) = 'ABC',
@Field7 NVARCHAR(4) = 'ABC',
@IsCountOnly BIT = 0,
@IsFilterOnly BIT = 0
EF generates the following query (captured via SQL profiler) based on the parameters I've added to my array but note that I'm only adding the ones I need since most of them are optional.
exec sp_executesql
N'EXEC MySp @Username, @Number, @IsCountOnly',
N'@Username nvarchar(100), Number decimal(6,0), @IsCountOnly bit',
@Username=N'me@mycompany.com', @Number=12345, @IsCountOnly=1
When I pass the @Username, @Number which are both compulsory and then pass the @IsCountOnly, my stored procedure gets executed but it returns the wrong results as it seems to treat the value passed via @IsCountOnly as @PageIndex rather than @IsCountOnly.
Note that if I call EXEC directly in the SQL Server Management Studio
:
EXEC [dbo].[MySp]
@Username = N'me@mycompany.com',
@Number = 12345,
@IsCountOnly = 1
GO
It works as expected.
To test whether this was the problem, I included all the parameters in the exec sp_executesql N'EXEC ...
and it worked as expected but it just seems like an overkill having to defined all the parameters when only a few are needed in some scenarios.
Is this a bug in SQL when working with exec sp_executesql
and EXEC
or am I doing something wrong??
Thanks.
UPDATE-1:
Note that when I say it worked as expected when passing all the parameters, that's not entirely true as when I pass null for the optional parameters, it's not actually using the default values provided which to some extend makes sense but it means I would have to pass the correct defaults in my .NET
project rather than via SQL which is just not ideal.