用于处理变量的SQL查询

时间:2016-10-17 15:15:55

标签: sql oracle

我有一个名为NAMES_INFO的表,其中包含以下字段

ID
NAME
ALTERNATIVE_NAME
PREFERED_NAME
REPORTING_NAME
ALAIS_NAME

现在我有了一个NAMES的新列表,需要检查上面有NAMES的每个字段以检查MATCH。所以我提出了以下SQL

SELECT * 
FROM NAMES_INFO 
WHERE ALTERNATIVE_NAME LIKE '%PETER%THOMAS%'
OR PREFERED_NAME LIKE  '%PETER%THOMAS%'
OR REPORTING_NAME LIKE '%PETER%THOMAS%'
OR ALAIS_NAME LIKE '%PETER%THOMAS%';

预计会有哪些作品。但是我需要在Excel文件中检查3000个名称。所以只需检查是否有一种更新SQL的方法,它可以处理变量并运行它。类似下面的内容

VAR1 = '%PETER%THOMAS%'
PASS TO BELOW SQL
SELECT * FROM NAMES_INFO WHERE ALTERNATIVE_NAME LIKE 'VAR1'
OR PREFERED_NAME LIKE  'VAR1'
OR REPORTING_NAME LIKE 'VAR1'
OR ALAIS_NAME LIKE 'VAR1';

我无法在DB中创建任何对象。我必须在只读环境中执行此活动。

2 个答案:

答案 0 :(得分:1)

请记住,在SQL中你不做循环,而是做集或表。因此,使用值表来检查您只需进行连接。

我不知道您使用的是什么平台,但这里是示例代码:

-- Oracle
WITH names2check(C) AS
(
   SELECT '%PETER%THOMAS%' as C FROM DUAL
    UNION ALL
   SELECT '%SECOND%FIDDLE%' as C FROM DUAL
    UNION ALL
   SELECT '%GENERIC%ALL%' as C FROM DUAL
   -- etc
    UNION ALL
   SELECT '%LAST%McLAST%' as C FROM DUAL
)
SELECT *
FROM NAME_INFO 
JOIN names2check ON 
    ALTERNATIVE_NAME LIKE names2check.C
 OR PREFERED_NAME LIKE names2check.C
 OR REPORTING_NAME LIKE names2check.C
 OR ALAIS_NAME LIKE names2check.C;

-- DB2 or MS SQL
WITH names2check(C) AS
(
   VALUES
     ('%PETER%THOMAS%'),
     ('%SECOND%FIDDLE%'),
     ('%GENERIC%ALL%'),
   -- etc
     ('%LAST%McLAST%')
)
SELECT *
FROM NAME_INFO 
JOIN names2check ON 
    ALTERNATIVE_NAME LIKE names2check.C
 OR PREFERED_NAME LIKE names2check.C
 OR REPORTING_NAME LIKE names2check.C
 OR ALAIS_NAME LIKE names2check.C;

答案 1 :(得分:0)

在Oracle中,您可以简化使用UNPIVOT

select *
from names_info
where id in (
  select id
  from names_info 
    unpivot (any_column for source_column in (alternative_name, prefered_name, reporting_name, alais_name))
  where any_column like '%PETER%THOMAS%'
);