|
create table T (IDX int, CODE varchar (50), DEPTCODE varchar (50), PARTNAME varchar (50))
insert T select 1, 'CN00001', 'CN00001001', 'PART1'
union all select 2, 'CN00001', 'CN00001002', 'PART2'
union all select 3, 'CN00001', 'CN00001001001', 'PART3'
union all select 4, 'CN00001', 'CN00001002001', 'PART4'
union all select 5, 'CN00002', 'CN00002001', 'PART5'
union all select 6, 'CN00002', 'CN00002001001', 'PART6'
create function fun (@DEPTCODE varchar (50))
returns varchar (200)
as
begin
declare @re varchar (200)
set @ re = ''
select @ re = @ re + DEPTCODE + ';' + PARTNAME + '|' from T where DEPTCODE like @DEPTCODE + '%'
select @ re = left (@re, len (@re) -1)
Ranch
return @re
end
select IDX, CODE, DEPTCODE, DETAIL = dbo.fun (DEPTCODE) from T where len (DEPTCODE) = 10
--result
IDX CODE DEPTCODE DETAIL
----------- --------------------------------------- ----------- --------------------------------------- ----------- --------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -----------
1 CN00001 CN00001001 CN00001001; PART1 | CN00001001001; PART3
2 CN00001 CN00001002 CN00001002; PART2 | CN00001002001; PART4
5 CN00002 CN00002001 CN00002001; PART5 | CN00002001001; PART6
(3 row (s) affected) |
|