使用动态字符串

时间:2014-01-03 06:59:59

标签: sql sql-server select left-join case

我在SQL server 2008 r2中有2个表

+----+-----------------+
| id | txt             |
+----+-----------------+
|  1 | {115467}Ruwan   |
|  2 | {7877878787}pat |
+----+-----------------+

+----+------------+
| id | pid        |
+----+------------+
|  1 |     115467 |
|  2 | 7877878787 |
|  3 |   78787878 |
+----+------------+

我需要比较t1的txt和t2的pid。从t1.txt我需要内部的东西{只考虑 所以我的输出就像

+----+------------+---------+
| id | pid        | matches |
+----+------------+---------+
|  1 |     115467 | yes     |
|  2 | 7877878787 | yes     |
|  3 |   78787878 | no      |
+----+------------+---------+

目前我做了以下事情:

$sql='SELECT pid  FROM t2";
//fetch all pid on array and then inside loop
begin loop
$sql1="select * from t1 where txt like %$array_of_pid[$i]%"; 

有没有有效的方法?

5 个答案:

答案 0 :(得分:2)

试试这个:

SELECT t1.id, t1.pid, (CASE WHEN t2.id IS NULL THEN 'no' ELSE 'yes' END) matches 
FROM temp2 t1
LEFT OUTER JOIN temp t2 ON t2.txt LIKE '%{' + CAST(t1.pid AS VARCHAR(10)) + '}%'

检查SQL FIDDLE DEMO

<强>输出

| ID |        PID | MATCHES |
|----|------------|---------|
|  1 |     115467 |     yes |
|  2 | 7877878787 |     yes |
|  3 |   78787878 |      no |

答案 1 :(得分:1)

查询:

  select t2.pid
  from   t2
  join   t1
  on     t1.txt like '%{' + t2.pid + '}%'
  order
  by     t2.id

答案 2 :(得分:1)

试试这个 -

DECLARE @temp TABLE (id INT PRIMARY KEY, txt VARCHAR(50))
INSERT INTO @temp (id, txt)
VALUES (1, '{115467}Ruwan'), (2, '{7877878787}pat')

DECLARE @temp2 TABLE (id INT PRIMARY KEY, pid BIGINT)
INSERT INTO @temp2 (id, pid)
VALUES (1, 115467), (2, 7877878787), (3, 78787878)

SELECT
    id, 
    pid, 
    matches = ISNULL((
        SELECT TOP 1 'yes' 
        FROM @temp t 
        WHERE t.txt LIKE '%' + CAST(t2.pid AS VARCHAR(10)) + '%'
    ), 'no')
FROM @temp2 t2

输出 -

id          pid                  matches
----------- -------------------- -------
1           115467               yes
2           7877878787           yes
3           78787878             no

答案 3 :(得分:1)

试试这个

select 
t2.id,
t2.pid,
CASE    
    when t1.txt is NULL THEN 'no' 
    ELSE 'YES' 
END AS matches 
  from   t2
  left join   t1
  on     (t1.txt like '%{'+t2.pid+'}%')

结果

id  pid         matches
1   115467      YES
2   7877878787  YES
3   78787878    no

答案 4 :(得分:0)

SQL代码看起来像这样

SELECT t2.id, t2.pid, CASE WHEN PATINDEX('%' + t2.pid + '%', t1.txt) > 0 THEN 'yes' ELSE 'no' END AS matches 
FROM t1 
LEFT JOIN t2 ON t1.id = t2.id

修改 如果你害怕在curleys之外可能有数学字符,你可以将你的PATINDEX更改为

PATINDEX('%{' + t2.pid + '}%', t1.txt) > 0