大家看看要实现这个功能,怎样写SQL更简单,谢谢!

chengxing 2005-08-29 05:21:32
SET @strArrUserID = "1~2~3~4~5~"
要把这个字符串中的5个数据分别插入到表里面,看看怎么写,SQL最简单,谢谢各位!

...全文
64 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
vivianfdlpw 2005-08-29
  • 打赏
  • 举报
回复
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_split]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_split]
GO

/*--得到字符串列表指定位置的字符

可以自定义字符串列表的分隔符
如果取数位置超出的范围,返回空字符串

--邹建 2004.07(引用请保留此信息)--*/

/*--调用示例

--测试数据
declare @t table(FITEM varchar(100))
insert @t select '100.120.10'
union all select '20.140.10'
union all select '150.124.150.10'

--查询
select fitem1=dbo.f_split(fitem,1,'.')
,fitem2=dbo.f_split(fitem,2,'.')
,fitem3=dbo.f_split(fitem,3,'.')
,fitem4=dbo.f_split(fitem,4,'.')
from @t
--*/
create function f_split(
@s varchar(8000), --字符串列表
@pos int, --取数位置
@splitchar varchar(10) --分隔符
)returns varchar(8000)
as
begin
declare @i int,@ilen int

select @i=charindex(@splitchar,@s),@ilen=len(@splitchar)
while @i>0 and @pos>1
select @s=substring(@s,@i+@ilen,8000)
,@i=charindex(@splitchar,@s)
,@pos=@pos-1
return(case @pos when 1
then case when @i>0 then left(@s,@i-1) else @s end
else '' end)
end
go

--测试
declare @strArrUserID varchar(100)
SET @strArrUserID = '1~2~3~4~5~'

declare @tb table(ID int)
declare @i int
set @i=1
while @i<=len(@strArrUserID)-len(replace(@strArrUserID,'~',''))
begin
insert @tb
select dbo.f_split(@strArrUserID,@i,'~')
set @i=@i+1
end

--查询
select * from @tb

--结果
/*
(所影响的行数为 1 行)

ID
-----------
1.00
2.00
3.00
4.00
5.00

(所影响的行数为 5 行)
*/

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧