SQL function to merge a field together

SQL function to merge a field together

Recently, I need to query all the fields in a related table and regroup them into one field. At this time, ordinary join query cannot meet the needs, and SQL function is needed to complete it:

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

Take the data with id = 2 for testing and get the result:

select (database name).getResCodesByOwnerId(fr.owner_id) as room_code
from t1 fr left join t2 frd on fr.owner_id=frd.owner_id

result:

1101010105,11GU002,1101010104

Supplement: SQL STUFF function concatenates strings

Today I saw an article about parallelism. I also studied it and it was pretty good.

Want this effect.

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)

Description: Delete length characters from param1 starting from startIndex (SQL starts at 1, not 0), and then replace the deleted characters with param2. */

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

That's it.

Information collected

/* 
Title: One of the strings merged by a field (simple merge) 
Author: (After 18 years of wind and rain, the snow lotus blooms on the iceberg) 
Location: Shenzhen, Guangdong Description: Merge the following data into the value field according to the id field. 
id value 
----- ------  
1aa 
1 bb 
2 aaa 
2 bbb 
2 ccc 
Need to get the result: 
id value 
------ -----------  
1 aa,bb 
2 aaa,bbb,ccc 
That is: group by id, find the sum of value (string addition) 
*/ 
--1. In sql2000, you can only use custom functions to solve 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 
 
--Call function select id, value = dbo.f_str(id) from tb group by id 
 
drop function dbo.f_str 
drop table tb  
 
--2. Method create table tb(id int, value varchar(10)) in sql2005 
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. Use cursor to merge data 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))--define result set table variable--define cursor and merge process 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

The above is my personal experience. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM. If there are any mistakes or incomplete considerations, please feel free to correct me.

You may also be interested in:
  • How to split and merge multiple values ​​in a single field in MySQL
  • Implementation steps of Mysql merge results and horizontal splicing fields
  • Analysis of MySQL Union merge query data and table alias and field alias usage
  • MySQL column to row conversion, method of merging fields (must read)
  • Group character merge SQL statement merges one of the strings by a certain field (simple merge)
  • An example of merging a field value in SQL Server
  • How to merge two fields in MySQL

<<:  Hyperlink icon specifications: improve article readability

>>:  Use of Docker UI, a Docker visualization management tool

Recommend

Mysql practical exercises simple library management system

Table of contents 1. Sorting function 2. Prepare ...

VMware Workstation 12 Pro Linux installation tutorial

This article records the VMware Workstation 12 Pr...

Install Windows Server 2019 on VMware Workstation (Graphic Tutorial)

If prompted to enter a key, select [I don’t have ...

Specific use of CSS front-end page rendering optimization attribute will-change

Preface When scroll events such as scroll and res...

Web page comments cause text overflow in IE

The experimental code is as follows: </head>...

Basic JSON Operation Guide in MySQL 5.7

Preface Because of project needs, the storage fie...

Detailed installation and configuration tutorial of PostgreSQL 11 under CentOS7

1. Official website address The official website ...

Summary of practical methods for JS beginners to process arrays

join() method: connects all elements in an array ...

Implementation of Docker private warehouse registry deployment

As more and more Docker images are used, there ne...

Detailed explanation of how to synchronize data from MySQL to Elasticsearch

Table of contents 1. Synchronization Principle 2....

How Web Designers Create Images for Retina Display Devices

Special statement: This article is translated bas...

How to deploy Confluence and jira-software in Docker

version: centos==7.2 jdk==1.8 confluence==6.15.4 ...