您好,欢迎访问一九零五行业门户网

数据库表字段数据分割问题

有的时候为了减少存储记录数,可能会把多条记录合并为一条显示。这种情况的发生主要体现上记录在表的其它字段都相同,只有某一个字段是变化的这种情况,例如人事管理中,部门中的相关人的id都放在一条记录的一个字段中,中间用逗号隔开。现在的需求就是要将
有的时候为了减少存储记录数,可能会把多条记录合并为一条显示。这种情况的发生主要体现上记录在表的其它字段都相同,只有某一个字段是变化的这种情况,例如人事管理中,部门中的相关人的id都放在一条记录的一个字段中,中间用逗号隔开。现在的需求就是要将一条记录按id字段分割成多条记录。
create table [dbo].[table_dept]( [dept_code] [int] null, [content] [nvarchar](50) null, [a0188s] [nvarchar](max) null) on [primary]goinsert into table_dept select 1000,'总务系','350,688,258' union all select 1001,'总经理室','2,3,4,298'查询该表结果如下,其中dept_code部门编码,content是部门名称,a0188s是相关人。
现在需要将a0188s中的id分解为多条显示。考虑采用自定义字符串分割函数实现,分割函数脚本:
create function [dbo].[split] ( @c varchar(max) , @split varchar(50) ) returns @t table ( col varchar(50) ) as begin while ( charindex(@split, @c) 0 ) begin insert @t( col ) values ( substring(@c, 1, charindex(@split, @c) - 1) ) set @c = stuff(@c, 1, charindex(@split, @c), '') end insert @t( col ) values ( @c ) return end
但是该函数只能处理单条记录,这里考虑采用游标遍历原表,逐个分解然后存储到临时表中。if object_id('tempdb..#temptb1') is not nullbegin drop table #temptb1endcreate table #temptb1( [dept_code] [int] null, [content] [nvarchar](50) null, [a0188s] [nvarchar](max) null)if object_id('tempdb..#temptb2') is not nullbegin drop table #temptb2endcreate table #temptb2( [pid] [nvarchar](max) null)declare @dept_code intdeclare @content varchar(50)declare @a0188s varchar(max)exec('declare my_cursor1 cursor for select * from [table_dept]')open my_cursor1declare @id1 sysnamedeclare @id2 sysnamedeclare @id3 sysnamefetch next from my_cursor1 into @id1,@id2,@id3 while(@@fetch_status= 0) begin set @dept_code =convert(int,@id1) set @content =convert(varchar(50),@id2) set @a0188s =convert(varchar(max),@id3) truncate table #temptb2 insert into #temptb2 select * from split(@a0188s,',') insert into #temptb1 select @dept_code,@content,pid from #temptb2 fetch next from my_cursor1 into @id1,@id2,@id3 endclose my_cursor1deallocate my_cursor1select * from #temptb1
得到最终结果
其它类似信息

推荐信息