在 C# 2.0 中,我有一个字段列表和一个值列表(存储为字符串)、一个表名和一个 ODBC 连接。
我需要获取该表上字段的数据类型,所以我知道如何生成我的 sql。
从我所拥有的信息中获取这些信息的最佳方式是什么?
我唯一的想法是SELECT TOP 0 * FROM @TableName
在数据适配器中做一个,取回数据集,然后根据数据表中的数据列遍历字段名称列表。
有没有更好的方法来解决这个问题?
试试这个
select * from sys.columns where object_id = object_id('MyTable')
希望这可以帮助。
您最好的选择是像 Nick Beradi 提到的那样查询您的数据库系统表。如果出于某种原因这不是一个选项,您可以执行以下操作:
using (SqlConnection conn = new SqlConnection(myConnectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * from MyTable", conn))
{
DataTable table = new DataTable();
adapter.FillSchema(table, SchemaType.Mapped);
//at this point, table will have no rows, but will have all the columns of which you can get their datatypes
}
}