将一条记录分成多条记录

时间:2016-04-22 08:46:14

标签: sql sql-server tsql

我需要一个查询来改变这个:

col1 col2 col3
1    2    abc
3    4    cd
4    5    null

到此

col1 col2 col3
1    2    a
1    2    b
1    2    c
3    4    c
3    4    d
4    5    NULL

谢谢。

2 个答案:

答案 0 :(得分:3)

尝试这样

编辑正在运行的数字的语法

EDIT2 JamieD77评论将TOP纳入数字的创建

CREATE FUNCTION dbo.SingleChars(@SomeText NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN
WITH nr10 AS
(
    SELECT * FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS tbl(A)
)
,RunningNumbers AS
(
    SELECT TOP (ISNULL(LEN(@SomeText),0)) ROW_NUMBER() OVER(ORDER BY (SELECT(NULL))) AS Nmbr FROM nr10,nr10 AS a,nr10 AS b,nr10 AS c,nr10 AS d,nr10 AS e,nr10 AS f,nr10 AS g
)
SELECT SUBSTRING(@SomeText,Nmbr,1) AS TheCharacter
      ,ASCII(SUBSTRING(@SomeText,Nmbr,1)) AS ASCII_Code
FROM RunningNumbers;

测试

SELECT * FROM dbo.SingleChars('This is a test');

结果

T   84
h   104
i   105
s   115
    32
i   105
s   115
    32
a   97
    32
t   116
e   101
s   115
t   116

现在你的问题

DECLARE @tbl TABLE(col1 INT, col2 INT, col3 VARCHAR(100));
INSERT INTO @tbl VALUES(1,2,'abc'),(3,4,'cd'),(4,5,NULL);

SELECT col1,col2,sc.TheCharacter
FROM @tbl
OUTER APPLY dbo.SingleChars(col3) AS sc;

结果

1   2   a
1   2   b
1   2   c
3   4   c
3   4   d
4   5   NULL

答案 1 :(得分:2)

在MSSQL中,您可以使用recursive CTE。只需在每一步上写一个左侧字母:

WITH T1 as 
(
  SELECT col1,col2,LEFT(col3,1) as col4, SUBSTRING(col3,2,10000) as col3 
         FROM Table1
  UNION ALL
  SELECT col1,col2,LEFT(col3,1) as col4, SUBSTRING(col3,2,10000) as col3 
         FROM T1 WHERE Col3 <> ''
)

SELECT col1,col2,col4 FROM T1 ORDER BY col1,col2;

又一个问题:

WITH T1 as 
(
  SELECT col1,col2,LEFT(col3,1) as col4, col3, 2 as nextPoint  
         FROM Table1
  UNION ALL
  SELECT col1,col2,SUBSTRING(col3,nextPoint,1) as col4, col3, 
         nextPoint+1 as nextPoint  
         FROM T1 WHERE LEN(col3)>=nextPoint
)
SELECT col1,col2,col4 FROM T1 ORDER BY col1,col2;