获取DataColumn的原始数据格式

发布于 2024-11-16 07:31:59 字数 429 浏览 1 评论 0原文

如何获取 DataColumn 对象的原始数据格式(在数据库中)?

我有来自 DataTable 的 DataColumn 对象,它是打开 DBCommand SQL“选择”查询的结果的一部分。

如何获取有关查询返回的原始数据格式的信息(即“varchar[50]”等)。

我知道 DataColumn.DataType 但这里的信息不够具体,例如无法区分 varchar 和 char 或区分日期和时间戳或获取 varchar 字段的最大长度等等。

直接从服务器数据库方案获取信息不是我正在寻找的解决方案,因为查询文本是由用户输入的,我不想自己解析文本以找出正在使用哪个表的哪一列,因为可能有些列在数据库中没有相应的条目(例如 select ColumnA || Column B, 'SomeLiteral', 12 * ColumnC, null from MyTable)

How can I get the original data format (in the database) of a DataColumn object?

I have DataColumn objects from a DataTable that is part of the result of opening a DBCommand SQL "select" query.

How do I get information on the original data formats returned by the query (i.e. "varchar[50]" and so forth).

I know DataColumn.DataType but the information here is not specific enough, for example it is not possible to distinguish varchar and char or to distinguish date and timestamp or to get the maximum length of a varchar field and so on.

Getting information from the server database scheme directly is not the solution I am looking for, because the query text is entered by the user and I don't want to parse the text myself to find out what column of what table is being used and because there can be columns that don't have a corresponding entry in the database (e.g. select ColumnA || Column B, 'SomeLiteral', 12 * ColumnC, null from MyTable)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

公布 2024-11-23 07:31:59

您可以尝试类似的操作,并检查结果(在 schemaTable 表中)。

DataTable schemaTable;

String sql = "select * from ...";

using (SqlConnection cnx = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
  using (SqlCommand cmd = new SqlCommand(sql, cnx))
  {
     cnx.Open();

     using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.KeyInfo))
     {
        schemaTable = rdr.GetSchemaTable();
     }
  }
}

You could try something like this, and examine the results (in the schemaTable table).

DataTable schemaTable;

String sql = "select * from ...";

using (SqlConnection cnx = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
  using (SqlCommand cmd = new SqlCommand(sql, cnx))
  {
     cnx.Open();

     using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.KeyInfo))
     {
        schemaTable = rdr.GetSchemaTable();
     }
  }
}
淡莣 2024-11-23 07:31:59

听起来您正在获取一个临时字符串,获取一个数据表,并尝试确定其数据类型和长度。

尝试另一种方法,直接查询 SQL Server。正如您所发现的,DataColumn 没有您需要的所有信息。

var cols = GetTableDetails("MyTable");  
DataTable dt = GetDataTableFromUserSpecifiedQuery(userSqlQuery);
foreach (var col in dt.Columns)
{
    var matching = cols.SingleOrDefault(x=>x.Name == col.ColumnName);   
    if (matching !=null)
    {
         //you now have the name, datatype, and length of the column
         //matched from your table. 
    }
}

public List<Col> GetTableDetails(string tableName)
{
    List<Col> cols = new List<Col>();
    using (var conn = new SqlConnection("Data Source=server;Initial Catalog=Test1;Integrated Security=true;"))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = @"SELECT syscolumns.name AS COLUMN_NAME, 
                                    systypes.name AS DATA_TYPE, 
                                    syscolumns.LENGTH AS LENGTH 
                            FROM       sysobjects 
                            INNER JOIN syscolumns ON sysobjects.id = syscolumns.id 
                            INNER JOIN systypes ON syscolumns.xtype = systypes.xtype 
                            WHERE     (sysobjects.xtype = 'U') and
                            sysobjects.name = @tableName
                            ORDER BY sysobjects.name, syscolumns.colid;";
        cmd.Parameters.AddWithValue("@tableName", tableName);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {                 
            cols.Add(new Col { Name= dr["COLUMN_NAME"],
                               DataType= dr["DATA_TYPE"],
                               Len = dr["LENGTH"] });                 
        }
        return cols;
    }
}


public class Col { 
  public string Name{get;set;} 
  public string DataType{get;set;} 
  public int Len{get;set;} 
}

在此处输入图像描述

Sounds like you're taking an ad-hoc string, getting a DataTable, and trying to determine its datatype and length.

Try another approach by querying SQL Server directly. As you've discovered, DataColumn doesn't have all the info you need.

var cols = GetTableDetails("MyTable");  
DataTable dt = GetDataTableFromUserSpecifiedQuery(userSqlQuery);
foreach (var col in dt.Columns)
{
    var matching = cols.SingleOrDefault(x=>x.Name == col.ColumnName);   
    if (matching !=null)
    {
         //you now have the name, datatype, and length of the column
         //matched from your table. 
    }
}

public List<Col> GetTableDetails(string tableName)
{
    List<Col> cols = new List<Col>();
    using (var conn = new SqlConnection("Data Source=server;Initial Catalog=Test1;Integrated Security=true;"))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = @"SELECT syscolumns.name AS COLUMN_NAME, 
                                    systypes.name AS DATA_TYPE, 
                                    syscolumns.LENGTH AS LENGTH 
                            FROM       sysobjects 
                            INNER JOIN syscolumns ON sysobjects.id = syscolumns.id 
                            INNER JOIN systypes ON syscolumns.xtype = systypes.xtype 
                            WHERE     (sysobjects.xtype = 'U') and
                            sysobjects.name = @tableName
                            ORDER BY sysobjects.name, syscolumns.colid;";
        cmd.Parameters.AddWithValue("@tableName", tableName);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {                 
            cols.Add(new Col { Name= dr["COLUMN_NAME"],
                               DataType= dr["DATA_TYPE"],
                               Len = dr["LENGTH"] });                 
        }
        return cols;
    }
}


public class Col { 
  public string Name{get;set;} 
  public string DataType{get;set;} 
  public int Len{get;set;} 
}

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文