我正在使用MS SQL Server Management Studio v17。
我有一个字符串:
Primary sector: General Industries Group Sub-sector: Chemicals (incl. agri businesses) Tier:6
预期产出
Primary_Sector
通用工业集团
Sub_Sector
化学品
我想计算两个新变量 - Primary_Sector
和Sub_Sector
,分别包含General Industries Group
和Chemicals
。你知道推断文本的最佳技术是什么以及我将如何做到这一点?
答案 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