Passing a Null Value to a Query Parameter : SqlParameter « ADO.Net « C# / CSharp Tutorial






using System;
using System.Data;
using System.Data.SqlClient;

    class Program
    {
        static void Main(string[] args)
        {
            string sqlConnectString = "Data Source=(local);Integrated security=SSPI;Initial Catalog=AdventureWorks;";
            using (SqlConnection connection = new SqlConnection(sqlConnectString))
            {
                SqlCommand command =new SqlCommand("PassNullParameter", connection);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@ValueIn", SqlDbType.Int);
                command.Parameters[0].Value = 1;
                connection.Open( );
                Console.WriteLine(command.ExecuteScalar( ));

                command.Parameters[0].Value = null;
                Console.WriteLine("Parameter value = null");
                try{
                    
                    Console.WriteLine(Convert.ToBoolean(command.ExecuteScalar( )));
                }catch (Exception ex){
                    Console.WriteLine("ERROR: {0}", ex.Message);
                }
                command.Parameters[0].Value = System.DBNull.Value;
                Console.WriteLine(command.ExecuteScalar( ));
            }
        }
    }








32.24.SqlParameter
32.24.1.Pass value to SqlCommand with SqlParameter
32.24.2.Add SqlParameter to SqlCommand
32.24.3.Command Parameter
32.24.4.Passing a Null Value to a Query Parameter