小编典典

分割字符串后将值插入表中

sql

我想在员工表中插入值。这些值以字符串格式~分隔

例如: AA~B~123

我正在使用以下功能拆分

CREATE FUNCTION [db_owner].[FN_Split] (@String varchar(8000), @Delimiter char(1))
   returns @temptable TABLE (items varchar(8000))        
   as        
   begin        
       declare @idx int        
        declare @slice varchar(8000)

        select @idx = 1        
            if len(@String)<1 or @String is null  return

       while @idx!= 0        
       begin        
           set @idx = charindex(@Delimiter,@String)        
           if @idx!=0        
               set @slice = left(@String,@idx - 1)        
           else        
              set @slice = @String

           if(len(@slice)>0)   
               insert into @temptable(Items) values(@slice)

           set @String = right(@String,len(@String) - @idx)        
           if len(@String) = 0 break        
       end    
   return        
   end

现在我得到输出为

SELECT * FROM db_owner.FN_Split('AA~B~123','~')

输出

items
______
AA
B
123

现在我被困在这里

如何在员工表中插入以上值???

喜欢

insert into employee (name,add,phone)
values('AA','B','123');

请指导。

尝试了这个但没有用

insert into employee
SELECT * FROM db_owner.FN_Split('AA~BB~CC','~')

错误

Msg 213, Level 16, State 1, Line 1
Column name or number of supplied values does not match table definition.

阅读 168

收藏
2021-05-23

共1个答案

小编典典

如果您可以像这样在存储过程中添加一个小计数器,那么生活会更轻松:

CREATE FUNCTION [db_owner].[FN_Split] (@String varchar(8000), @Delimiter char(1))      
   returns @temptable TABLE (orderId int,items varchar(8000))        
   as        
   begin        
       declare @idx int        
       declare @slice varchar(8000)        
       declare @orderId int = 0 --<added a counter

        select @idx = 1        
            if len(@String)<1 or @String is null  return

       while @idx!= 0        
       begin        
           set @idx = charindex(@Delimiter,@String)        
           if @idx!=0        
               set @slice = left(@String,@idx - 1)        
           else        
              set @slice = @String

           if(len(@slice)>0)   
               insert into @temptable(orderId, Items) values(@orderId, @slice)        
           set @orderId = @orderId+1 --<increment the counter

           set @String = right(@String,len(@String) - @idx)        
           if len(@String) = 0 break        
       end    
   return        
   end

您的后续查询可能类似于以下内容:

DECLARE @name varchar(50) = (SELECT items  FROM db_owner.FN_Split('AA~BB~CC','~') where orderId = 0)
DECLARE @add varchar(50) = (SELECT items  FROM db_owner.FN_Split('AA~BB~CC','~') where orderId = 1)
DECLARE @phone varchar(50) = (SELECT items  FROM db_owner.FN_Split('AA~BB~CC','~') where orderId = 2)
insert into employee 
    (
    name,
    add,
    phone
    )
values
    (
    @name, 
    @add,
    @phone
    )

但是,您是否尝试过更改过程,以使其以水平格式而不是当前当前的垂直输出方式输出数据?

2021-05-23