首页 > 解决方案 > 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.

标签: sqlsql-servertsql

解决方案


问题是STR

返回从数字数据转换而来的字符数据。

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

是总长度。这包括小数点、符号、数字和空格。默认值为 10。

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

OUTPUT:
-----22656

我会简单地使用CONCAT

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

看演示


推荐阅读