字符串使用SQL拆分

时间:2018-06-11 10:58:44

标签: sql-server

我正在使用MS SQL Server Management Studio v17。

我有一个字符串:

Primary sector: General Industries Group Sub-sector: Chemicals (incl. agri businesses) Tier:6

预期产出

Primary_Sector
通用工业集团

Sub_Sector
 化学品

我想计算两个新变量 - Primary_SectorSub_Sector,分别包含General Industries GroupChemicals。你知道推断文本的最佳技术是什么以及我将如何做到这一点?

2 个答案:

答案 0 :(得分:1)

我认为通过Substring非常简单:

DECLARE @x NVARCHAR(100) = 'Primary sector: General Industries Group Sub-sector: Chemicals (incl. agri businesses) Tier:6';

DECLARE @l INT = LEN(@x);
DECLARE @iTier INT = CHARINDEX('Tier:', @x)
DECLARE @iSubSector INT = CHARINDEX('Sub-sector:', @x)
DECLARE @iPrimarySector INT = CHARINDEX('Primary sector:', @x)

SELECT 'Tier = ' +  SUBSTRING(@x, @iTier+5, @l-(@iTier+5)+1)
SELECT 'SubSector = ' + SUBSTRING(@x, @iSubSector+11, @iTier-(@iSubSector+11))
SELECT 'PrimarySector = ' + SUBSTRING(@x, @iPrimarySector+15, @iSubSector-(@iPrimarySector+15))

答案 1 :(得分:0)

试试这个

DECLARE @Tabl AS TABLE(data nvarchar(max))
INSERT INTO @Tabl
SELECT 'Primary sector: General Industries Group Sub-sector: Chemicals (incl. agri businesses) Tier:6'

SELECT  data,
        [Primary sector],
        SUBSTRING([Sub-sector],1,CHARINDEX(')',[Sub-sector]))AS [Sub-sector],
        Tier 
FROM
(
SELECT data,
        REPLACE(SUBSTRING(data,0,CHARINDEX('Sub-sector:',data)),':',' = ') AS [Primary sector],
        REPLACE(SUBSTRING(data,CHARINDEX('Sub-sector:',data),LEN(data)),':',' = ') AS [Sub-sector]
        ,RIGHt(data,LEn('Tier:')+1) AS [Tier]
 FROM @Tabl
 )dt

演示结果:http://rextester.com/ARPH77432