字符串到行的转换SQL Server

时间:2018-09-25 11:31:54

标签: sql sql-server split

如何将以下输入转换为SQL Server中的一行?

'e4lu50', 'e4lu10', 'e4lu11', 'e4de11', 'e4de12', 'e4nl51', 'e4es11'

预期输出

e4lu50
e4lu10
e4lu11
e4de11
e4de12
e4nl51
e4es11

我有一个功能

 CREATE FUNCTION [dbo].[BreakStringIntoRows] 
     (@CommadelimitedString VARCHAR(1000))  
 RETURNS   
     @Result TABLE (Column1 INT)  
 AS  
 BEGIN  
     DECLARE @IntLocation INT  

     WHILE (CHARINDEX(',', @CommadelimitedString, 0) > 0)  
     BEGIN  
         SET @IntLocation = CHARINDEX(',', @CommadelimitedString, 0)        

         INSERT INTO @Result (Column1)  
             --LTRIM and RTRIM to ensure blank spaces are removed
             SELECT 
                 RTRIM(LTRIM(SUBSTRING(@CommadelimitedString, 0, @IntLocation)))     

             SET @CommadelimitedString = STUFF(@CommadelimitedString, 1, @IntLocation, '')
     END  

     INSERT INTO @Result (Column1)  
         SELECT RTRIM(LTRIM(@CommadelimitedString))--LTRIM and RTRIM to ensure blank spaces are removed  

     RETURN   
 END       

和一个查询,但是问题在于它不使用带引号的输入

WITH SEG(aa) AS
(
    SELECT
        BreakStringIntoRows ('e4lu50', 'e4lu10', 'e4lu11', 'e4de11',
                             'e4de12', 'e4nl51', 'e4es11', 'e4it11')
)
SELECT * 
FROM SEG

1 个答案:

答案 0 :(得分:0)

您没有单个字符串,而是有一组由逗号分隔的8个字符串。如果您想坚持使用自己的功能,请按以下方式调用它:

with SEG(aa) as 
(select BreakStringIntoRows ('e4lu50,e4lu10,e4lu11,e4de11,e4de12,e4nl51,e4es11')
SELECT * from SEG

由于您直接在查询中指定了字符串,这样做可行吗?如果没有,请在调用之前使用REPLACE()函数删除引号。