Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>If you search in the way you describe, you would actually need to use Regular Expressions or something else to make it reliable.</p> <p>In your example you say you want to search for:</p> <pre><code>companystring like '%CompanyName":"%test 2%","%' </code></pre> <p>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:</p> <pre><code>-- 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}' </code></pre> <p>Even though "test 2" isn't in the CompanyName, it is in the text following it (TradingName), which is also followed by the string <code>","</code> so it would meet your search criteria.</p> <p>Another option would be to create a view that exposes the value of CompanyName using a column defined as follows:</p> <pre><code>LEFT( SUBSTRING(companystring, CHARINDEX('"CompanyName":"', companystring) + LEN('"CompanyName":"'), LEN(companystring)), CHARINDEX('"', SUBSTRING(companystring, CHARINDEX('"CompanyName":"', companystring) + LEN('"CompanyName":"'), LEN(companystring))) - 1 ) AS CompanyName </code></pre> <p>Then you could query that view using <code>WHERE CompanyName LIKE '%test 2%'</code> and it would work, although performance could be an issue.</p> <p>The logic of the above is to get everything after <code>"CompanyName":":</code></p> <pre><code>SUBSTRING(companystring, CHARINDEX('"CompanyName":"', companystring) + LEN('"CompanyName":"'), LEN(companystring)) </code></pre> <p>Up to but not including the first <code>"</code> in the sub-string (which is why it is used twice).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload