拆分文本值插入另一个单元格

时间:2014-02-04 07:53:01

标签: sql sql-server database tsql

我希望从NAME列拆分文本,并为每行插入逗号分隔数据到PARCA列。例如:

name            parca
----            -------------
john            j,jo,joh,john

代码:

DECLARE @i int = 0
WHILE @i < 8
BEGIN 
SET @i = @i + 1
update export1 set PARCA = cast ( PARCA as nvarchar(max))  + cast (substring(NAME,1,@i) as nvarchar(max) ) +',' 
FROM export1 
end

有两件事我不能做;

  1. 我无法将@i值均衡为名称行计数
  2. 我无法检查NAME列是否为PARCA列中的值

4 个答案:

答案 0 :(得分:1)

DECLARE @Count INT,@I INT
SET @I = 1
SET @Count = LEN('SURESH')
DECLARE @N VARCHAR(2000)
SET @N = ''
WHILE @Count > 0
BEGIN
    SET  @N = @N + ','+SUBSTRING('SURESH',1,@I)
    SET  @I = @I+1
    SET @Count  = @Count -1
END

SELECT SUBSTRING(@N,2,2000)

上面的代码只是一个示例.'SURESH'是你的名字字段。你可以从中传递你自己的名字值。而不是最终选择你可以把你更新。

答案 1 :(得分:1)

创建此功能:

create function f_parca
(
 @name varchar(100)
) returns varchar(max)
as
begin
declare @rv varchar(max) = ''

if @name is not null
select top (len(@name)) @rv += ','+ left(@name, number + 1) 
from master..spt_values v
where type = 'p'

return stuff(@rv, 1,1,'')
end

测试功能

select dbo.f_parca('TClausen')

结果:

T,TC,TCl,TCla,TClau,TClaus,TClause,TClausen

像这样更新你的桌子:

UPDATE export1
SET PARCA = dbo.f_parca(name)

答案 2 :(得分:0)

试试这个,这个查询会按预期将单词分成字符行,然后你可以合并成一行

DECLARE @Name AS Varchar(100)='Naveen'  

;with cte as
(
select 1 AS Counter,CAST(SUBSTRING(@Name, 1, 1) AS Varchar(100)) Name
union all 
select Counter+1,CAST((Name + ',' + SUBSTRING(@Name, Counter+1, 1))AS Varchar(100)) Name
from cte
where Len(Name) < Len(@Name) + (Len(@Name) -1)
)
select
    Name
   from cte
option(MAXRECURSION 0) 

答案 3 :(得分:0)

-- This query will give you exactly what you are looking for, use Emp Table with Ename as     column    

;with cte as
(
select  1 AS Counter,EName,CAST(SUBSTRING(E.EName, 1, 1) AS Varchar(100)) Name
        From EMP E 
union all 
select Counter+1,E.EName,CAST((Name + SUBSTRING(E.EName, Counter+1, 1))AS Varchar(100)) Name
From EMP E
     INNER JOIN CTE C ON C.Ename=E.EName
where Len(Name) < Len(E.EName) 
)
select EName AS Name,
   STUFF((    SELECT ',' + Name AS [text()]                        
                        FROM CTE A
                        WHERE
                        A.EName = cte.EName
                        FOR XML PATH('')
                        ), 1, 1, '' )                       
            AS Parca    
   from cte 
   Group By EName
   Order By EName
   option(MAXRECURSION 0)