|
假设我有两个表,两个表的列都叫Brand。例如,如果表之一有逗号分隔8 M: f2 x# r* A9 L
ACER,ASUS,HP AMD,NVIDIA,SONY作为价值。然后另一个表有。
8 v/ w3 o E) y' j- B L" DHP,GIGABYTE MICROSOFT SAMSUNG,PHILIPS作为价值。
~1 X/ {) H5 [4 g8 \+ ]( Q在我的例子中,我想比较这些表以获得所有匹配的记录ACER,ASUS,HP和HP,GIGABYTEmatch因为两者都有HP。现在,我正在使用循环来实现这一点,我想知道是否有可能在单个查询语法中实现这一点。
& G# J' P3 d2 |# ~8 z 0 Q* Y" f4 ]9 Z8 m* w3 h* }( H4 d. F
解决方案: ; H, y" t% l% p+ c2 R$ L
想要脱离循环是正确的。
. s% S0 H" U& F% N4 w3 {" {, \" p因为你在2012年,String_Split()不在桌面上。然而,野生有任何数量的拆分/分析TVF函数。
7 L4 [' R4 \" R* h$ k7 \3 _9 j示例1-没有TVF% ~% S6 }% d! E' s) `( _
Declare @T1 table (Brand varchar(50))Insert Into @T1 values ('ACER,ASUS,HP'),('AMD,NVIDIA,SONY')Declare @T2 table (Brand varchar(50))Insert Into @T2 values ('HP,GIGABYTE'),('MICROSOFT'),('SAMSUNG,PHILIPS')Select Distinct T1_Brand = A.Brand ,T2_Brand = B.Brand From ( Select Brand,B.* From @T1 Cross Apply ( Select RetVal = LTrim(RTrim(B.i.value('(./text()'varchar(max)))))) From (Select x = Cast('' replace(Brand,',','') '' as xml)) as A Cross Apply x.nodes('x') AS B(i) B ) A Join ( Select Brand,B.* From @T2 Cross Apply ( Select RetVal = LTrim(RTrim(B.i.value('(./text()[1]varchar(max)))))) From (Select x = Cast('' replace(Brand,',','') '' as xml)) as A Cross Apply x.nodes('x') AS B(i) B ) B on A.RetVal=B.RetVal示例2-使用TVF
8 e! x) _6 V) d' }Select Distinct T1_Brand = A.Brand T2_Brand = B.Brand From ( Select Brand,B.* From @T1 Cross Apply [dbo].[tvf-Str-Parse](Brand,',') B ) A Join ( Select Brand,B.* From @T2 Cross Apply [dbo].[tvf-Str-Parse](Brand,',') B ) B on A.RetVal=B.RetVal两者都会回来
- e" `7 e6 G# y qT1_Brand T2_BrandACER,ASUS,HP HP,GIGABYTEUDF(如有兴趣). Y1 o, O; c3 i L! [) w
CREATE FUNCTION [dbo].[tvf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))Returns Table AsReturn ( Select RetSeq = Row_Number() over (Order By (Select null)) RetVal = LTrim(RTrim(B.i.value('(./text()[1]varchar(max)) From (Select x = Cast('' replace((Select replace(@String,@Delimiter,'搂搂Split搂搂') as For XML Path('),'搂搂Split搂搂','') '' as xml).query('.')) as A Cross Apply x.nodes('x') AS B(i));--Thanks Shnugo for making this XML safe--Select * from [dbo].[tvf-Str-Parse]('Dog,Cat,House,Car,--Select * from [dbo].[tvf-Str-Parse]('John Cappelletti was here--Select * from [dbo].[tvf-Str-Parse]('this,is,,for,, |
|