在SQL中使用[like] like in子句?

时间:2013-07-05 05:31:40

标签: sql sql-server sql-server-2008

USE tempdb

CREATE TABLE A
(
     id INT,
     a_desc VARCHAR(100)
)

INSERT INTO A 
VALUES (1, 'vish'),(2,'hp'),(3,'IBM'),(4,'google')

SELECT * FROM A

CREATE TABLE B
(
     id INT,
     b_desc VARCHAR(100)
)

INSERT INTO B 
VALUES (1, 'IBM[SR4040][SR3939]'),(2,'hp[GR3939]')

SELECT * FROM B

SELECT * 
FROM A 
WHERE a_desc LIKE (SELECT b_desc FROM B) -- IN with LIKE problem here

表B中的结束字符串不一样,所以我不能使用trim方法 删除某些字符并在In子句中匹配。

- 上面的抛出错误子查询返回的值超过1个

- 我在两个表中都有一千行只是为了示例目的我创建了这个例子

--excepted output 
--IBM
--hp 

- 来自A表

4 个答案:

答案 0 :(得分:5)

试试这个 -

<强>查询:

SELECT * 
FROM A
WHERE EXISTS(
    SELECT 1
    FROM B
    WHERE b_desc LIKE '%' + a_desc + '%'
)

<强>输出:

id          a_desc
----------- ----------
2           hp
3           IBM

执行计划:

proff

扩展统计信息:

stat

<强>更新

SELECT A.*, B.* 
FROM A
OUTER APPLY (
     SELECT * 
     FROM B
     WHERE b_desc LIKE '%' + a_desc + '%' 
) B
WHERE b_desc IS NOT NULL

答案 1 :(得分:3)

你可以简单加入:

SELECT distinct a.* 
from A inner join b on b.b_desc like '%' + a.a_desc + '%' 

答案 2 :(得分:3)

试试这个,这将为您提供准确的输出

select distinct a.a_desc 
from A r 
join B b
on b.b_desc like  a.a_desc +'%'

答案 3 :(得分:1)

SELECT * 
FROM A , B
WHERE a_desc LIKE '%' + b_desc + '%'