查找字符串中不在数据库中的名称

时间:2014-08-13 12:17:11

标签: sql string

我有两个名单:

1) In table 'Names'

   Carl
   Tom
   Dan
   Thomas
   Beneth

2) In variable @string

   Tom
   Thomas
   Ben
   John
   Peter

Tables:
Names
Columns:
NameId
Name

第一个列表在我的数据库中,但第二个列表在一个字符串中。我正在寻找一个可以从@string给我名字的查询,这些名字不在表名中。在这个例子中,这应该是:Carl,Dan,Beneth。我不知道该怎么做。如果可能的话 - 没有程序会很棒。

2 个答案:

答案 0 :(得分:1)

the function recommended by Alex K的代码调整为一次执行,您需要执行以下操作(取出@Names表并替换为您的实际表):

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 

答案 1 :(得分:1)

这是一个SQL版本(适用于Oracle),但您应该能够将其适用于其他系统。

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)