使用具有相同 ID 的行的表中的列来形成字符串值的最佳方法是什么? [英] Which is the best way to form the string value using column from a Table with rows having same ID?
本文介绍了使用具有相同 ID 的行的表中的列来形成字符串值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 SQL Server 2008.
I am using SQL Server 2008.
这是我的桌子.
表 A
Aid int pk
col2
col3
XYZID int
表 B
Bid int pk
XYZID int
Col2
Col3
Col4
seq -- (Sequence )
Table B
会是这样的
seq col2 |XYZID|Bid |col3| col4
===============================================
1 foo | 1 | 1 | 12 | wqw
3 bar | 1 | 10 | 77 | kikk
2 foobar | 1 | 2 | w | ed
1 barfoo | 2 | 4 | e | dwe
2 asdsad | 2 | 5 | e | e
Table A
是主表,基于 A 中的 XYZID
Table A
is the main table and based on the XYZID
in A
我需要使用 TableB
中的 col 和 XYZID 和 Seq
生成一个字符串值.
I need to generate a string value using col from TableB
with XYZID and Seq
.
我需要使用来自 TableB 的 col 和 XYZID 和 Seq 生成一个字符串值.
I need to generate a string value using col from TableB with XYZID and Seq .
例如:xyzid=1
我期望:foo-12-wqw#foobar-w-ed#bar-77-kikk
基于序列foo-1,foobar-2,bar-3
推荐答案
For XYZID = 1
.
select stuff((select '#'+col2+'-'+col3+'-'+col4
from TableB
where XYZID = 1
order by seq
for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '')
对于表A中的所有行:
select stuff((select '#'+col2+'-'+col3+'-'+col4
from TableB as B
where A.XYZID = B.XYZID
order by seq
for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '')
from TableA as A
这篇关于使用具有相同 ID 的行的表中的列来形成字符串值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文