子串sql查询

时间:2014-07-07 07:37:05

标签: sql sql-server substring

以下查询将返回

PR-2014-00006-02

查询:

select PRItemNo 
from tPRItem
order by PRItemNo ASC

我想要子字符串,例如我将返回以下结果

col1   col2   col3    col4 
PR     2014   00006   02

2 个答案:

答案 0 :(得分:4)

使用 PARSENAME

   --Using PARSENAME 
   SELECT PARSENAME(REPLACE(PRItemNo ,'-','.'),4) col1, 
          PARSENAME(REPLACE(PRItemNo ,'-','.'),3) col2, 
          PARSENAME(REPLACE(PRItemNo ,'-','.'),2) col3, 
          PARSENAME(REPLACE(PRItemNo ,'-','.'),1) col4
   FROM Table1

<强> Fiddle Demo


输出

COL1    COL2    COL3    COL4
PR      2014    00006   02

答案 1 :(得分:0)

declare @t VARCHAR(30)= 'PR-2014-00006-02'
SELECT SUBSTRING(@t,CHARINDEX(@t,'-'),3),
SUBSTRING(substring(@t, charindex('-',@t) + 1,len(@t) - charindex('-',@t)),0,CHARINDEX('-',@t)+2),
RIGHT(substring(@t, charindex('-',@t) + 1,len(@t) - charindex('-',REVERSE(@t))-CHARINDEX('-',@t)),5),
 REVERSE(LEFT(reverse(@t), charindex('-', reverse(@t)) - 1))