sql server - format a wbs column in sql -


how split format wbs column have prefix of zeroes using sql?

example: 1.2.15 1.002.015

sample wbs column content:

 - 1.1  - 1.1.1  - 1.1.2  - 1.1.3  - 1.2 

not beautiful code on earth, trick:

declare @str varchar(100) = '1.2.15' declare @format varchar(10) = '000'  declare @p1 varchar(10) declare @p2 varchar(10) declare @p3 varchar(10) declare @p4 varchar(10)  declare @parts int = 1 + len(@str) - len(replace(@str, '.', ''))  select @p1 = parsename(@str, @parts) select @p2 = parsename(@str, @parts - 1)  select @p3 = parsename(@str, @parts - 2)  select @p4 = parsename(@str, @parts - 3)  select @p2 = format(cast(@p2 int), @format) select @p3 = format(cast(@p3 int), @format) select @p4 = format(cast(@p4 int), @format)  select isnull(@p1, '') + isnull('.' + @p2, '') + isnull('.' + @p3, '') + isnull('.' + @p4, '') -- output 1.002.015 

the key use parsename function. it's intended parsing qualified sql object name, here use wbs. first find number of points know how many parts has, function's second parameter part counting end. way can main version in @p1, next 1 in @p2, etc.

then trick add leading zeroes, , concatenate numbers, avoiding nulling string if 1 of them null.

limitations:

  1. only 4 parts (can't use 1.2.15.6.3)
  2. must valid, no spaces , no . @ end

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

Qt QGraphicsScene is not accessable from QGraphicsView (on Qt 5.6.1) -

What is happening when Matlab is starting a "parallel pool"? -