SQL WHERE clause with binary

时光总嘲笑我的痴心妄想 提交于 2020-01-29 06:31:25

问题


I have a SQL Server database table with a varbinary(max) column (i.e. Data VarBinary(max) in a create table command).

Is it possible to do a where clause with some kind of pattern matching within the binary data?

For example, using the C# .NET SqlCommand object, I found that I can do a query like select * from TableName where Data = 0x4638763849838709 go, where the value is the full data column value. But I want to be able to pattern match just parts of the data, like select * from TableName where Data = 0x%3876% go.

Thanks.


回答1:


For the example you have given in the question

WITH t(c) AS
(
SELECT CAST(0x4638763849838709 AS VARBINARY(MAX)) 
)
SELECT *
FROM t
WHERE CHARINDEX(0x3876,c) > 0



回答2:


SQL Server doesn't provide any functions to search through VARBINARY fields, so this is not possible.

See this related SO question and answers.

Essentially, you will need to extract the binary information and use a tool that understands the format it is in to search through it. It can't be done directly in SQL Server.




回答3:


Taking a shot in the dark here, but you could convert the field to VARCHAR(MAX) first, then compared using a LIKE statement.

E.g.

SELECT *
FROM TableName
WHERE CONVERT(VARCHAR(MAX), Data) LIKE '%2345%'


来源:https://stackoverflow.com/questions/5765018/sql-where-clause-with-binary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!