如何检查指定的列是否允许空值?
我正在使用以下代码打印所有列,但如果列允许空值,我还想打印:
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,即使在不允许空值的列中也是如此。
谢谢你的时间!
答案 0 :(得分:2)
如果您只是在列数据之后,我会从系统视图执行此操作,而不是依赖于数据适配器。 e.g。
DECLARE @TableName VARCHAR(50) = 'dbo.TableName'
SELECT Name, Column_ID, Is_Nullable
FROM SYS.COLUMNS
WHERE [Object_ID] = OBJECT_ID(@TableName)
这也意味着您可以正确使用参数化查询并避免SQL Injection的风险。所以你的最终代码是这样的:
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));
}
}
}
答案 1 :(得分:1)
SqlDataAdapter.Fill()
添加或刷新行,并且不会对知道特定列是否允许null的表架构信息执行任何操作。但您可以使用SqlDataAdapter.FillSchema()加载架构信息,然后AllowsDBNull会显示正确的列状态。
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
da.FillSchema(ds, SchemaType.Source, tableName);
da.Fill(ds, tableName);
答案 2 :(得分:1)
da.FillSchema(ds, SchemaType.Source, tableName);//Loads all the constraints and relations of tables
da.Fill(ds, tableName);//Loads the data
答案 3 :(得分: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
}