将 int 值转换为太小的 char
在 MSSQL 2005 上尝试以下操作:
select convert(char(2), 123)
这里的关键是 char(2) 太小,无法接受值“123”。我希望在这里看到截断错误,但返回值“*”。
更新: 一些答案展示了如何以会导致错误的方式进行转换。这并不是我真正需要的。我们有很多代码使用了一个特定字段,该字段过去被声明为 char(2),但后来已更改为 int。我的目标是确保未转换的代码在遇到无法处理的数据时会失败。所以我们可以去修复它。
有趣的是, dsolimano 注释将上述类型更改为 nchar 会导致预期错误,并且 Justin Niessner 指出,这两者都是设计使然。考虑到 nchar 用于 Unicode 支持,奇怪的不一致,嘿?
从我在这里得到的答案来看,遗憾的是我似乎无法让服务器抛出现有代码的错误。
Try the following on MSSQL 2005:
select convert(char(2), 123)
The key here is that char(2) is too small to accept the value '123'. I would expect to see a truncation error here, but instead the value "*" is returned.
Update:
A few of the answers showed how to cast in a way that will cause an error. That's not really what I need. We have lots of code that uses a specific field that used to be declared char(2) but has since been changed to int. My goal here is to make sure that code that hasn't been converted will fall over if it encounters data that it can't handle. So we can go fix it.
Interestingly, dsolimano notes that changing the above type to nchar causes the expected error, and Justin Niessner notes that both of these are by design. Strange inconsistency given that nchar is for Unicode support, hey?
From the answers I have here, it appears that I sadly can't make the server throw the error for existing code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
SQL Server 将毫无问题地截断字符串。因此,您可以先将该值转换为
varchar
,然后将其转换为char(2)
:SQL Server will truncate strings without a problem. So you could convert the value to a
varchar
first, and then cast it tochar(2)
:取决于你所说的“防止”这种情况的发生是什么意思?您希望发生什么?没有什么?
Depends what you mean by "prevent" this from happening? What would you like to happen instead? Nothing?
Microsoft 的 转换/转换页面 似乎表明您可以转换为 nchar (2) 如果你想得到一个错误而不是
*
或截断,这确实是我得到的:Microsoft's convert/cast page seems to indicate that you can cast to nchar(2) if you want to get an error instead of
*
or truncation, and indeed that is what I get:向下滚动以下 MSDN 页面:
CAST 和 CONVERT (Transact-SQL)
直到到达标题截断和舍入结果时,
您将看到您所看到的行为是已定义的行为。
如果您希望进行截断以便只得到数字的两位数,那么您可以尝试:
Scroll down the following MSDN Page:
CAST and CONVERT (Transact-SQL)
Until you get to the heading Truncating and Rounding Results
You'll see that the behavior you're seeing is the defined behavior.
If you want the truncation to occur so that you get only two digits of the number, then you can try:
在将其转换为太小的字符串之前,只需将其转换为可变长度字符串即可。
Just cast it to a variable length string before you cast it to a string that is too small.