Sql-Server

從條件模式中獲取匹配部分

  • July 17, 2019

我有一張這樣的桌子:

|id|key    |value      |
------------------------
| 0|name   |Homer      |
| 1|surname|Simpson    |
| 2|town   |Springfield| 

我正在執行這個查詢:

SELECT *
FROM Search
WHERE [value] LIKE '%m%'
OR [value] like '%p%'

有沒有機會知道,這兩個條件中的哪一個匹配?

一個語句中(因此單獨執行每個條件)。

因此,例如這樣的結果:

|id|key    |value      |match  | 
--------------------------------
| 0|name   |Homer      |%m%    |
| 1|surname|Simpson    |%m%,%p%|
| 2|town   |Springfield|%p%    |

http://sqlfiddle.com/#!18/bc0b1/3/0

編輯: 結果也可能是這樣的:

|id|key    |value      |match  | 
--------------------------------
| 0|name   |Homer      |%m%    |
| 1|surname|Simpson    |%m%    |
| 1|surname|Simpson    |%p%    |
| 2|town   |Springfield|%p%    |

編輯2: 條件可能不止兩個,因此通用方法(如果可能)會很棒

WITH 
cte AS ( SELECT value AS pattern            -- or TRIM(value)
        FROM STRING_SPLIT('%m%,%p%', ',')  -- comma is NOT allowed in a pattern
                                           -- or alter your delimiter
      )
SELECT Search.[id], 
      Search.[key], 
      Search.[value], 
      STRING_AGG(cte.pattern, ',') [match]
FROM Search, 
JOIN cte ON Search.[value] LIKE cte.pattern -- or LEFT JOIN
GROUP BY Search.[id], 
        Search.[key], 
        Search.[value]

小提琴

Possibe CTE replace 可在以前的伺服器版本CHAR(9)上使用(用作分隔符,在 cte 之前@pattern聲明必須是從客戶端作為文字傳輸的查詢參數):

DECLARE @pattern VARCHAR(64) = '%m%'+CHAR(9)+'%p%';

WITH cte AS ( SELECT LEFT(@pattern,CHARINDEX(CHAR(9),@pattern)-1) pattern, 
                    SUBSTRING(@pattern, CHARINDEX(CHAR(9),@pattern)+1, LEN(@pattern)) slack
             UNION ALL
             SELECT LEFT(slack,CHARINDEX(CHAR(9),slack)-1), 
                    SUBSTRING(slack, CHARINDEX(CHAR(9),slack)+1, LEN(slack))
             FROM cte
             WHERE CHARINDEX(CHAR(9),slack) > 0
             UNION ALL
             SELECT slack, ''
             FROM cte
             WHERE CHARINDEX(CHAR(9),slack) = 0
               AND slack != ''
           )

小提琴

STRING_AGG() 也必須替換…

引用自:https://dba.stackexchange.com/questions/243061