Join condition with like %

ASHMITP 141 Reputation points
2022-05-17T06:24:25.057+00:00

Hi there,

How to put condition on on clause when joining two tables-

select * from a
left outer join n
on
a.[Visit ID] =n.[Service Event ID]
and
a.[Appt Date] =n.[Service Date]

eg, visit id be like '%n.[Service Event ID]%'

202674-visit.png

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,767 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,555 questions
{count} votes

Accepted answer
  1. LiHong-MSFT 10,046 Reputation points
    2022-05-18T02:29:15.91+00:00

    Hi @ASHMITP
    Two points to note:

    1. Wrong syntax: aaa ='%aaa%'
    2. Long strings come before like, short strings come after like.

    Try change this app.[Visit ID] ='%' + nap4.[Service Event ID] + '%' to this nap4.[Service Event ID] LIKE '%' + app.[Visit ID] + '%'
    Also, you can use CONCAT, like this : ON nap4.[Service Event ID] LIKE CONCAT('%',app.[Visit ID],'%')

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 40,901 Reputation points
    2022-05-17T06:29:57.727+00:00

    You can, but you have to do it the right way by concat the column with two apostrophe, like

    select * 
    from a
    left outer join 
    n
        on a.[Visit ID] = '%' + n.[Service Event ID] + '%'
           and a.[Appt Date] =n.[Service Date]