Sql查询将2个或更多列组合到一个单元格中

时间:2016-07-16 12:01:35

标签: sql sql-server tsql

我的查询带来3个字段 例如,如果我有以下代码:

// Prompt for a name and print a greeting using the name.    

#include <stdio.h>
#include <string.h>

int main()
{
    // Prompt for a name.
    printf("What is your name? ");

    // Get the name.
    char name[20];
    scanf("%s", name);    // Suspect segfault occurs here...

    // Construct the greeting.
    char *greeting;
    char *suffix;
    greeting = "Hello, ";
    suffix = ", nice to meet you!";
    strcat(greeting, name);
    strcat(greeting, suffix);

    // Display the greeting.
    printf("%s", greeting);

    return 0;
}

所有字段都是int类型

但我希望所有人都在一个牢房里 我认为这可能就像下面的陈述;但它没有工作

select C.ContactId,C.CityId,C.ZipCode
from Contacts C
Where c.ContactId=256

3 个答案:

答案 0 :(得分:4)

您可以使用FORMATMESSAGE

SELECT FORMATMESSAGE('%i %i %i', C.ContactId, C.CityId, C.ZipCode)
FROM Contacts C
WHERE C.ContactId = 256;

LiveDemo

答案 1 :(得分:2)

Concat有更多支持

SELECT CONCAT ( 'Happy ', 'Birthday ', 11, '/', '25' ) AS Result;  

这是结果集。

生日快乐11/25

https://msdn.microsoft.com/en-us/library/hh231515.aspx

答案 2 :(得分:0)

Solution of lad2025 is elegant. But you can do this too:

   select cast(C.ContactId as varchar(50)) + ',' + cast(C.CityIdas varchar(50)) + ',' + cast(C.ZipCode as varchar(50))
   from Contacts C
   Where c.ContactId=256