0

This is a new issue of my previous question (C# Using Parameters in SqlHelper.DB). If I pass null as the parameters and set the command text to a parameterless stored procedure, it works fine.

SQLHelper.DB is executing the stored procedure but I get an error:

Unhandled Exception: System.Data.SqlClient.SqlException: Procedure or function 'sptest' expects parameter '@param1', which was not supplied.

This can be recreated by creating a new .NET 4.7.2 console app and installing Nuget package SQLHelper.DB then using the code below.

Console app code:

using Microsoft.Extensions.Configuration;
using SQLHelperDB;
using SQLHelperDB.HelperClasses;
using SQLHelperDB.HelperClasses.Interfaces;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            TestSql();
        }

        static void TestSql()
        {
            IParameter[] p = new IParameter[]
            {
                new Parameter<string>("@param1", "test1"),
                new Parameter<string>("@param2", "test2")
            };

            IConfigurationRoot Configuration = new ConfigurationBuilder()
                 .AddInMemoryCollection()
                 .Build();

            SQLHelper helper = new SQLHelper(Configuration, SqlClientFactory.Instance, "your connection string here");
            helper.CreateBatch()
                .AddQuery("dbo.sptest", CommandType.StoredProcedure, p)
                .Execute();
        }
    }
}

Stored procedure:

CREATE PROCEDURE [dbo].[sptest]
    (@param1 VARCHAR(10),
     @param2 VARCHAR(10))
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO dbo.tbltest (field1, field2)
    VALUES (@param1, @param2);
END;

Table:

CREATE TABLE [dbo].[tbltest]
(
    [field1] [VARCHAR](10) NULL,
    [field2] [VARCHAR](10) NULL
) ON [PRIMARY]
Jeremy Hodge
  • 612
  • 3
  • 14

1 Answers1

0

Adding a parameter without a value, or adding a parameter with an explicit initial value of DBNull.Value is ignored when executing the underlying System.Data.SqlCommand, which SQLHelper.DB is using.

Contrast this with T-SQL, where the scalar variable exists with a value of NULL every time you declare it, even without an explicit NULL value: DECLARE @param1 VARCHAR(10).

This inconsistency has caused my code to crash unexpectedly under this pattern as well:

command.Parameters.AddWithValue("@param1", (object)this.Status == null ? DBNull.Value : this.Status);

The solution:

command.Parameters.Add("@param1", SqlDbType.VarChar);
command.Parameters["@param1"].Value = (object)this.Status == null ? DBNull.Value : this.Status;

Presumably this translates similarly to SQLHelper.DB

Elaskanator
  • 1,135
  • 10
  • 28
  • That isn't the problem in this case as I am explicitly setting the parameter values in the code above... but this is good to know! – Jeremy Hodge Nov 11 '19 at 21:50