简体   繁体   中英

Is it possible to make Select() over Datatable with byte[] array field?

I run a query against a SQL Server for getting a table which contains varbinary columns; the columns are converted to byte array when returned as a datatable.

I am wondering if there is a way to make Select() over System.Byte[] ?

This is what I tried:

byte[] b = (byte[])sessions.table.Rows[72]["security_id"];
string hexString = ByteArrayToHexString(b);
DataRow[] rows = users.table.Select("sid = " + hexString);
// throw exception...
// System.Data.SyntaxErrorException: 'Cannot interpret token '0' at position 7.'

Dunno, but the DataView filter syntax is very obscure and rarely used. Instead just iterate the DataTable.Rows and run the comparison, or use the LINQ extensions and run something like:

var rows = users.table.AsEnumerble().Where(r => r["sid"].SequenceEqual(b)).ToArray();

According to the source , thanks to David Browne, datatable cannot handle binary data with select function, it's not implemented:

internal enum ValueType {
        Unknown = -1,
        Null = 0,
        Bool = 1,
        Numeric = 2,
        Str = 3,
        Float = 4,
        Decimal = 5,
        Object = 6,
        Date = 7,
}

The only solutions are to convert the varbinay to varchar in the server query if you know what the columns are or convert the datatable byte[] columns to string columns on duplicate table and than make the select(), of course other components like linq make it much easier...

Update:

example code how to add new string columns to table and convert the byte[] to string :

private DataTable fixDatatableType(DataTable input) {

 List<DataColumn> overwriteColumnIndex = new List<DataColumn>();
 List<string> addedColumns = new List<string>();

 for (int i = 0; i < input.Columns.Count; i++)
 {
  if (input.Columns[i].DataType == typeof(byte[])) {
      overwriteColumnIndex.Add(input.Columns[i]);
      string newColumnName = input.Columns[i].ColumnName + "_str";
      addedColumns.Add(newColumnName);
      DataColumn dataColumn = new DataColumn(newColumnName, typeof(string));
      input.Columns.Add(dataColumn);
  }
 }

 if (overwriteColumnIndex.Count != 0) {
  for (int z = 0; z < input.Rows.Count; z++)
  {
   DataRow row = input.Rows[z];
   for (int m = 0; m < overwriteColumnIndex.Count; m++)
   {
    if (row[overwriteColumnIndex[m]] != DBNull.Value) {
     row[addedColumns[m]] = 
     ByteArrayToHexString((byte[])row[overwriteColumnIndex[m]]);
    }
   }
  }
 }
 return input;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM