рüф*_*ффп 5 sql sql-server sql-server-2008-r2
我需要我的选择有这样的模式:
SELECT '<text> ' + tbl.* + ' </text>' FROM table tbl;
Run Code Online (Sandbox Code Playgroud)
理想的解决方案是将所有列用逗号分隔,以便具有该输出:
表1的SQL结果有两列:
'<text>col1, col2</text>'
Run Code Online (Sandbox Code Playgroud)
表2的SQL结果有三列:
'<text>col1, col2, col3</text>'
Run Code Online (Sandbox Code Playgroud)
我试着使用这样的CONCAT(...)函数:
SELECT CONCAT('<text>', tbl.*, '</text>')
FROM table2 tbl
Run Code Online (Sandbox Code Playgroud)
但我明白这并不是那么简单,因为列数可变.
有没有解决这个问题的简单解决方案?
我正在使用SQL Server 2008 R2.
Kaf*_*Kaf 11
给定表名的任意数量的列 ; 如果需要包装的列名<text>
DECLARE @s VARCHAR(500)
SELECT @s = ISNULL(@s+', ','') + c.name
FROM sys.all_columns c join sys.tables t
ON c.object_id = t.object_id
WHERE t.name = 'YourTableName'
SELECT '<text>' + @s + '</text>'
Run Code Online (Sandbox Code Playgroud)
SQL小提琴示例在这里
-- RESULTS
<text>col1, col2, col3,...</text>
Run Code Online (Sandbox Code Playgroud)
如果您需要选择查询结果集包带<text>即可;
SELECT @S = ISNULL( @S+ ')' +'+'',''+ ','') + 'convert(varchar(50), ' + c.name FROM
sys.all_columns c join sys.tables t
ON c.object_id = t.object_id
WHERE t.name = 'YourTableName'
EXEC( 'SELECT ''<text>''+' + @s + ')+' + '''</text>'' FROM YourTableName')
Run Code Online (Sandbox Code Playgroud)
SQL小提琴示例在这里
--RESULTS
<text>c1r1,c2r1,c3r1,...</text>
<text>c1r2,c2r2,c3r2,...</text>
<text>c1r3,c2r3,c3r3,...</text>
Run Code Online (Sandbox Code Playgroud)
MS SQL Server 2008 架构设置:
create table YourTable
(
ID int identity primary key,
Name varchar(50),
)
insert into YourTable values
('Name 1'),
('Name 2'),
('Name 3'),
('Name 4'),
('Name 5')
Run Code Online (Sandbox Code Playgroud)
查询1:
select (
select (
select ', '+T2.N.value('./text()[1]', 'varchar(max)')
from (
select T.*
for xml path(''), type
) as T1(N)
cross apply T1.N.nodes('/*') as T2(N)
for xml path(''), type
).value('substring(./text()[1], 3)', 'varchar(max)')
for xml path('text'), type
)
from YourTable as T
Run Code Online (Sandbox Code Playgroud)
结果:
| COLUMN_0 |
--------------------------
| <text>1, Name 1</text> |
| <text>2, Name 2</text> |
| <text>3, Name 3</text> |
| <text>4, Name 4</text> |
| <text>5, Name 5</text> |
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35449 次 |
| 最近记录: |