SQL:如何在每个字符处拆分字符串以在单独的行中显示?

时间:2017-10-11 11:13:38

标签: sql sql-server sql-server-2008

我想在每个字符处拆分一个字符串,并在一个单独的行中显示它们。我还需要一个额外的列(Col2),它应显示该字符是否为数字(如果是数字,则为1,否则为0)。

示例:

如果数据是2017年10月11日',我应该

Col1 Col2
O    0
c    0
t    0
o    0
b    0
e    0
r    0
     0
1    1
1    1
,    0
     0
2    1
0    1
1    1
7    1

4 个答案:

答案 0 :(得分:3)

试试这个:

CREATE TABLE tbSeperate (Data NVARCHAR(100))

INSERT INTO tbSeperate SELECT 'October 11, 2017'

SELECT SUBSTRING(Data,Number,1) rt , CASE WHEN TRY_CAST(SUBSTRING(Data,Number,1) AS INT) IS NULL THEN 0 
WHEN SUBSTRING(Data,Number,1) = ' ' THEN 0 ELSE 1 END c FROM tbSeperate
CROSS APPLY (SELECT DISTINCT number FROM master..spt_values WHERE number > 0 AND number <= LEN(Data))V  

答案 1 :(得分:2)

你可以使用它。

DECLARE @data VARCHAR(100) = 'October 11, 2017'

;WITH CTE AS 
(
    SELECT STUFF(@data,1,1,'') TXT, LEFT(@data,1) Col1

    UNION ALL

    SELECT STUFF(TXT,1,1,'') TXT, LEFT(TXT,1) Col1 FROM CTE
    WHERE LEN(TXT) > 0
)
select Col1, ISNUMERIC(Col1) from CTE

结果:

Col1 Col2
---- -----------
O    0
c    0
t    0
o    0
b    0
e    0
r    0
     0
1    1
1    1
,    1
     0
2    1
0    1
1    1
7    1

答案 2 :(得分:1)

一种方法使用递归CTE:

with cte as (
      select cast('October 11, 2017' as varchar(max)) as str,
             cast(NULL as varchar(max)) as letter, 0 as lev
      union all
      select substring(str, 2, len(str)), left(str, 1), lev + 1
      from cte
      where str <> ''
    )
select letter,
       (case when letter between '0' and '9' then 1 else 0 end) as is_digit
from cte
where lev > 0;

如果字符串的字符数超过99个,那么您可能希望使用最大递归选项。

Here是Rextester。

答案 3 :(得分:0)

在MySQL中使用递归CTE,我们可以实现这一目标。

以下查询将在不同行中打印每个字符串的字符。 根据要求替换表名和列名。

   WITH RECURSIVE cte
   as 
   ( 
      select 1 as n,1 as f,first_name ,'Temporary Variable' as name1  from        customer
    union
    select (n+1) as n,f,first_name,substr(first_name,n,f) as name1 from cte 
   where substr(first_name,n,n)<>""
   )
   select n,name1,first_name from cte where n<>1 and first_name='KAREN'

Screenshot