1

如何检查指定列是否允许空值?

我正在使用以下代码打印所有列,但如果列允许空值,我也想打印:

cnn = new SqlConnection(connetionString);
cnn.Open();

SqlCommand myCommand = new SqlCommand("select * from " + tableName, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();

da.Fill(ds, tableName);

foreach (DataColumn dc in ds.Tables[0].Columns)
{
     // Print stuff here, dc.ColumnName is the column name
}

获取预定义表时,DataColumn.allowDBnull 属性似乎不起作用,它始终设置为 true,即使在不允许空值的列中也是如此。

谢谢你的时间!

4

4 回答 4

2

如果您只关注列数据,我会从系统视图中执行此操作,而不是依赖数据适配器。例如

DECLARE @TableName VARCHAR(50) = 'dbo.TableName'

SELECT  Name, Column_ID, Is_Nullable
FROM    SYS.COLUMNS
WHERE   [Object_ID] = OBJECT_ID(@TableName)

这也意味着您可以正确使用参数化查询并避免 SQL 注入的风险。所以你的最终代码将是这样的:

using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("SELECT Name, Is_Nullable FROM sys.columns WHERE [Object_ID] = OBJECT_ID(@TableName)", connection))
{
    connection.Open();
    command.Parameters.Add("@TableName", SqlDbType.VarChar).Value = tableName;
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine("Name: {0}; Allows Null: {1}", reader.GetString(0), reader.GetBoolean(1));
        }
    }
}
于 2012-10-29T09:55:53.757 回答
1

SqlDataAdapter.Fill() 添加或刷新行并且不执行与表模式信息相关的任何操作,该信息知道特定列是否允许为空。但是您可以使用SqlDataAdapter.FillSchema()加载架构信息,然后AllowsDBNull将向您显示列的正确状态。

SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
da.FillSchema(ds, SchemaType.Source, tableName);
da.Fill(ds, tableName);
于 2012-10-29T09:41:08.753 回答
1
da.FillSchema(ds, SchemaType.Source, tableName);//Loads all the constraints and relations of tables 
da.Fill(ds, tableName);//Loads the data
于 2012-10-29T09:48:40.360 回答
0
cnn = new SqlConnection(connetionString);
cnn.Open();

SqlCommand myCommand = new SqlCommand("
select name,is_nullable  from sys.columns where object_id=object_id('"+tableName+"')", cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();

da.Fill(ds, tableName);

foreach (datarow in ds.Tables[0].rows)
{
    if(dr["is_nullable"].ToString()==1)
    //the column is nullable
    else
    //column is not nullable
}
于 2012-10-29T09:51:18.867 回答