I'm trying to create a stored procedure that would take 4 paramters. These 4 paramters dictate how the returned table will look like.
@C_ID
parameter is always numeric. @U_ID
and @P_ID
values can contain a valid numeric value, or can be (or should be) passed as NULL
so WHERE
conditions either execute or not.
ALTER PROCEDURE [dbo].[GetData]
@C_ID integer,
@U_ID integer = Null,
@P_ID integer = Null,
@SortIndex integer = 1
AS
BEGIN
SELECT
ID, P_ID, U_Name, P_Name,
FORMAT(Date_When, 'dd/MM/yyyy hh:mm tt')
FROM
SomeTable
WHERE
C_ID = @C_ID
AND (@P_ID IS NULL OR P_ID = @P_ID)
AND (@U_ID IS NULL OR U_ID = @U_ID)
ORDER BY
CASE WHEN @SortIndex = 1 THEN -ID
ELSE ID
END ASC
END
On SQL Server 2014 the following executions work fine without any errors:
exec GetData '15', null, null, '1';
exec GetData '15', '1', null, '1';
exec GetData '15', null, '1', '1';
exec GetData '15', '1', '1', '1';
...
However on C# side the following code fails to execute:
int? SomeValue = null;
Adapter = new SqlDataAdapter("exec GetData '15'," + SomeValue + ",null,'1';", Connection);
Adapter.Fill(Data);
which gives me an error
Incorrect syntax near ','.
If I change the SomeValue
variable to 1, it works perfectly fine.
DBNull.Value
and simply leaving the parameter as ' ' do not work either.
So the question would be: how would I (if it is possible) be able to pass nullable integer to SQL given that it can be both null and a valid number?