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

Solution to the problem that Java cannot connect to MySQL 8.0

This article shares a collection of Java problems...

Why the CSS attribute value clear:right does not work in detail

Using the clear property to clear floats is a comm...

MySQL merges multiple rows of data based on the group_concat() function

A very useful function group_concat(), the manual...

Detailed graphic tutorial on how to enable remote secure access with Docker

1. Edit the docker.service file vi /usr/lib/syste...

Detailed explanation of linux crm deployment code

Linux basic configuration Compile and install pyt...

Detailed explanation of Vue filter implementation and application scenarios

1. Brief Introduction Vue.js allows you to define...

How to customize more beautiful link prompt effect with CSS

Suggestion: Handwriting code as much as possible c...

Recommended plugins and usage examples for vue unit testing

Table of contents frame First-class error reporti...

Why is there this in JS?

Table of contents 1. Demand 2. Solution 3. The fi...

How to generate mysql primary key id (self-increment, unique and irregular)

Table of contents 1. Use the uuid function to gen...

How to disable ads in the terminal welcome message in Ubuntu Server

If you are using the latest Ubuntu Server version...

CSS sets the list style and creates the navigation menu implementation code

1. Set the list symbol list-style-type: attribute...

Solve the problem that Docker pulls MySQL image too slowly

After half an hour of trying to pull the MySQL im...

Implementation of ssh non-secret communication in linux

What is ssh Administrators can log in remotely to...