| |

VerySource

 Forgot password?
 Register
Search
View: 644|Reply: 2

Find a summary of strings

[Copy link]

1

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-2-19 16:00:01
| Show all posts |Read mode
The table data is as follows:
ID CharCol
1 A
1 B
1 C
2 B
2 D

Instead of storing procedures, using a single statement, can you summarize them into:

ID CharCol_Total
1 A, B, C
2 B, D
Reply

Use magic Report

0

Threads

211

Posts

108.00

Credits

Newbie

Rank: 1

Credits
108.00

 China

Post time: 2020-4-26 18:30:01
| Show all posts
create table T (ID int, CharCol char (1))
insert T select 1, 'A'
union all select 1, 'B'
union all select 1, 'C'
union all select 2, 'B'
union all select 2, 'D'

create function fun (@ID int)
returns varchar (100)
as
begin
declare @re varchar (100)
set @ re = ''
select @ re = @ re + CharCol + ',' from T where ID = @ ID
select @ re = left (@re, len (@re) -1)

return @re
end

select distinct ID, dbo.fun (ID) as CharCol_Total from T
--result
ID CharCol_Total
----------- --------------------
1 A, B, C
2 B, D

(2 row (s) affected)
Reply

Use magic Report

0

Threads

41

Posts

13.00

Credits

Newbie

Rank: 1

Credits
13.00

 China

Post time: 2020-4-26 20:00:02
| Show all posts
create function f_getstr (@id varchar (64))
RETURNS varchar (8000)
as
begin
declare @s varhcar (8000)
set @s = ''
select @s = @s + ',' + CharCol from tb where id = @ id
return stuff (@ s, 1,1, '')
end
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list