[英]Using ADO.Net, how do I get the database table name associated with a DataColumn?
[英]How do I get the SqlDbType of a column in a table using ADO.NET?
我試圖在運行時確定sql server表列的SqlDbType是什么。
是否有一個類可以在System.Data.SqlClient中執行該操作,還是應該自己進行映射? 我可以從中獲取字符串表示
SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = '{0}' AND TABLE_SCHEMA = '{1}'
AND TABLE_NAME = '{2}' AND COLUMN_NAME = '{3}'
編輯:我不能使用SMO,因為我無法控制執行機器,所以我不能保證它將被安裝。 (抱歉沒有說清楚rp)。
編輯:回答Joel,我正在嘗試創建一個我可以調用的函數,它會在傳遞SqlConnection,表名和列名時返回一個SqlDBType。
在SQL Server中,您可以使用FMTONLY選項。 它允許您在不獲取任何數據的情況下運行查詢,只返回列。
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF";
SqlDataReader reader = cmd.ExecuteReader();
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"];
如果您最終要讀取數據,則可以執行以下操作:
SqlCommand comm = new SqlCommand("SELECT * FROM Products", connection);
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
Type type = reader.GetSqlValue(0).GetType();
// OR Type type = reader.GetSqlValue("name").GetType();
// yields type "System.Data.SqlTypes.SqlInt32"
}
}
老問題,但如果你要做的就是從字符串DATA_TYPE到SqlDbType枚舉,原始問題中提出的查詢結合一行代碼就可以解決問題了:
string dataType = "nvarchar"; // result of the query in the original question
var sqlType = (SqlDbType)Enum.Parse(typeof(SqlDbType), dataType, true);
您可以使用枚舉System.Data.CommandBehavior作為方法SqlCommand.ExecuteReader(System.Data.CommandBehavior.KeyInfo)的參數:
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "select column from table";
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.KeyInfo);
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"];
這個例子看起來像使用sql的示例:SET FMTONLY ON; 設置FMTONLY OFF。 但是你不能使用SET FMTONLY。 在這種情況下,你沒有
從表中接收數據。 您只收到元數據。
對於SQL Server,請使用SMO(SQL Server管理對象)。
http://www.yukonxml.com/articles/smo/
例如,您可以使用此代碼遍歷表的所有列。
Server server = new Server();
Database database = new Database( "MyDB" );
Table table = new Table( database, "MyTable" );
foreach ( Column column in table.Columns )
{
WriteLine( column.Name );
}
以下是您可以使用的所有列屬性: http : //msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.column_members.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.