--测试数据
if not object_id(N'Tempdb..#AAA') is null
drop table #AAA
Go
Create table #AAA([aaa] nvarchar(1000))
Insert #AAA
select N'A02-065-B035-SdD-EA' union all
select N'A01-06-B05-SD' union all
select N'A1-7-B3-om' union all
select N'A1-7-B3' union all
select N'A1-8' union all
select N'A1'
Go
--测试数据结束
if not object_id(N'fn_getstrtest') is null
drop function fn_getstrtest
GO
create function fn_getstrtest(@s nvarchar(1000))
returns nvarchar(1000)
as
begin
declare @n int=0,@r nvarchar(100)=''
set @s=@s+'-'
while @n<4
begin
set @r=@r+left(@s,charindex('-',@s))
if @s<>''
set @s=stuff(@s,1,charindex('-',@s),'')
set @n=@n+1
end
return left(@r,len(@r)-1)
end
GO
SELECT dbo.fn_getstrtest([aaa]) as newaaa from #AAA
newaaa
--------------------------------------------------------------------------------------
A02-065-B035-SdD
A01-06-B05-SD
A1-7-B3-om
A1-7-B3
A1-8
A1
(6 行受影响)