.net:如何在 C# 中执行带有可为空参数的存储过程?

标签 .net sql-server stored-procedures parameters nullable

如何在 C# 中执行带有可空参数的存储过程?

编辑:

实际上,我已经写了下面的代码。如您所见,status 参数是一个可以为 null 的值类型。 这是对的吗?还是不是?

public void LoadAll(DataTable tb, int? status=null)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection())
            {
                connection.ConnectionString = this.connectionString;

                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "USP_OrganizationChartSelect";
                    SqlCommandBuilder.DeriveParameters(command);
                    command.Parameters["@Status"].Value = status.HasValue ? status : null;
                    if (connection.State != ConnectionState.Open)
                        connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    tb.Clear();
                    adapter.Fill(tb);
                    adapter.Dispose();
                    adapter = null;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

谢谢

最佳答案

你可以试试 DBNull.Value而不是 null 或在 nullable 完全没有值时省略参数。

关于.net:如何在 C# 中执行带有可为空参数的存储过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2947540/

相关文章:

.net - 通过 Reflection.Emit 调用默认的无参数值类型构造函数

.net - 自定义 SQL 函数和 Code First (EF 4.1)

sql - 什么是插槽?

php - 使用 php 在下拉列表中从 MSSQL 中获取数据

sql - 我正在 PostgreSQL 中创建存储过程,但出现错误 'syntax error at or near "UPDATE"'

c# - WinForms:可变数量的动态 TextBox 控件

c# - 我应该抛出哪个异常来表示程序中的内部错误?

sql-server - 如何设置项目以使用 odbc 和 mssql 驱动程序?

c# - 在 C# 中从 Entity Framework 调用存储过程

sql - 参数化 WHERE 子句?