简体   繁体   English

如何在SQL Server中连接字符串和逗号?

[英]How to concatenate strings and commas in SQL Server?

I'm relatively new to MSSQL, so sorry if the question might sounds trivial. 我是MSSQL的新手,如果问题听起来很简单,对不起。 I want to concatenate multiple fields with a delimiter , . 我想用定界符,连接多个字段。 However, when the field is empty, the extra , will be included in the result string as well. 但是,如果该字段为空,额外的,将被包括在结果字符串为好。 So is there an easy way to solve this problem? 那么有没有简单的方法可以解决这个问题呢? For example, 例如,

SELECT VRI.Street_Number_and_Modifier + ',' + 
       VRI.Street_Direction + ',' + 
       VRI.Street_Name + ',' + 
       VRI.Street_Direction + ',' + 
       VRI.Street_Suffix + ',' + 
       VRI.Street_Post_Direction + ',' + 
       VRI.Unit
FROM View_Report_Information_Tables VRI

This modified version of Lamak's handles NULL or strings containing only space/empty: Lamak的此修改版本处理NULL或仅包含空格/空的字符串:

SELECT  COALESCE(NULLIF(VRI.Street_Number_and_Modifier, '') + ',', '') + 
        COALESCE(NULLIF(VRI.Street_Direction, '') + ',', '') + 
        COALESCE(NULLIF(VRI.Street_Name, '') + ',', '') + 
        COALESCE(NULLIF(VRI.Street_Direction, '') + ',', '') + 
        COALESCE(NULLIF(VRI.Street_Suffix, '') + ',', '') + 
        COALESCE(NULLIF(VRI.Street_Post_Direction, '') + ',', '') + 
        COALESCE(NULLIF(VRI.Unit, ''), '')
FROM View_Report_Information_Tables VRI

I was able to get it to work with a slightly different approach. 我能够用一种稍有不同的方法来使其工作。 Putting the commas at the beginning of each field and then removing the first one with the STUFF function worked for me: 将逗号放在每个字段的开头,然后使用STUFF函数删除第一个对我有用:

SELECT 

    STUFF((COALESCE(', ' + NULLIF(VRI.Street_Number_and_Modifier, ''), '') +
        COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '') + 
        COALESCE(', ' + NULLIF(VRI.Street_Name, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Street_Suffix, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Street_Post_Direction, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Unit, ''), ''))
    , 1, 2, '')

FROM View_Report_Information_Tables AS VRI

If the columns are empty instead of null, you can try this: 如果列为空而不是null,则可以尝试以下操作:

SELECT VRI.Street_Number_and_Modifier 
    + CASE WHEN VRI.Street_Number_and_Modifier <> '' THEN ', ' ELSE '' END
       + VRI.Street_Direction
    + CASE WHEN VRI.Street_Direction <> '' THEN ', ' ELSE '' END
       + VRI.Street_Name
    + CASE WHEN VRI.Street_Name <> '' THEN ', ' ELSE '' END
       + VRI.Street_Direction
    + CASE WHEN VRI.Street_Direction <> '' THEN ', ' ELSE '' END
       + VRI.Street_Suffix
    + CASE WHEN VRI.Street_Suffix <> '' THEN ', ' ELSE '' END
       + VRI.Street_Post_Direction
    + CASE WHEN VRI.Street_Post_Direction <> '' THEN ', ' ELSE '' END
       + VRI.Unit
    + CASE WHEN VRI.Unit<> '' THEN ', ' ELSE '' END
FROM View_Report_Information_Tables VRI

Try this: 尝试这个:

SELECT  COALESCE(VRI.Street_Number_and_Modifier + ',','') + 
        COALESCE(VRI.Street_Direction + ',','') + 
        COALESCE(VRI.Street_Name + ',','') + 
        COALESCE(VRI.Street_Direction + ',','') + 
        COALESCE(VRI.Street_Suffix + ',','') + 
        COALESCE(VRI.Street_Post_Direction + ',','') + 
        COALESCE(VRI.Unit,'')
FROM View_Report_Information_Tables VRI

Short or long answer? 简短还是长久的答案?

Short answer - dont. 简短答案-不要。 This is a formatting issue, not a database issue. 这是格式问题,而不是数据库问题。

Long answer - When you concatenate a string and a null in sql server, the result is null. 长答案-当在SQL Server中连接字符串和null时,结果为null。 So you can use combinations of ISNULL 因此,您可以使用ISNULL的组合

SELECT ISNULL(afield + ',','') + ISNULL(bfield + ',','')

You have to use select case when IsNull(fieldname, '')= '' or ltrim(rtrim(fieldname))='') Then ... Else... end +... 当IsNull(fieldname,'')=``或ltrim(rtrim(fieldname))='')时,您必须使用选择大小写。然后...其他...结束+ ...

Edit: 编辑:
Was written from Android mobile. 是从Android手机编写的。
Below your example. 下面的例子。
The following translations (from German) apply, FYI: 仅供参考,以下翻译(德语):

Vorname: given name 姓:给定名字
Name: surname 名字姓
Benutzer: User Benutzer:用户

And here's the example code: 这是示例代码:

CREATE VIEW [dbo].[V_RPT_SEL_Benutzer]  
AS  
SELECT 

    BE_ID AS RPT_UID, 

    CASE 
        WHEN (ISNULL(BE_Name, '0') = '0' OR LTRIM(RTRIM(BE_Name)) = '')  AND (ISNULL(BE_Vorname, '0') = '0' OR LTRIM(RTRIM(BE_Vorname)) = '')
            THEN ''
        WHEN (ISNULL(BE_Name, '0') = '0' OR LTRIM(RTRIM(BE_Name)) = '')
            THEN ISNULL(BE_Vorname, '') 
        WHEN (ISNULL(BE_Vorname, '0') = '0' OR LTRIM(RTRIM(BE_Vorname)) = '')
            THEN ISNULL(BE_Name, '') 
        ELSE
            ISNULL(BE_Name, '') + ', ' + ISNULL(BE_Vorname, '') 
    END AS RPT_Name, 

    ROW_NUMBER() OVER (ORDER BY BE_Name, BE_Vorname ASC) AS RPT_Sort 

FROM T_Benutzer  

For SQL 2008+ 对于SQL 2008+

Using ISNULL(Colmn1 + ', ', '') Will always result with a leading comma in the end, so you'll have to handle it. 使用ISNULL(Colmn1 +',','')始终总是以逗号开头,因此您必须处理它。 Example: 例:

DECLARE @Column1 NVARCHAR(10) = 'Column1'
,   @Column2 NVARCHAR(10) = 'Column2'

SELECT  SUBSTRING(  ISNULL(@Column1 + ', ', '') + ISNULL(@Column2 + ', ', '')
            , 0 --Starting from 0 not 1 to remove leading comma
            , LEN(ISNULL(@Column1 + ', ', '') + ISNULL(@Column2 + ', ', '')))

Or we could approach this the other way around and use the STUFF function to remove our beginning comma which looks cleaner, example: 或者我们可以采用另一种方法,并使用STUFF函数删除看起来更干净的开始逗号,例如:

SELECT  STUFF   (ISNULL(( ', ' + @Column1), '') + ISNULL(( ', ' + @Column2), ''), 1, 2, N'')

For SQL 2012+ we could use the CONCAT function and remove beginning comma using STUFF similar to our previous example but avoiding ISNULL: 对于SQL 2012+,我们可以使用CONCAT函数并使用STUFF删除开头的逗号,这与前面的示例类似,但避免了ISNULL:

SELECT  STUFF(CONCAT( ', ' + @Column1, ', ' + @Column2), 1, 2, N'')

For SQL 2017+ CONCAT_WS was introduced where you can concatinate/join multiple string columns with a delimiter specified in the first argument of the function: 对于SQL 2017+ ,引入了CONCAT_WS,您可以使用在函数的第一个参数中指定的分隔符来合并/联接多个字符串列:

MS Documents CONCAT_WS MS文件CONCAT_WS

MS Doc Example: MS Doc示例:

SELECT CONCAT_WS(',' --delimiter
            ,'1 Microsoft Way', NULL, NULL, 'Redmond', 'WA', 98052) AS Address;
SELECT  COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_1_TXT, ''), ',')+
    COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_2_TXT, '') , ',')+
    COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_3_TXT, '') , ',')+
    COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_CITY_TXT, '') , ',')+
    COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ST_TXT, '') , ',')+
    COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_CNTRY_TXT, '') , ',')+
    COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_PSTL_CD, '') , '')
    FROM ACCOUNT_DETAILS ad

您可以使用ISNULL(field + ',', '')

SELECT isnull(VRI.Street_Number_and_Modifier + ',','')+
   isnull(VRI.Street_Direction + ',','')+
   isnull(VRI.Street_Name + ',','')+
   isnull(VRI.Street_Direction + ',','')+
   isnull(VRI.Street_Suffix + ',','')+
   isnull(VRI.Street_Post_Direction + ',','')+
   isnull(VRI.Unit,'')
FROM View_Report_Information_Tables VRI

I would agree completely with Jamiec's short answer. 我完全同意Jamiec的简短回答。

Otherwise, I would look at a nasty solution of using a REPLACE([concat], ',,', ',') everywhere you concatenate two columns, and then figure out how to trim commas from the beginning and end of the string where the first and last columns might be empty. 否则,我将看一个令人讨厌的解决方案,在连接两列的任何地方都使用REPLACE([concat],',',',','),然后弄清楚如何从字符串的开头和结尾修剪逗号,其中第一列和最后一列可能为空。 Very very messy. 非常非常混乱。

Wanted to see if I can get it without using CASE but could not. 想看看我是否可以不使用CASE而得到它,但是不能。 A long-winded way of mine: 我的一个漫长的方法:

    SELECT case when isnull(nullif(VRI.Street_Number_and_Modifier, ''),'')='' then '' else VRI.Street_Number_and_Modifier end
+ case when isnull(nullif(VRI.Street_Direction, ''),'')='' then '' else ',' + VRI.Street_Direction end
+ case when isnull(nullif(VRI.Street_Name, ''),'')='' then '' else ',' + VRI.Street_Name end
+ case when isnull(nullif(VRI.Street_Suffix, ''),'')='' then '' else ',' + VRI.Street_Suffix end
+ case when isnull(nullif(VRI.Street_Post_Direction, ''),'')='' then '' else ',' + VRI.Street_Post_Direction end
+ case when isnull(nullif(VRI.Street_Post_Direction, ''),'')='' then '' else ',' + VRI.Street_Post_Direction end
FROM View_Report_Information_Tables VRI

This will not add any commas if null-strings 如果为空字符串,则不会添加任何逗号

SELECT CONCAT_WS(', ', IFNULL(column1, NULL), 
         IFNULL(column2, NULL), IFNULL(column3, NULL), 
         IFNULL(column4, NULL), IFNULL(column5, NULL))
FROM yourtable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM