0

I have this below input

string request = "[
    {
        "firstname" : null,
        "lastname" : "xyz"
    },
    {
        "firstname" : "def",
        "lastname" : null
    }
]"

I am trying to insert this into a SQL Server table.

I tried with this code:

public class SqlData
{
    public string? firstname;
    public string? lastname;
}

List<SqlData> sqldata = JsonSerializer.Deserialize<SqlData>[]>(request).ToList();

SqlConnection connection = new SqlConnection("connection string...........")
connection.open();

foreach (SqlData data in sqldata)
{
    SqlCommand cmd = new SqlCommand("storedprocedure", connection)
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@FirstName",data.firstname);
    cmd.Parameters.AddWithValue("@LastName",data.lastname);

    int i = cmd.ExecuteNonQuery();
}

connection.close();

I get this error:

Procedure or function 'storedprocedure' expects parameters '@FirstName' which was not supplied.

This is my stored procedure:

CREATE PROCEDURE storedprocedure
    @FirstName varchar(50),
    @LastName varchar(50)
AS
BEGIN
    INSERT INTO mytable (FirstName, LastName) 
    VALUES (@FirstName, @LastName)
END

Sometimes my firstname value will be null and sometimes my lastname value will be null.

I need to send this null values into the SQL Server table. How to handle these null values? Could anyone help with this?

Thanks in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vijay
  • 15
  • 3

0 Answers0