SQL拆分字符串
在SQL中拆分字符串,有时候会有这样的需求,下面是我在实际应用中使用的一个例子:
1
set ANSI_NULLS ON
2
set QUOTED_IDENTIFIER ON
3
GO
4
-- =============================================
5
-- Author: Allen
6
-- Create date: 2008-6-11
7
-- Description: 批量导入客户
8
-- =============================================
9
Create PROCEDURE [dbo].[ImportCustomer]
10
@strTel varchar(8000),
11
@strName varchar(8000),
12
@strUserName varchar(50),
13
@groupID int
14
AS
15
BEGIN
16
declare @count int
17
declare @tempTel varchar(20)
18
declare @tempName varchar(20)
19
create table #temp(id int IDENTITY(1,1) NOT NULL primary key,tel varchar(20))
20
declare @strsql as varchar(8000)
21
select @strsql='' select @strsql='insert into #temp values ('''+replace(@strTel,',','''); insert into #temp values (''')+''')'
22
exec (@strsql)
23
create table #temp1(id int IDENTITY(1,1) NOT NULL primary key,[name] varchar(20))
24
declare @strsq2 as varchar(8000)
25
select @strsq2='' select @strsq2='insert into #temp1 values ('''+replace(@strName,',','''); insert into #temp1 values (''')+''')'
26
exec (@strsq2)
27
select @count = count(*) from #temp
28
while(@count>0)
29
BEGIN
30
select @tempTel = tel from #temp where id=@count
31
select @tempName = [Name] from #temp1 where id=@count
32
insert into dbo.SendCustomer(Tel,[Name],FirstDate,EndDate,UserName) values(@tempTel,@tempName,getdate(),getdate(),@strUserName)
33
insert into dbo.SendGroupCus(Tel,GroupID) values(@tempTel,@groupID)
34
Set @count = @count-1
35
END
36
drop table #temp
37
drop table #temp1
38
END
39
40
set ANSI_NULLS ON2
set QUOTED_IDENTIFIER ON3
GO4
-- ============================================= 5
-- Author: Allen6
-- Create date: 2008-6-117
-- Description: 批量导入客户8
-- ============================================= 9
Create PROCEDURE [dbo].[ImportCustomer]10
@strTel varchar(8000), 11
@strName varchar(8000), 12
@strUserName varchar(50),13
@groupID int14
AS15
BEGIN16
declare @count int17
declare @tempTel varchar(20) 18
declare @tempName varchar(20)19
create table #temp(id int IDENTITY(1,1) NOT NULL primary key,tel varchar(20)) 20
declare @strsql as varchar(8000) 21
select @strsql='' select @strsql='insert into #temp values ('''+replace(@strTel,',','''); insert into #temp values (''')+''')'22
exec (@strsql) 23
create table #temp1(id int IDENTITY(1,1) NOT NULL primary key,[name] varchar(20)) 24
declare @strsq2 as varchar(8000) 25
select @strsq2='' select @strsq2='insert into #temp1 values ('''+replace(@strName,',','''); insert into #temp1 values (''')+''')'26
exec (@strsq2)27
select @count = count(*) from #temp28
while(@count>0) 29
BEGIN 30
select @tempTel = tel from #temp where id=@count31
select @tempName = [Name] from #temp1 where id=@count 32
insert into dbo.SendCustomer(Tel,[Name],FirstDate,EndDate,UserName) values(@tempTel,@tempName,getdate(),getdate(),@strUserName) 33
insert into dbo.SendGroupCus(Tel,GroupID) values(@tempTel,@groupID)34
Set @count = @count-135
END36
drop table #temp37
drop table #temp138
END39
40

浙公网安备 33010602011771号