String_Split 可以用在 VIEW 中吗?

Can String_Split be used in a VIEW?

我有一个 table,在单个列中有多个 IP 地址,用逗号分隔,我正在使用以下查询,它在 select 中使用时效果很好,但是当我尝试做一个视图它不起作用,它给我错误

Invalid Object name 'string_split'.

string_split可以在视图中实际使用吗?我可以使用 SP,但它确实有助于它的视图,因为我需要将此结果与其他视图和 UNION ALL

进行多次连接
SELECT 
      distinct [ColumnA]
      ,[ColumnB]
      ,cs.value as IPs
  FROM [table] as A
  cross apply string_split( 
    replace(
    replace(
            replace(
                replace([value], '-', ',')
                , ';', ',')
            , '_', ',')
            , ' ', ',')
    , ',')cs
  where A.[value] <> ''
  and cs.value like '%.%.%.%' --and cs.value like '%host%'
  order by 3

数据通常也有很多垃圾文本,比如系统或其他词,所以我用替换过滤掉它们,所以 string_split 也将其拆分,然后我使用 where 删除所有内容那不是 IP

数据示例

ColumnA ColumnB IPs
SomeText MoreText 10.10.10.10,10.10.10.11,10.10.10.12

用作查询时的结果示例

ColumnA ColumnB IPs
SomeText MoreText 10.10.10.10
SomeText MoreText 10.10.10.11
SomeText MoreText 10.10.10.12

您的查询在 视图 中运行良好,如下所示。请注意,SQL Server 2017 引入了 Translate,您可以使用它来代替嵌套的 Replace 函数

create or alter view test as 

select ColumnA, ColumnB, cs.[value] as IPs
from t
cross apply string_split( translate(IPs, '-;_ ', ',,,,'),',')cs
where cs.[value] <> ''
and cs.value like '%.%.%.%' 

GO

select * from test
order by IPs