Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Stored Procedure LIKE

Tags:

sql

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?

like image 511
user979331 Avatar asked Apr 08 '16 20:04

user979331


People also ask

What is like %% in SQL?

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.

How can use like query in stored procedure in SQL Server?

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.

Can you do in like SQL?

the LIKE operation is not permitted to be used with IN.


1 Answers

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.

like image 76
Nik Bo Avatar answered Oct 14 '22 21:10

Nik Bo