简体   繁体   中英

SQL LIKE multiple values

I am running the following sql code in python:

SELECT 
    FIN AS 'LIN',
    CUSIP, 
    Borrower_Name, 
    Alias,
    DS_Maturity, 
    Spread, 
    Facility, 
    Facility_Size, 
    Log_date
FROM 
    [Main].[FacilityInformation]
WHERE 
    CUSIP IN ('00485GAC2', 'N1603LAD9')
    OR (YEAR(DS_Maturity) in (2019,2024)
    AND ((Borrower_Name LIKE 'Acosta Inc , Bright Bidco BV%'
          OR Alias LIKE 'Acosta 9/14 (18.61) Non-Extended Cov-Lite, Lumileds 2/18 Cov-Lite%')))

It works perfectly when I have 3 or 4 borrower names or cusips or alias, but I am trying to run this with dozens of possible values. I thoungh that following the same logic as IN ('{}') with LIKE '{}%' will work, but it doesn't. So I want to use a efficient code but not something like:

SELECT * FROM table WHERE
column LIKE 'text1%'
column LIKE 'text2%'
.
.
.
column LIKE 'textn%'

This is good if every time you know the exactly numbers of time that you have to introduce the 'text, even though it is hard to do this 30 times or more so it will be pretty bad for a large number of borrower_names or cusips. It is not efficient. I hope it is clear what I am trying to ask.

You can join using VALUES and LIKE :

-- Test data
DECLARE @s TABLE (mytext NVARCHAR(20))
INSERT INTO @s VALUES ('abc'), ('def'), ('ghi')

-- Select
SELECT
    s.mytext
FROM @s s
INNER JOIN (VALUES ('a%'),('%h%')) n(wildcard) ON s.mytext LIKE n.wildcard

Or you can do it by using a table:

DECLARE @s TABLE (mytext NVARCHAR(20))
DECLARE @t TABLE (wildcard NVARCHAR(20))

INSERT INTO @s VALUES ('abc'), ('def'), ('ghi')
INSERT INTO @t VALUES ('a%'), ('%h%')

SELECT s.mytext FROM @s s
INNER JOIN @t t ON s.mytext LIKE t.wildcard

Both gives the result:

mytext
------
abc
ghi
WITH CTE AS
(
SELECT VALUE
FROM (
        VALUES ('B79'), ('BB1'), ('BB10'), ('BB11'), ('BB12'), ('BB18'), ('BB2'), ('BB3'), ('BB4'), ('BB5'), ('BB6'), ('BB8'), ('BB9'), ('BB94'), ('BD1'), ('BD10'), ('BD11'), ('BD12'), ('BD13'), ('BD14'),
                ('BD15'), ('BD16'), ('BD17'), ('BD18'), ('BD19'), ('BD2'), ('BD20'), ('BD21'), ('BD22'), ('BD3'), ('BD4'), ('BD5'), ('BD6')
     ) V(VALUE)
)   


SELECT * 
FROM tbl_ClientFile T
WHERE EXISTS ( SELECT TOP 1 1 FROM CTE WHERE T.CLNTPOST1 LIKE CTE.VALUE + '%')

Link to the answer is there:

SQL Multiple LIKE Statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM