0

我在 Sql Server 表中有一个列:

companystring = {"CompanyId":0,"CompanyType":1,"CompanyName":"Test     
215","TradingName":"Test     215","RegistrationNumber":"Test 
215","Email":"test215@tradeslot.com","Website":"Test    
215","DateStarted":"2012","CompanyValidationErrors":[],"CompanyCode":null}

我想查询要搜索的列

companyname like '%CompanyName":"%test 2%","%'

我想知道我是否正确查询,因为对于某些搜索字符串,它不会产生正确的结果。谁能帮我解决这个问题?

编辑:我删除了粗体格式

4

3 回答 3

2

%是一个特殊字符,表示通配符。如果要查找字符串中的实际字符,则需要对其进行转义。

DECLARE @d TABLE(id INT, s VARCHAR(32));

INSERT @d VALUES(1,'foo%bar'),(2,'fooblat');

SELECT id, s FROM @d WHERE s LIKE 'foo[%]%'; -- returns only 1

SELECT id, s FROM @d WHERE s LIKE 'foo%'; -- returns both 1 and 2
于 2013-11-11T23:16:24.250 回答
0

It looks like you have JSON data stored in a column called "companystring". If you want to search within the JSON data from SQL things get very tricky.

I would suggest you look at doing some extra processing at insert/update to expose the properties of the JSON you want to search on.

If you search in the way you describe, you would actually need to use Regular Expressions or something else to make it reliable.

In your example you say you want to search for:

companystring like '%CompanyName":"%test 2%","%'

I understand this as searching inside the JSON for the string "test 2" somewhere inside the "CompanyName" property. Unfortunately this would also return results where "test 2" was found in any other property after "CompanyName", such as the following:

-- formatted for readability
companystring = '{
    "CompanyId":0,
    "CompanyType":1,
    "CompanyName":"Test Something 215",
    "TradingName":"Test 215",
    "RegistrationNumber":"Test 215",
    "Email":"test215@tradeslot.com",
    "Website":"Test 215",
    "DateStarted":"2012",
    "CompanyValidationErrors":[],
    "CompanyCode":null}'

Even though "test 2" isn't in the CompanyName, it is in the text following it (TradingName), which is also followed by the string "," so it would meet your search criteria.

Another option would be to create a view that exposes the value of CompanyName using a column defined as follows:

LEFT(
    SUBSTRING(companystring, CHARINDEX('"CompanyName":"', companystring) + LEN('"CompanyName":"'), LEN(companystring)),
    CHARINDEX('"', SUBSTRING(companystring, CHARINDEX('"CompanyName":"', companystring) + LEN('"CompanyName":"'), LEN(companystring))) - 1
) AS CompanyName

Then you could query that view using WHERE CompanyName LIKE '%test 2%' and it would work, although performance could be an issue.

The logic of the above is to get everything after "CompanyName":":

SUBSTRING(companystring, CHARINDEX('"CompanyName":"', companystring) + LEN('"CompanyName":"'), LEN(companystring))

Up to but not including the first " in the sub-string (which is why it is used twice).

于 2013-11-12T01:56:35.927 回答
0

根据您的平台,您可能能够使用其主库中内置的正则表达式和/或 lambda 表达式的某种组合。例如,.NET 有 LINQ,这是一个强大的工具,可以抽象查询并为搜索提供杠杆作用。

于 2013-11-11T23:13:45.333 回答