简体   繁体   中英

SQL Server removing necessary whitespaces

I'm trying to add whitespaces to a column. However, the SPACE function is not working.

Example:

SELECT LEN(('ABC' + SPACE(10)))

Returns 3 instead 13.

This behavior also happens with the REPLICATE function.

Example:

REPLICATE(' ', 5)

Returns ''

What I need:

REPLICATE(' ', 5)

Returns ' '

Editing:

This suggestion works, but it needs do add : to the string.

DECLARE @Test varchar(32); 

SELECT @Test = 'ABC' + SPACE(10); 
SELECT @Test + ':';

Returns ABC :

I need ABC

--This table is in SQL Server
CREATE TABLE Iten
(
    Code varchar(35)
);

--This table is on DB2
CREATE TABLE Product
(
    code char(35),
    description varchar(100)
)

INSERT INTO Iten VALUES ('ABC');
INSERT INTO Product VALUES ('ABC', 'My Test')

SELECT 
    Iten.Code, Product.description, 
    DATALENGTH(Iten.Code), 
    DATALENGTH(Product.code)
FROM
    Iten 
INNER JOIN 
    IBMServerD.DatabaseD.LDAT.Product AS Product ON Iten.Code = Product.code

This query returns no rows.

Because that, I need to fill spaces on the right to Iten.Code , but it does not respect it.

If both tables were in SQL Server, it would work fine.

Try using trim functions

SELECT Iten.Code, Product.description, DataLength(Iten.Code), 
       DataLength(Product.code)
  from Iten INNER JOIN IBMServerD.DatabaseD.LDAT.Product as Product
    ON ltrim(rtrim(Iten.Code)) = ltrim(rtrim(Product.code))
'ABC' + REPLICATE(' ',10)

作品

SPACE(INTEGER) is working fine  
select LEN('abc'+SPACE(10))    `3`

LEN() function excludes trailing blanks/whitespaces

select DATALENGTH('abc'+SPACE(10))   `13`  

using DATALENGTH() give you 13 , DATALENGTH() includes trailing blanks/whitespaces

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