SQL 함수 가 필드 를 합 친 동작

4706 단어 SQL필드합치다
최근 에 관련 표 의 한 필드 를 모두 조회 하고 하나의 필드 로 재 구성 해 야 하 는 상황 이 발생 했 습 니 다.이 럴 때 일반적인 연결 조 회 는 수 요 를 만족 시 키 지 못 하고 SQL 함수 로 완성 해 야 합 니 다.

ALTER function dbo.getResCodesByOwnerId(@OwnerId INT)
returns nvarchar(2000)
as
begin
DECLARE @codes VARCHAR(2000)
SET @codes=''
select @codes=stuff((select ','+residence_code from crm_owner co left join crm_owner_residence cor on co.id=cor.owner_id where co.id=@OwnerId for xml path('')),1,1,'')
return @codes
END
id=2 의 데 이 터 를 가지 고 테스트 하여 결 과 를 얻 습 니 다.

select (    ).getResCodesByOwnerId(fr.owner_id) as room_code
from t1 fr left join t2 frd on fr.owner_id=frd.owner_id
결과:

1101010105,11GU002,1101010104
추가:SQL STUFF 함수 연결 문자열
오늘 한 편의 문장 을 보 았 는데,그것 은 병렬 에 관 한 것 이 고,또 연구 해 보 았 는데,그래도 괜찮다.

이런 효과 로

create table tb(idint, value varchar(10))
insert into tbvalues(1,'aa')
insert into tbvalues(1,'bb')
insert into tbvalues(2,'aaa')
insert into tbvalues(2,'bbb')
insert into tbvalues(2,'ccc')
go
 
/*     stuff(param1, startIndex, length, param2)
설명:param 1 에서 startIndex(SQL 에 서 는 0 이 아 닌 1 부터 시작)부터 length 문 자 를 삭제 한 다음 에 param 2 로 삭 제 된 문 자 를 교체 합 니 다.*/

SELECT id,
           value = stuff
             ((SELECT   ',' + value
               FROM     tb AS t
               WHERE   t .id = tb.id FOR xml path('')), 1, 1, '')
FROM     tb
GROUP BY id
이렇게 하면 된다.
수집 한 자료

/* 
  :           (    ) 
  :(     ,        ) 
  :     
 
  :         id    value  。 
id  value 
----- ------  
1   aa 
1   bb 
2   aaa 
2   bbb 
2   ccc 
      : 
id   value 
------ -----------  
1   aa,bb 
2   aaa,bbb,ccc 
 :group by id,   value   (     ) 
*/ 
--1、sql2000              
create table tb(id int, value varchar(10)) 
insert into tb values(1, 'aa') 
insert into tb values(1, 'bb') 
insert into tb values(2, 'aaa') 
insert into tb values(2, 'bbb') 
insert into tb values(2, 'ccc') 
go 
 
create function dbo.f_str(@id varchar(10)) returns varchar(1000) 
as 
begin 
 declare @str varchar(1000) 
 select @str = isnull(@str + ',' , '') + cast(value as varchar) from tb where id = @id 
 return @str 
end 
go 
 
--      
select id , value = dbo.f_str(id) from tb group by id 
 
drop function dbo.f_str 
drop table tb  
 
--2、sql2005      
create table tb(id int, value varchar(10)) 
insert into tb values(1, 'aa') 
insert into tb values(1, 'bb') 
insert into tb values(2, 'aaa') 
insert into tb values(2, 'bbb') 
insert into tb values(2, 'ccc') 
go  
select id, [value] = stuff((select ',' + [value] from tb t where id = tb.id for xml path('')) , 1 , 1 , '') 
from tb 
group by id  
drop table tb 
  
--3、          
create table tb(id int, value varchar(10)) 
insert into tb values(1, 'aa') 
insert into tb values(1, 'bb') 
insert into tb values(2, 'aaa') 
insert into tb values(2, 'bbb') 
insert into tb values(2, 'ccc') 
go 
declare @t table(id int,value varchar(100))--          
--             
declare my_cursor cursor local for 
select id , value from tb 
declare @id_old int , @id int , @value varchar(10) , @s varchar(100) 
open my_cursor 
fetch my_cursor into @id , @value 
select @id_old = @id , @s='' 
while @@FETCH_STATUS = 0 
begin 
  if @id = @id_old 
    select @s = @s + ',' + cast(@value as varchar) 
  else 
   begin 
    insert @t values(@id_old , stuff(@s,1,1,'')) 
    select @s = ',' + cast(@value as varchar) , @id_old = @id 
   end 
  fetch my_cursor into @id , @value 
END 
insert @t values(@id_old , stuff(@s,1,1,'')) 
close my_cursor 
deallocate my_cursor 
 
select * from @t 
drop table tb 
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.만약 잘못 이 있 거나 완전히 고려 하지 않 은 부분 이 있다 면 아낌없이 가르침 을 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기