您可以使用此处的一些方法将逗号分隔的字符串转换为单独的行来为每组值获取一个表,然后将这些表交叉连接在一起并连接这些值。
我把这个例子放在了上面链接中的 CTE 答案中:
declare @Types as varchar(max)
declare @Areas as varchar(max)
set @Types = 'DP,DPC,PC'
set @Areas = 'M1,M2,M3'
;with tmp(DataItem, Data) as (
select LEFT(@Types, CHARINDEX(',',@Types+',')-1),
STUFF(@Types, 1, CHARINDEX(',',@Types+','), '')
union all
select LEFT(Data, CHARINDEX(',',Data+',')-1),
STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where Data > ''
)
select
DataItem
into #Types
from tmp
;with tmp2(DataItem, Data) as (
select LEFT(@Areas, CHARINDEX(',',@Areas+',')-1),
STUFF(@Areas, 1, CHARINDEX(',',@Areas+','), '')
union all
select LEFT(Data, CHARINDEX(',',Data+',')-1),
STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp2
where Data > ''
)
select
DataItem
into #Areas
from tmp2
select
_Types.DataItem + '_' + _Areas.DataItem
from #Types _Types
cross join #Areas _Areas
drop table #Types
drop table #Areas
如果您需要重新加入这些,您可以在此处查看这篇文章以获取多个示例并选择最适合您的示例。