解释存储过程中的 byte[]

本文关键字:byte 过程中 存储 存储过程 解释 | 更新日期: 2023-09-27 17:55:26

一个过程,我们通过加密搜索字段并比较这些加密值来搜索加密字段。 我需要做的是(通过实体框架 4)将加密值(因为代码对其进行加密)传递到 proc 中,但如果未提供该值,也允许 null。

所以我需要传入一个字节[],但它也需要接受空值......这甚至可能吗,或者如果不是,有什么解决方法? 同样,我通过实体框架调用存储过程。

谢谢。

解释存储过程中的 byte[]

给定此存储过程:

create procedure dbo.pConvertBytesToInt
  @bytes varbinary(4)
as
  select convert(int,@bytes)
go

以下代码将执行它,如果传递的参数为 null,则传递 NULL:

static int? Bytes2IntViaSQL( byte[] @bytes )
{
  int? value ;
  const string connectionString = "Data Source=localhost;Initial Catalog=sandbox;Integrated Security=SSPI;" ;
  using ( SqlConnection connection = new SqlConnection( connectionString ) )
  using ( SqlCommand    sql        = connection.CreateCommand() )
  {
    sql.CommandType = CommandType.StoredProcedure ;
    sql.CommandText = "dbo.pConvertBytesToInt" ;
    SqlParameter p1 = new SqlParameter( "@bytes" , SqlDbType.VarBinary ) ;
    if ( @bytes == null ) { p1.Value = System.DBNull.Value ; }
    else                  { p1.Value = @bytes              ; }
    sql.Parameters.Add( p1 ) ;
    connection.Open() ;
    object result = sql.ExecuteScalar() ;
    value = result is DBNull ? (int?)null : (int?)result ;
    connection.Close() ;
  }
  return value ;
}

此测试工具

static void Main( string[] args )
{
  byte[][] testcases = { new byte[]{0x00,0x00,0x00,0x01,} ,
                         null                   ,
                         new byte[]{0x7F,0xFF,0xFF,0xFF,} ,
                       } ;
  foreach ( byte[] bytes in testcases )
  {
      int? x =  Bytes2IntViaSQL( bytes ) ;
      if ( x.HasValue ) Console.WriteLine( "X is {0}" , x ) ; 
      else              Console.WriteLine( "X is NULL" ) ;
  }
  return ;
}

产生预期的结果:

X is 1
X is NULL
X is 2147483647

我们最终通过将其推送为字符串,然后在进程中解析它来使其工作。 这奏效了。 但我相信我读到有一个表示 byte[] 数组的二进制对象,这也可以工作。