我们检测线系统一个employee有多个gangwei,用的逗号分隔的简单形式没单独存表,sGangWei存着这个人的岗位,用逗号分隔。
有一个sql函数splitToTable,传入字符串和分隔符,会拆出来表。
--拆分字符串为临时表,海宏软件,周承昊,20150811
CREATE function [dbo].[splitToTable](@str varChar(1000), @split varChar(10)=',')
returns @RTable table
(
sValue varChar(100),
nIndex int
)
as Begin
declare @debug bit
select @debug=0
if (@debug=1) select @str='1,2,3,45,6'
if @split='' select @split=','
declare @ix int, @pos int, @s varchar(1000), @nIndex int
select @pos=1, @ix=1, @nIndex=0
while @ix>0
begin
set @ix=charindex(',', @str, @pos)
if @ix>0
set @s=substring(@str, @pos, @ix-@pos)
else
set @s=substring(@str, @pos, len(@str))
set @s=ltrim(rtrim(@s))
-- print @str
insert into @RTable(sValue, nIndex) values(@s, @nIndex+1)
select @pos=@ix+1, @nIndex=@nIndex+1
end
return
end
/* --用法:
select * from dbo.splitToTable('1,2,3,678,9,,2',',')
*/
GO
select * from dbo.splitToTable('GW004,GW006,GW007', ',')
select employee.sID, employee.sName, Employee.sGangWei, jobs.*
from employee outer apply dbo.splitToTable(employee.sGangWei, ',') as jobs

可见,cross apply比较省事的调用了dbo.splitToTable函数。
SQL函数splitToTable拆分字符串为临时表的应用
这篇博客介绍了如何使用SQL自定义函数splitToTable将一个人员的多个岗位信息,以逗号分隔的字符串形式拆分成单独的记录。通过outer apply操作,实现了从员工表中按岗位字段拆分数据并与工作岗位表进行关联查询,简化了数据处理过程。
455

被折叠的 条评论
为什么被折叠?



