奇怪的CAST行为与INT和单个连字符( - ) [英] Strange CAST behaviour with INT and a single hyphen ( - )
问题描述
我刚刚回答了这个问题: SQL中的主要键值
I just answered this question: Concate Primary Keys in SQL
我遇到了一个奇怪的行为:
There I encountered a strange behaviour:
SELECT 5 + '-' + 8
返回13
SELECT CAST('-' AS INT)
返回0,说明上述...
returns 0, which explains the above...
但是:为什么单个连字符隐含地隐藏?
But: Why is a single hyphen casted to zero implictly?
Btw:与单个+ - )blank string ...
Btw: It's the same with a single + or a (multi-)blank string...
这是相关的 CAST连字符( - )到十进制,但指向这样的事实,即转换为小数不会带来这些结果...
This is related CAST hyphen (-) to Decimal but points to the fact, that a cast to decimal would not bring up these results...
推荐答案
我写这个答案,因为它太长/复杂的评论 - 但它是基于我的意见。
另外请注意 - 我没有一个官方的源,所以没有确认我的逻辑是什么实现。 (但我认为这是有道理的:))
I'm writing this as an answer because it's too long/complex for a comment - but it's based off my comments. Also note - I DO NOT HAVE AN OFFICIAL SOURCE, so no confirmation that my logic is "what's implemented". (But it makes sense I think :))
但假设你正在写一个需要执行的转换函数。
But suppose you're writing a conversion function, that needs to perform.
所以你有一个字符串来验证 - 例如 CAST(' - 50'AS INT);
然后将每个字符它自己的:
So you have a string to validate - for example CAST('-50' AS INT);
Then take each character on its own:
`-` is a valid part of the conversion, so move to next character.
`5` is a valid part of the conversion, so move to next character.
`0` is a valid part of the conversion, so move to next character.
Done.
所以假定字符串 CAST(' - 'AS INT) code>:
So supposed the string CAST('-' AS INT);
:
`-` is a valid part of the conversion, so move to next character.
Done.
现在 - 您可以执行额外的检查以使无效,因为 -
不允许独立,但这将需要额外的代码。
Now - you could do an additional check to invalidate because -
is not allowed standalone, but that would require additional code.
与 +
和空格类似。
以及货币和金额或期间和金额相同:
Similar with +
and spaces.
As well as the same with currency and MONEY or period and money:
SELECT CAST('$' AS MONEY)
SELECT CAST('.' AS MONEY)
两者都是有效字符实际只与实际数字有关。但他们解析通过 - 表明这是所有故意,和转换的速度似乎是明智的。
Both are valid characters - but in actuality only in connection with actual numbers as well. But they parse through - indicating that it's all intentional, and speed for conversion seems sensible.
这篇关于奇怪的CAST行为与INT和单个连字符( - )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!