0

I have a problem with an extraction query.

I want to extract all records that begin with exactly one name.

The problem:

  • Not always the end of the name is this extension;
  • When they are present, they have no fixed length.

Example:

TabNames

id | Name

1 | Mike
2 | Mike Nell-1
3 | Mike-2
4 | Robert-1
5 | Mike Rio-NN
6 | Mike-Orio-2
.....

Name searched for: 'Mike'

Desired outcome:

Mike, Mike-2

If interested, I use SQL Server.

How can I do?

  • Why Mik resolves to Mike, Mike-2? Why did it not also resolve to Mike Nell -1 etc. – Priyansh Goel Jun 15 '16 at 17:19
  • You're right Priyanshi Gel! It was my mistake. The sample name is 'Mike' –  Jun 15 '16 at 17:26
  • This is a forum for programming questions. To make this a programming question, you would have to fully define the rules for how to get your desired outcome. Then we could help you with the programming. Right now, this is a "What should my business rules be?" question, which is off-topic. – Tab Alleman Jun 15 '16 at 17:42

1 Answers1

0

You can do this with FOR XML. You will have update the Table Names, Columns Names and Where Statement in both select statements. This is a variation of this Concatenation Script.

SELECT DISTINCT
    SUBSTRING(
        (
            SELECT ', '+ T1.Name  AS [text()]
            FROM dbo.TabNames T1
            WHERE T1.Name LIKE 'Mike%'
            ORDER BY T1.Name
            FOR XML PATH ('')
        ), 3, 8000) AS Names
FROM
    dbo.TabNames T2
WHERE
    T2.Name LIKE 'Mike%'
Community
  • 1
  • 1
Arleigh Reyna
  • 319
  • 1
  • 6