3

我想要做以下使用SQL Server 2005SQL Server的拆分和表格插入

  1. 創建一個存儲過程,需要一個varchar()逗號「」分隔PARAM

  2. 分流/爆炸varchar() PARAM並在臨時表中插入值

的東西,將做到以下幾點:

INSERT INTO #temp_table SPLIT('john,peter,sally',','); 

SELECT * FROM #temp_table; 

是否有一個函數或存儲過程將執行拆分?

如果是這樣,它是如何工作的?

感謝

+3

可能重複:// stackoverflow.com/questions/2647/split-string-in-sql) – Jacob

回答

5

SQL Server不有一個字符串分割功能開箱即用,但你可以創建[分割字符串在SQL](HTTP一個像this

CREATE FUNCTION dbo.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