如何根据' /'将包含路径的列拆分为各列?在一个选择声明?

时间:2016-10-07 15:09:47

标签: sql sql-server

Ex,Column包含此

const rollupConfig = require('../node_modules/@ionic/app-scripts/config/rollup.config');
const replace = require('rollup-plugin-replace');

console.log('Editing default ionic configuration');

const nodeEnv = JSON.stringify(process.env.NODE_ENV) || 'development';
const apiUrl = JSON.stringify(process.env.API_URL) || '';
const platform = JSON.stringify(process.env.PLATFORM) || 'android';

rollupConfig.plugins.push(replace({
    'process.env.NODE_ENV': nodeEnv,
    'process.env.API_URL': apiUrl,
    'process.env.PLATFORM': platform
}));

module.exports = rollupConfig;

使用select返回行时我想根据" /"将它们拆分为不同的列值。

2 个答案:

答案 0 :(得分:0)

我有一个可能有帮助的TVF。目前返回9个职位,但很容易扩展。

Declare @String varchar(max) = '/RS2015/DCA/Training/Summary'
Select * from [dbo].[udf-Str-Parse-Row](Stuff(@String,1,1,''),'/')

返回

Pos1    Pos2    Pos3        Pos4     Pos5   Pos6    Pos7    Pos8    Pos9
RS2015  DCA     Training    Summary  NULL   NULL    NULL    NULL    NULL

注意:我使用STUFF()来剥离第一个/。这将是可选的

这也可用于交叉申请

Select A.ID
       B.*
 From YourTable A
 Cross Apply [dbo].[udf-Str-Parse-Row](Stuff(A.PathString,1,1,''),'/') B

UDF(如果需要)

CREATE FUNCTION [dbo].[udf-Str-Parse-Row] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (
    Select Pos1 = xDim.value('/x[1]','varchar(max)')
          ,Pos2 = xDim.value('/x[2]','varchar(max)')
          ,Pos3 = xDim.value('/x[3]','varchar(max)')
          ,Pos4 = xDim.value('/x[4]','varchar(max)')
          ,Pos5 = xDim.value('/x[5]','varchar(max)')
          ,Pos6 = xDim.value('/x[6]','varchar(max)')
          ,Pos7 = xDim.value('/x[7]','varchar(max)')
          ,Pos8 = xDim.value('/x[8]','varchar(max)')
          ,Pos9 = xDim.value('/x[9]','varchar(max)')
     From (Select Cast('<x>' + Replace(@String,@Delimiter,'</x><x>')+'</x>' as XML) as xDim) A
)
--Select * from [dbo].[udf-Str-Parse-Row]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-Row]('John Cappelletti',' ')

答案 1 :(得分:0)

以下是使用dynamic sqlxml

的一种方法
DECLARE @str   VARCHAR(8000) = '/RS2015/DCA/Training/Summary',
        @start INT= 1,
        @count INT,
        @sql VARCHAR(max) = ''

SET @count = Len(@str) - Len(Replace(@str, '/', ''))

SET @sql = ';WITH Split_Names AS
            (
            SELECT CONVERT(XML,''<Names><name>'' + REPLACE(''' + Stuff(@str, 1, 1, '') + ''',''/'', ''</name><name>'') + ''</name></Names>'') AS xmlname
            )
            SELECT 
            '
WHILE @start <= @count
  BEGIN
      SET @sql +=Concat('xmlname.value(''/Names[1]/name[', @start, ']'',''varchar(500)'') as [column',@start,'], ')
      SET @start+=1
  END

SET @sql =LEFT(@sql, Len(@sql) - 1)
SET @sql+= ' FROM Split_Names'

--select @sql
EXEC( @sql) 

结果:

╔═════════╦═════════╦══════════╦═════════╗
║ column1 ║ column2 ║ column3  ║ column4 ║
╠═════════╬═════════╬══════════╬═════════╣
║ RS2015  ║ DCA     ║ Training ║ Summary ║
╚═════════╩═════════╩══════════╩═════════╝