比较字符串的多个部分,在两个表之间分隔字符“”

时间:2017-01-13 16:14:21

标签: sql sql-server

我有两个带字符串的表。现在,这些字符串由"分隔的不同部分组成。例如:

表1:

---------------------
| 1 | hello"world   |
---------------------
| 2 | hows"life"bro |
---------------------

表2:

-----------------------
| 1 | world"hello     |
-----------------------
| 2 | hows"bro"life   |
-----------------------

目前我收到了这样的查询:

select * from table1 inner join table2 on table1.id = table2.id where table1.colum2 = table2.colum2

我需要的查询应该显示两行,因为如果您更改了table1中的helloworld,那么得到{2}表格确实包含的world"hello。我怎样才能做到这一点?

提前致谢

2 个答案:

答案 0 :(得分:1)

您需要使用拆分字符串函数来执行此操作

;WITH tab1
     AS (SELECT *
         FROM   (VALUES ( 1,'hello"world' ),
                        (2,'hows"life"bro' )) t1 (id, NAME)
                CROSS apply (SELECT *
                             FROM   Delimitedsplit8k(t1.NAME, '"')) cs),
     tab2
     AS (SELECT *
         FROM   (VALUES ( 1,'world"hello' ),
                        (2,'hows"bro"life' )) t2 (id, NAME)
                CROSS apply (SELECT *
                             FROM   Delimitedsplit8k(t2.NAME, '"')) cs)
SELECT DISTINCT t1.id,
                t1.NAME,
                t2.id,
                t2.NAME
FROM   tab1 t1
       JOIN tab2 t2
         ON t1.Item = t2.Item 

从此处创建拆分字符串

Tally OH! An Improved SQL 8K “CSV Splitter” Function

答案 1 :(得分:0)

您可以将column2转换为xml并使用xquery对值进行排序并进行比较。

declare @T1 table (id int, col varchar(max))
insert into @T1 (id, col) values (1, 'hellow"world'), (2, 'a"b"c')

declare @T2 table (id int, col varchar(max))
insert into @T2 (id, col) values (1, 'world"hellow'), (2, 'b"c"a')

select *
from @T1 as t1
inner join @T2 as t2 on t1.id = t2.id
where 
    cast('<a>' + replace(t1.col, '"', '</a><a>') + '</a>' as xml).query('for $x in /a order by $x return string($x)').value('/', 'varchar(max)') =
    cast('<a>' + replace(t2.col, '"', '</a><a>') + '</a>' as xml).query('for $x in /a order by $x return string($x)').value('/', 'varchar(max)')