This is a simple question and I can't seem to think of a solution.
I have this defined in my stored procedure:
@communityDesc varchar(255) = NULL
@communityDesc is "aaa,bbb,ccc"
and in my actual query I am trying to use IN
WHERE AREA IN (@communityDesc)
but this will not work because my commas are inside the string instead of like this "aaa", "bbb", "ccc"
So my question is, is there anything I can do to @communityDesc so it will work with my IN statement, like reformat the string?
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.
The value of the parameter is used along with LIKE operator (statement) in a SELECT statement. In the above Stored Procedure, the LIKE operator (statement) works as CONTAINS where it looks for the match throughout the string value. You can also use it as STARTS WITH and ENDS WITH options as shown below.
the LIKE operation is not permitted to be used with IN.
This article could help you by your problem:
http://sqlperformance.com/2012/07/t-sql-queries/split-strings
In this article Aaron Bertrand is writing about your problem. It's really long and very detailed.
One Way would be this:
CREATE FUNCTION dbo.SplitStrings_XML
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
FROM
(
SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>')
+ '</i>').query('.')
) AS a CROSS APPLY x.nodes('i') AS y(i)
);
GO
With this function you only call:
WHERE AREA IN (SELECT Item FROM dbo.SplitStrings_XML(@communityDesc, N','))
Hope this could help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With