2012-10-29 168 views
1

如何檢查指定的列是否允許空值?檢查列是否允許空值,C#?

我用下面的代碼打印的所有列,但我也想打印列是否允許空值:

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,即使在不允許空值的列中。

謝謝你的時間!

回答

2

如果你只後列的數據我會做到這一點從系統的觀點,而不是依賴數據適配器上。例如

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

​​添加或刷新行並且對錶知道特定列是否允許爲空的表模式信息沒有做任何事情。但是,您可以使用SqlDataAdapter.FillSchema()加載架構信息,然後AllowsDBNull會向您顯示列的正確狀態。

SqlDataAdapter da = new SqlDataAdapter(myCommand); 
DataSet ds = new DataSet(); 
da.FillSchema(ds, SchemaType.Source, tableName); 
da.Fill(ds, tableName); 
1
da.FillSchema(ds, SchemaType.Source, tableName);//Loads all the constraints and relations of tables 
da.Fill(ds, tableName);//Loads the data 
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 
}