Split and insert in batches declare @ svarchar (8000), @ sqlnvarchar (4000) set @ s1, 12,1212, 4545set @ sqlinsertintot (col) select + replace (@ s, colunionallselect) exec (@ SQL) test droptable # batch Insert after tabled split
Declare @ s varchar (8000), @ SQL nvarchar (4000)
Set @ s = '1, 4545'
Set @ SQL = 'insert into t (col) select' + replace (@ s, ',', 'col union all select ')
Exec (@ SQL)
Test
Drop table # table
Declare @ s varchar (8000), @ SQL nvarchar (4000)
Set @ s = '1, 4545,454'
Create table # table (col int)
Set @ SQL = 'insert into # table (col) select '+ replace (@ s,', ', 'col union all select ')
Exec (@ SQL)
Select * from # table
Create function f_split (@ sourcesql varchar (8000), @ strseprate varchar (10 ))
Returns @ temp table (a varchar (100 ))
-- Implement the split Function
As
Begin
Declare @ I int
Set @ sourcesql = rtrim (ltrim (@ sourcesql ))
Set @ I = charindex (@ strseprate, @ sourcesql)
While @ I> = 1
Begin
Insert @ temp values (left (@ sourcesql, @ i-1 ))
Set @ sourcesql = substring (@ sourcesql, @ I + 1, len (@ sourcesql)-@ I)
Set @ I = charindex (@ strseprate, @ sourcesql)
End
If @ sourcesql <>''
Insert @ temp values (@ sourcesql)
Return
End
Usage: select * from dbo. f_split ('abc: bc: c: d: e ',':')
Let's look at another instance.
Create function [dbo]. [split]
(
@ Str as nvarchar (1000 ),
@ Delimiters as nvarchar (100)
)
Returns @ t table
(
Pos int not null,
Value nvarchar (100) not null
)
As
Begin
Declare @ end int,
@ Start int,
@ Pos int,
@ Delino int,
@ Strchar nvarchar (1 ),
@ Delimiter nvarchar (1)
Select @ str = replace (@ str, '',''), @ delimiters = replace (@ delimiters ,'','')
Set @ str = ltrim (rtrim (@ str) + substring (@ delimiters, 1, 1)
Select @ pos = 1, @ start = 1, @ end = 1
While @ end <= len (@ str)
Begin
Select @ strchar = substring (@ str, @ end, 1 ),
@ Delino = 1
While @ delino <= len (@ delimiters)
Begin
Set @ delimiter = substring (@ delimiters, @ delino, 1)
If @ strchar = @ delimiter
Begin
If substring (@ str, @ start, @ end-@ start) <>''
Begin
Insert into @ t
Values (@ pos, substring (@ str, @ start, @ end-@ start ))
Set @ pos = @ pos + 1
End
Set @ start = @ end + 1
Break
End
Set @ delino = @ delino + 1
End
Set @ end = @ end + 1
End
Return
End
Go