0

I'm trying to use the string_split function in my where clause to split the values from json filter and create IN clause. The query should return the values found, otherwise return everything.

Filter:

DECLARE @Filter NVARCHAR(MAX)
SET @Filter=N'{
    "objectName": "Object2"
}'

The following query, will do exactly what I want, if I only specify one objectName.

...
AND (c.objectName IS NULL AND JSON_VALUE(@Filter,N'$.objectName') IS NULL OR c.objectName= ISNULL(JSON_VALUE(@Filter,N'$.objectName'),c.objectName))

But if I change my Filter to contain , separated values:

SET @Filter=N'{
    "objectName": "Object1, Object2"
}'

and use string_split function to read those values, it's not liking the string_split function in the where clause. I believe my syntax is wrong.

AND (c.objectName IS NULL AND JSON_VALUE(@Filter,N'$.objectName') IS NULL OR c.objectName IN 
string_split(ISNULL(JSON_VALUE(@Filter,N'$.objectName'),c.objectName), ','))

Does json_value needs to be casted to varchar first?

1
  • STRING_SPLIT is a table value function. If you want it in the WHERE you need to include it in a sub query. Commented Dec 4, 2018 at 18:45

1 Answer 1

1

I can't test, however, this will (probably) get you what you are after:

  AND (c.objectName IS NULL
  AND  JSON_VALUE(@Filter,N'$.objectName') IS NULL 
   OR  c.objectName IN (SELECT value FROM STRING_SPLIT(ISNULL(JSON_VALUE(@Filter,N'$.objectName'),c.objectName), ',')))

Like I stated above, STRING_SPLIT is a TVF, you can't just reference it in the WHERE. It needs to be inside a subquery, or in your FROM clause.

Sign up to request clarification or add additional context in comments.

1 Comment

that's exactly what I did, based on your comment. Thank you, it worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.