且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

奇怪的SQL Server类型转换问题

更新时间:2023-01-29 14:17:34

由于数据类型优先级

为此,UI列将更改为十进制(25 ,0)

For this, the UI column will be changed to decimal(25,0)

where UI = 2011040773395012950010370

这几乎是正确的。右边是varchar,并更改为nvarchar

This one is almost correct. The right hand side is varchar and is changed to nvarchar

where UI = '2011040773395012950010370'

这是真正的正确版本,两种类型都相同

This is the really correct version where both types are the same

where UI = N'2011040773395012950010370'

错误之所以会开始,是因为 UI列现在包含一个不能将CAST转换为十进制(25,0)的值。

Errors will have started because the UI column now contains a value that won't CAST to decimal(25,0).

一些不相关的注释:


  • 如果您在UI列上有索引,则由于需要隐式CAST,在第一个版本中会将其忽略

  • 您需要使用unicode来存储数字吗?有一个严重的开销,其中存储和性能具有Unicode数据类型

  • 为什么不使用 char(25) nchar(25)是值始终固定长度?您的查询使用存储空间过多,无法达到优化要求根据 nvarchar(256)

  • if you have an index on the UI column it would be ignored in the first version because of the implicit CAST required
  • do you need unicode to store numeric digits? There is a serious overhead with unicode data types in storage and performance
  • why not use char(25) or nchar(25) is values are always fixed length? Your queries use too much memory as the optimiser assumes an average length of 128 characters based on nvarchar(256)

假定平均长度为128个字符编辑,在评论后

Edit, after comment

当您不知道起作用时,不要假定有时为什么起作用

Don't assume "why does it works sometimes" when you don't know that it does work

示例:


  • 该值本可以删除然后再添加

  • 一个TOP子句或SET ROWCOUNT可能意味着未达到有问题的值

  • 该查询从未运行过,因此不会失败

  • 该错误是否被其他代码静默忽略?

  • The value could have been deleted then added later
  • A TOP clause or SET ROWCOUNT could mean the offending value is not reached
  • The query was never run so it couldn't fail
  • The error is silently ignored by some other code?

编辑2以获得更多清晰度

Edit 2 for hopefully more clarity

聊天

gbn:


当您运行WHERE UI = 2011040773395012950010370时,您不知道行访问的顺序。因此,如果一行确实有自行车,您可能会也可能不会点击该行。

When you run WHERE UI = 2011040773395012950010370, you do not know the order of row access. So if one row does have "bicycle" you may or may not hit that row.

随机:


所以问题可能不在我尝试访问的行中,而是其他值损坏的行?

So the problem may be not in the row which i was trying to access but other one with corrupted value?

gbn


根据服务包级别,索引和表,不同的机器将具有不同的读取顺序碎片,CPU数量,并行度

different machines will have different order of reads based on service pack level, index and table fragmentation, number of CPUs, parallelism maybe

正确

甚至是TOP。这类东西

and TOP even. That kind of stuff

正如Tao提到的,重要的是要了解另一个不相关的东西甚至可以使查询中断

As Tao mentions, it's important to understand that another unrelated can break the query even if this one is OK.


数据类型优先级会导致该列中的所有数据在计算where子句之前都被转换

data type precedence can cause ALL the data in that column to be converted before the where clause is evaluated