Sql query to split one column into two columns

北慕城南 提交于 2019-12-13 04:23:13

问题


I have one single column as project name, the data in project name

1.1.1 chapter1
1.1.2 chapter2

I want to divide that single column into two columns as

Major   Minor
1.1     .1 chapter1
1.1     .2 chapter2

the datatype of my project name column is nvarchar, I am using sql 2005

Any help?


回答1:


Something like this

declare @x nvarchar(500) = '1.1.1 chapter1'

select substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1) as Major,
       substring(@x,charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x))) as Minor

Substitute @x in your query ..

and the fiddle for it : http://sqlfiddle.com/#!3/d41d8/4424/0

updated with the . in front and proof to error

declare @x nvarchar(500) = '1.1.1 chapter1'

select @x,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1)
        else 'Cannot be parsed'
   end,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x))+1)
        else 'Cannot be parsed'
   end

and without the . in front

declare @x nvarchar(500) = '1.1.1 chapter1'

select @x,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1)
        else 'Cannot be parsed'
   end,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1+charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x)))
        else 'Cannot be parsed'
   end

http://sqlfiddle.com/#!3/d41d8/4430/0




回答2:


select substring(ProjectName,1,charindex('.',ProjectName,charindex('.',@t)+1)) as Major


来源:https://stackoverflow.com/questions/12435469/sql-query-to-split-one-column-into-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!