sql-server – 如何解析字符串并从中创建多个列?

前端之家收集整理的这篇文章主要介绍了sql-server – 如何解析字符串并从中创建多个列?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含名称值对的varchar(max)字段,在每行中我都有名称Underscore Value.

我需要对它进行查询,以便它返回两列中的Name,Value对(因此通过解析文本,删除下划线和“new line”char.

所以从此

select NameValue from Table

我在哪里得到这个文字

Name1_Value1
Name2_Value2
Name3_Value3

我想有这个输出

Names  Values
=====  ======
Name1  Value1
Name2  Value2
Name3  Value3

解决方法

SELECT substring(NameValue,1,charindex('_',NameValue)-1) AS Names,substring(NameValue,NameValue)+1,LEN(NameValue)) AS Values
FROM Table

编辑:
放入函数或存储过程与temp表结合使用的东西应该适用于多行,具体取决于行分隔符,你应该在开始之前删除CHAR(13):

DECLARE @helper varchar(512)
DECLARE @current varchar(512)
SET @helper = NAMEVALUE
WHILE CHARINDEX(CHAR(10),@helper) > 0 BEGIN
    SET @current = SUBSTRING(@helper,CHARINDEX(CHAR(10),NAMEVALUE)-1)
    SELECT SUBSTRING(@current,CHARINDEX('_',@current)-1) AS Names,SUBSTRING(@current,@current)+1,LEN(@current)) AS Names
    SET @helper = SUBSTRING(@helper,@helper)+1,LEN(@helper))
END
SELECT SUBSTRING(@helper,@helper)-1) AS Names,SUBSTRING(@helper,LEN(@helper)) AS Names
原文链接:https://www.f2er.com/mssql/83254.html

猜你在找的MsSQL相关文章