How to concatenate all columns in a select with SQL Server(如何使用 SQL Server 连接选择中的所有列)
问题描述
我需要我的选择有这样的模式:
I need my select to have a pattern like this:
SELECT '<text> ' + tbl.* + ' </text>' FROM table tbl;
理想的解决方案是将所有列用逗号分隔,以便获得该输出:
The ideal solution would have all the columns separated by a comma in order to have that output:
表 1 的两列 SQL 结果:
SQL result for Table 1 with two columns:
'<text>col1, col2</text>'
表 2 三列的 SQL 结果:
SQL result for Table 2 with three columns:
'<text>col1, col2, col3</text>'
我尝试像这样使用 CONCAT(...)
函数:
I tried to use the CONCAT(...)
function like this:
SELECT CONCAT('<text>', tbl.*, '</text>')
FROM table2 tbl
但我知道它不是那么简单,因为列数可变.
But I understand it is not so simple because the variable number of columns.
有什么简单的方法可以解决这个问题吗?
Is there any simple solution to address that problem?
我使用的是 SQL Server 2008 R2.
I am using SQL Server 2008 R2.
推荐答案
给定表名的任意数量的列;如果您需要用 <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>'
SQL Fiddle 此处为示例
-- RESULTS
<text>col1, col2, col3,...</text>
如果您需要使用 <text>
选择查询 结果集 则;
If you need select query result set wrapped with <text>
then;
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')
SQL Fiddle此处为示例
--RESULTS
<text>c1r1,c2r1,c3r1,...</text>
<text>c1r2,c2r2,c3r2,...</text>
<text>c1r3,c2r3,c3r3,...</text>
这篇关于如何使用 SQL Server 连接选择中的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 SQL Server 连接选择中的所有列


基础教程推荐
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01