querying binary column using like in sql server

前端 未结 3 548
不思量自难忘°
不思量自难忘° 2020-12-20 15:54

I\'m using SQL Server 2008. In my table I have a column called TestData of type binary.

Sample data in TestData column are

         


        
3条回答
  •  我在风中等你
    2020-12-20 16:30

    For a leading prefix LIKE comparison, gbn's answer will do. For a real LIKE equivalence of string searches, you can use LIKE as follows:
    (borrowing schema and sample data from @gbn)

    DECLARE @foo TABLE (TestData varbinary(100) NOT NULL);
    INSERT @foo (TestData) VALUES
             (0x0001DC780C0030373156635D0C00B8),
             (0x0001AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA),
             (0x0001AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF),
             (0x0301DC780C0030373156385D0C006499C401009A0600AC),
             (0x0301FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF),
             (0x0302000000000000000000000000000000000000000000);
    
    SELECT *
    FROM @foo
    WHERE CAST(TestData AS VARCHAR(MAX)) LIKE '%'+CAST(0xDC78 AS VARCHAR(MAX))+'%';
    

    When you cast a binary value to VARCHAR, all it does is treat the raw bits as a string stream. It does not magically convert it into the string representation. Consider the example below:

    select cast(0x41 as varchar(10));     -- Result: A
    select cast(0x414263 as varchar(10)); -- Result: ABc
    

    Because the byte 0x41 or ordinal 65 is 'A' in the standard Latin codepage.

提交回复
热议问题