使用子串和& patindex将字符串的一部分提取到新列MS SQL

时间:2016-01-12 16:44:45

标签: sql-server

我在MS SQL中有一个字段连接,如TopLevel> MidLevel> Lowestlevel tis字符串的长度不同。有时字符串较短,只有topLevel或顶级> MidLevel 我需要做的是在">"并将文本放入新的列/字段中。 我尝试过的parsename很有效,直到长度开始变化。

我所拥有的并没有错误,但也没有产生任何东西 - 除了3个空列。

SELECT 
[program_Name]

,substring([Program_Name],1, patindex([Program_Name], '>')) as UP
,substring([Program_Name],patindex([Program_Name], '>*>') - patindex([Program_Name], '>'), patindex([Program_Name], '>*>')) as MID
,substring([Program_Name],patindex([Program_Name], '>*>*>') - patindex([Program_Name], '>*>'), patindex([Program_Name], '>*>')) as LOW


 */
  FROM [dbo].[MSP_EpmProject_UserView]

1 个答案:

答案 0 :(得分:3)

使用PARSENAME(只要数据本身不包含.):

CREATE TABLE #tab(col NVARCHAR(100));
INSERT INTO #tab(col) VALUES( 'TopLevel>MidLevel>Lowestlevel');

SELECT 
  PARSENAME(REPLACE(col, '>', '.'),3) AS UP,
  PARSENAME(REPLACE(col, '>', '.'),2) AS MID,
  PARSENAME(REPLACE(col, '>', '.'),1) AS LOW
FROM #tab;

LiveDemo

输出:

╔══════════╦══════════╦═════════════╗
║    UP    ║   MID    ║     LOW     ║
╠══════════╬══════════╬═════════════╣
║ TopLevel ║ MidLevel ║ Lowestlevel ║
╚══════════╩══════════╩═════════════╝

说明:

  • 使用PARSENAME,您最多可以达到4个级别
  • PARSENAME适用于SYSNAME 的别名NVARCHAR(128)
  • 如果您有TOP.DATA>MID.DATA>LOW.DATA,则可以先将.更改为^,然后>更改为.,最后再更改^.

LiveDemo2

修改

使用PARSENAME有点笨拙,所以让我们以旧时尚的方式做事:

CREATE TABLE #tab(col NVARCHAR(1000));
INSERT INTO #tab(col) VALUES( 'TOP>MID>LOW'), ('A>B>C>D');

WITH tally AS
(
SELECT TOP 5000 rn = ROW_NUMBER() OVER(ORDER BY (SELECT 1))
  FROM master..spt_values
), cte AS
( SELECT col, s.val, pos
  FROM #tab t
  CROSS APPLY(
    SELECT SUBSTRING('>' + t.col + '>', rn + 1,
           CHARINDEX('>', '>' + t.col + '>', rn + 1) - rn -1)AS VAL,
           pos = ROW_NUMBER() OVER (ORDER BY rn)
    FROM tally
    WHERE rn <= LEN('>' + t.col + '>') - 1
      AND SUBSTRING('>' + t.col + '>', rn, 1) = '>') AS s(val, pos)
)
SELECT col, [1] AS UP, [2] AS MID, [3] AS LOW
FROM cte
PIVOT (MAX(val) FOR pos IN ([1],[2],[3],[4],[5])) AS pvt;

现在您可以拥有更多级别(只需将[4],[5], ...添加到SELECT列列表),依此类推。

LiveDemo3