简体   繁体   English

SQL Server:基于定界符拆分值并在运行时进行匹配

[英]SQL Server : split value based on delimiter and match at run-time

I have 2 simplified tables (all columns are varchar ). 我有2个简化表(所有列均为varchar )。 Some rows in T1_TAB for F2 contain multiple values separated by ; F1的T1_TAB某些行包含多个值,这些值之间用;隔开; , some do not have separators at all as shown below (sometimes ; might also appear at the beginning and/or at the end). ,有些根本没有如下所示的分隔符(有时;可能还会出现在开头和/或结尾)。 F2 in T2_TAB always has a single value. T2_TAB F2始终具有单个值。

I need to be able to pull rows from ether table based on single selection from one table and likeliness on F2 columns. 我需要能够基于一个表的单一选择和F2列的相似性从以太表中提取行。

T1_TAB T1_TAB

F0   |  F2
--------------
1          ;30
2       ;10;20;30
3          ;20;30;
4          10

T2_TAB T2_TAB

F1   |  F2
-------------
100       10    
200       20      
300       30

I can do: 我可以:

SELECT T1.F0
FROM T1_TAB T1 
LEFT JOIN T2_TAB T2
ON T2.F2 LIKE '%' + T1.F2 + '%'
WHERE T2.F1 = '200'

This would bare result: 这将是结果:

2
3

Now, I need to do the opposite. 现在,我需要做相反的事情。 For instance: 例如:

Based on condition WHERE T1.F0 = 3 , I need to pull from T2 rows with F1 equals 200 and 300 respectively. 基于条件WHERE T1.F0 = 3 ,我需要从T2行中分别提取F1等于200和300。 I guess I need to somehow split ;20;30; 我想我需要以某种方式拆分; 20; 30; by a ";" 用“;” and do the loop to match each value separately at run-time disregarding blank tokens. 并进行循环以在运行时分别匹配每个值,而无需考虑空白令牌。

You can create a function which converts the semicolon-separated string into a table of values: 您可以创建一个将分号分隔的字符串转换为值表的函数:

create function CreateTableFromList(@Values varchar(1000))
returns @table table (id int)
as
begin
declare @p int = 1, @q int = 1, @n int = len(@Values)

while @p<@n begin
  set @q = CHARINDEX(';',@Values,@p)
  if @q=0 set @q=@n + 1
  if @q > @p 
    insert into @table values (cast(substring(@Values,@p,@q-@p) as int))
  set @p= @q + 1
end
return
end

and then 接着

select T2.F1 
  from T2
where T2.F2 in (
  select ID 
    from T1 
         cross apply dbo.CreateTableFromList(T1.F2) 
  where T1.F0=3
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM