简体   繁体   中英

SQL Server CONCAT adds blank spaces when used

I've tried to use CONCAT function of some fields in a table; in order to get a string that I need to compare onto another field from different table.

However when I use the function it's like it random adds spaces between the fields and then I cannot use this result to compare.

I've tried:

SELECT CONCAT([STC_GL-STC].[ZZGL_Desc_Group_5D],'-',
              [STC_GL-STC].[ZZCostCentreGroup],'-',
              AS RESULT
FROM [STC_GL-STC];

As an example of result:

'Compras - RM -MATERIA PRIMA -'

(Please note the blank spaces in the second and third (-).

I would need to obtain:

'Compras - RM-MATERIA PRIMA-'

I've checked the values in the fields and there is no blank spaces at the end on fields ZZGL_Desc_Group_5D, ZZCostCentreGroup.

I've also tried:

SELECT CONCAT_WS('-',[ZZGL_Desc_Group_5D],[ZZCostCentreGroup]) AS RESULT
FROM [STC_GL-STC]

With same result.

And finally I tried to remove blank spaces using RTRIM and LTRIM using the following:

SELECT CONCAT(LTRIM(RTRIM([STC_GL-STC].[ZZGL_Desc_Group_5D])),
              LTRIM(RTRIM('-')),
              LTRIM(RTRIM([STC_GL-STC].[ZZCostCentreGroup]))) AS RESULT
FROM [STC_GL-STC]
ORDER BY RESULT ASC;

And even with LTRIM and RTRIM functions on that field, I still getting the same result.

How to get rid of this behaviour and of the blank spaces? Is there another way to build that string?

Kind Regards and many thanks in advance,

Long time ago I created a udf function to remove white spaces.

It is based on the 'magic' of the XML xs:token data type.

udf

/*
1. All invisible TAB, Carriage Return, and Line Feed characters will be replaced with spaces.
2. Then leading and trailing spaces are removed from the value. 
3. Further, contiguous occurrences of more than one space will be replaced with a single space.
*/
CREATE FUNCTION dbo.udf_tokenize(@input VARCHAR(MAX))
   RETURNS VARCHAR(MAX)
AS
BEGIN 
   RETURN (SELECT CAST('<r><![CDATA[' + @input + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)'));
END

Test harness

-- DDL and sample data population, start
DECLARE @mockTbl TABLE (ID INT IDENTITY(1,1), col_1 VARCHAR(100), col_2 VARCHAR(100));
INSERT INTO @mockTbl (col_1, col_2)
VALUES ('  FL   ', '  Miami')
   , ('  FL   ', '  Fort       Lauderdale   ')
   , ('  NY   ', '  New           York   ')
   , ('  NY   ', '')
   , ('  NY   ', NULL);
-- DDL and sample data population, end

SELECT * 
    , col_1n = dbo.udf_tokenize(col_1)
    , col_2n = dbo.udf_tokenize(col_2)
    , CONCAT_WS('-', dbo.udf_tokenize(col_1), dbo.udf_tokenize(col_2)) AS RESULT
FROM @mockTbl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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