带案例声明的RTRIM和LTRIM函数

时间:2018-09-05 08:10:39

标签: sql sql-server

如何将LTRIM和RTRIM与以下SQL一起使用?我需要将LTRIM和RTRIM所有这些字段都留在前导空格中

UPDATE CORE.WeccoPartyAddress 
SET AddressElements = CONTROL.TrimChar(
                                   CASE when COALESCE(Address1,'') != '' THEN Address1 + ', ' ELSE '' END +
                                   CASE when COALESCE(Address2,'') != '' THEN Address2 + ', ' ELSE '' END +
                                   CASE when COALESCE(Address3,'') != '' THEN Address3 + ', ' ELSE '' END +
                                   CASE when COALESCE(Town,'') != '' THEN Town + ', ' ELSE '' END +
                                   CASE when COALESCE(County,'') != '' THEN County + ', ' ELSE '' END +
                                   CASE when COALESCE(Postcode,'') != '' THEN Postcode ELSE '' END, ', '
                                  )

2 个答案:

答案 0 :(得分:1)

用法如下嵌套:

UPDATE CORE.WeccoPartyAddress SET AddressElements = rtrim(ltrim(CASE when COALESCE(Address1,'') != '' THEN Address1 + ', ' ELSE '' END + CASE when COALESCE(Address2,'') != '' THEN Address2 + ', ' ELSE '' END + CASE when COALESCE(Address3,'') != '' THEN Address3 + ', ' ELSE '' END + CASE when COALESCE(Town,'') != '' THEN Town + ', ' ELSE '' END + CASE when COALESCE(County,'') != '' THEN County + ', ' ELSE '' END + CASE when COALESCE(Postcode,'') != '' THEN Postcode ELSE '' END))

答案 1 :(得分:1)

您不必在声明中使用CASE

UPDATE CORE.WeccoPartyAddress
SET AddressElements = ISNULL( STUFF (
    COALESCE( ', ' + LTRIM( RTRIM(Address1) )           , '') +
    COALESCE( ', ' + LTRIM( RTRIM(Address1Address2) )   , '') +
    COALESCE( ', ' + LTRIM( RTRIM(Address1Address3) )   , '') +
    COALESCE( ', ' + LTRIM( RTRIM(Address1Town) )       , '') +
    COALESCE( ', ' + LTRIM( RTRIM(Address1County) )     , '') +
    COALESCE( ', ' + LTRIM( RTRIM(Address1Postcode) )   , '')
    ,1
    ,2
    ,''
    ), '')

如果任何一个Address值都不为null,您将获得如下字符串:',Address',然后使用函数STUFF在字符串开头替换',',以将'Address'作为结果。

如果所有值都为null,则STUFF函数将返回NULL,它将由ISNULL函数替换为''。