我正在嘗試將基于主要專案的相關專案放在一起。
例如,假設我有一個非常簡單的[FRUIT]表:
| ID | 名稱 |
|---|---|
| 1 | 富士蘋果 |
| 2 | 蘋果:金冠 |
| 3 | 史密斯奶奶蘋果 |
| 4 | 血橙 |
| 5 | 橙色:普通話 |
而用戶目前正在查看“富士蘋果”。我想回傳“Apple:Golden Delicious”和“Granny Smith Apple”的行,因為它們的[Name]列的值中也包含“Apple”一詞。我想我正在尋找類似LIKE 的東西,它對字串進行更廣泛的比較,看看是否有任何相似的字符集。
我已經查看了SOUNDEX和DIFFERENCE,但它們不是我想要的,因為我的字串太長并且類似的單詞可能在字串中的任何位置。
如果沒有任何問題,如果需要,我總是可以實作一些相似性演算法;但如果 t-sql 已經內置,我不想付出努力。
注意:我知道在上面的示例中,只添加另一個具有“Apple”和“Orange”值的列和/或表會更有意義;但這不是我要問的。
uj5u.com熱心網友回復:
請嘗試以下解決方案。
它使用 XML、XQuery 和量化運算式。
有用的鏈接:量化運算式(XQuery)
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, fruit VARCHAR(200));
INSERT INTO @tbl (fruit) VALUES
('Fuji Apples'),
('Apple: Golden Delicious'),
('Granny Smith Apple'),
('Blood Orange'),
('Orange: Mandarin');
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1)
, @searchFor VARCHAR(30) = 'Fuji Apple';
SELECT t.*
, c.value('some $r in /root/source/r/text()
satisfies contains(data(/root/target)[1], $r)', 'BIT') AS Result
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><source><r><![CDATA[' REPLACE(@searchFor, @Separator, ']]></r><r><![CDATA[') ']]></r></source>'
'<target><r><![CDATA[' REPLACE(fruit, @Separator, ']]></r><r><![CDATA[') ']]></r></target></root>' AS XML)
) AS t1(c);
輸出
---- ------------------------- --------
| ID | fruit | Result |
---- ------------------------- --------
| 1 | Fuji Apples | 1 |
| 2 | Apple: Golden Delicious | 1 |
| 3 | Granny Smith Apple | 1 |
| 4 | Blood Orange | 0 |
| 5 | Orange: Mandarin | 0 |
---- ------------------------- --------
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405457.html
標籤:
下一篇:如何在組T-SQL中公開層次結構
