我们检测线系统一个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函数。