Sql 从单列中获取多列的代码

Sql code to get multiple columns out of single column

我有一个像 "AP.1.12345.ABCD.20150523_0523.20150524_0223" 这样的专栏。

我可以根据“.”将列分成多列吗?

对于上面的示例列,输出将类似于

AP 1 12345 ABCD 20150523_0523 20150524_0223.

因此单列将转换为6列。

在网络上搜索 split() 函数。这并不难。 Google "SQL Server split" 你会有很多选择。您实际上想要一个给您第二个 return 值的值,即子字符串在较大字符串中的位置。

然后:

select t.*, newcols.*
from table t cross apply
     (select max(case when pos = 1 then val end) as col1,
             max(case when pos = 2 then val end) as col2,
             max(case when pos = 3 then val end) as col3,
             max(case when pos = 4 then val end) as col4,
             max(case when pos = 5 then val end) as col5,
             max(case when pos = 6 then val end) as col6             
      from dbo.split(t.col, '.') as s(val, pos)
      group by t.col
     ) newcols;

您还可以编写一个函数来执行如下操作:

DECLARE @Col    VARCHAR(64),
        @DynSQL VARCHAR(MAX)

SET @Col = 'AP.1.12345.ABCD.20150523_0523.20150524_0223'
SET @DynSQL = 'SELECT '''+REPLACE(@Col,'.',''',''')+''''

exec(@DynSQL)

这可以处理任意数量的 delimiters/columns。

感谢大家的建议和解决方案。 我得到了解决方案。经过一些试验,假设该列如前所述,我使用 substringcharindex 来获得所需的结果。 尽管查询看起来有点大,但仍然有效。

与其使用函数,我更希望它是一个简单的查询。

不过需要检查查询的性能。