简体   繁体   中英

T-SQL string concatenation `'string' + str(integer)` introduces extra space character

Sorry for the somewhat trivial question, but why does

select ('https://stackoverflow.com/users/' + str(Id)) as Link
from Users
where DisplayName = 'Jon Skeet';

when entered into the Data Explorer return

https://stackoverflow.com/users/ 22656

instead of

https://stackoverflow.com/users/22656

?

According to Microsoft's documentation on T-SQL's + operator ,

'book' + 'case'

should give

'bookcase'

not

'book case'

and according to the Data Explorer documentation , the SQL-flavor used in the Stack Exchange Data Explorer is indeed T-SQL.


Some additional experiments:

select str(42);

returns "42" , without extra spaces (see EDIT below) .

select ('foo' + 'bar');

returns "foobar" , also without spaces.

select ('foo' + '42');

returns "foo42" , so it doesn't treat digits specially or anything like that.


To me, it looks as if basic semantic compositionality principle is violated. What am I missing here?


EDIT The problem turned out to be the wrong assumption that

select str(42); 

returns "42" . It actually returns

"        42"

but the spaces are ignored by the browser-based GUI.

Here is another example that demonstrates the problem more clearly:

select 'foo' + str('42'); 

seems to return

"foo 42"

but it actually returns

"foo        42"

as can be seen in this query:

select LEN('foo' + str('42')); 

which returns 13 (not 5 and also not 6). Many thanks @lad2025 for pointing this out.

So, it was mostly an "optical illusion" caused by a somewhat inaccurate representation of string-results in the browser.

The problem is STR :

Returns character data converted from numeric data.

STR ( float_expression [ , length [ , decimal ] ] )

Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.

select REPLACE(str(Id), ' ', '-')
from Users
where DisplayName = 'Jon Skeet';

OUTPUT:
-----22656

I would simply use CONCAT :

select CONCAT('https://stackoverflow.com/users/', id) AS link
from Users
where DisplayName = 'Jon Skeet';

See Demo

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