简体   繁体   English

MS SQL Server比较数字列与字符串值

[英]Ms Sql Server Compare Numeric column with string value

In MS SQL Server, what is the difference between: 在MS SQL Server中,有什么区别:

select * from Person where Id='7'

and

select * from Person where Id=7

The two queries returns the same results. 这两个查询返回相同的结果。

The Id type is int . Id类型为int

should we not compare int to string? 我们不应该将int与string进行比较吗?

and when should use one of them? 什么时候应该使用其中之一?

Always compare with the same data type and avoid implicit conversions. 始终将相同的数据类型进行比较,并避免隐式转换。

SELECT 'Not OK!' WHERE 'text' = 1
-- Result: Conversion failed when converting the varchar value 'text' to data type int.

As stated by the data type precedence, when there is a mismatch of the data types, the SQL engine will (in most cases) try to convert the most complex type to the simplest, so comparisons are faster. 如数据类型优先级所述,当数据类型不匹配时,SQL引擎(在大多数情况下)将尝试将最复杂的类型转换为最简单的类型,因此比较会更快。 In this case ( VARCHAR vs. INT ), it will always convert the string type to int. 在这种情况下( VARCHARINT ),它将始终将字符串类型转换为int。

Also, when coding SQL that has implicit conversions with joins and other operations, it's most likely to generate a different execution plan that the one it would with an explicit conversion. 另外,在对具有通过联接和其他操作进行隐式转换的SQL进行编码时,最有可能生成与通过显式转换生成的执行计划不同的执行计划。

If you have to compare different types, remember to explicitly cast them, not just for the reason mentioned before but it also says to the next developer that the columns or expressions differ in data type. 如果必须比较不同的类型,切记要显式地强制转换它们,这不仅是因为前面提到的原因,而且还告诉下一个开发人员数据类型不同的列或表达式。

SELECT 'OK!' WHERE 'text' = CONVERT(VARCHAR(10), 1)

With some data type you might find unwanted behaviour if you leave implicit conversions. 对于某些数据类型,如果您保留隐式转换,则可能会发现不需要的行为。

DECLARE @BitValue1 BIT = NULL
DECLARE @BitValue2 BIT = 1

SELECT
    'Oops!'
WHERE
    ISNULL(@BitValue1, -999) = ISNULL(@BitValue2, -999)

-- Result: Oops! (-999 is being converted to bit, which is 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM