0

I have two lists of names:

1) In table 'Names'

   Carl
   Tom
   Dan
   Thomas
   Beneth

2) In variable @string

   Tom
   Thomas
   Ben
   John
   Peter

Tables:
Names
Columns:
NameId
Name

The first list is in my database, but the second is in a string. I'm looking for a query that can give me names from @string, which are NOT in table Names. In this example, this should be: Carl, Dan, Beneth. I have no idea how to do that. If it's possible - no-procedure will be great.

jvdhooft
  • 657
  • 1
  • 12
  • 33

2 Answers2

1

Adapting the code of the function recommended by Alex K to just a single execution, you'll need to do the following (take out the @Names table and replace with your actual table):

DECLARE @List VARCHAR(100)
SET @List = 'Tom, Thomas, Ben, John, Peter'

DECLARE @Names TABLE (Name VARCHAR(10))
INSERT INTO @Names (Name) VALUES ('Tom')
INSERT INTO @Names (Name) VALUES ('Thomas')

SELECT [Value] 
FROM 
  ( 
    SELECT 
        [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],CHARINDEX(',', @List + ',', [Number]) - [Number])))
    FROM 
      (
        SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
        FROM sys.all_objects
      ) AS x
    WHERE 
        Number <= LEN(@List) AND 
        SUBSTRING(',' + @List, [Number], LEN(',')) = ','
  )  y
     LEFT JOIN 
    @Names n ON 
        y.Value = n.Name
WHERE n.Name IS NULL 
Community
  • 1
  • 1
AHiggins
  • 7,029
  • 6
  • 36
  • 54
1

This is a SQL version (for Oracle) but you should be able to adapt it to other systems.

select names.name from (
select 1 as NameId, 'Carl' as Name from dual
union
select 2, 'Tom' from dual
union
select 3, 'Dan' from dual
union
select 4, 'Thomas' from dual
union
select 5, 'Beneth' from dual) names
, (select 'Tom Thomas Ben John Peter' as list from dual) string
where length(replace(list, name, '')) =  length(string.list)