简体   繁体   English

为什么SQL Server尝试将我的nvarchar(20)数据类型转换为int?

[英]Why is SQL Server trying to convert my nvarchar(20) datatype to an int?

I'm getting the "conversion" error in a SQL Select query. 我在SQL Select查询中收到“转换”错误。

The error is: 错误是:

Msg 248, Level 16, State 1, Line 6 Msg 248,Level 16,State 1,Line 6
The conversion of the nvarchar value '7000952682' overflowed an int column. nvarchar值'7000952682'的转换溢出了一个int列。

Problem is, there are no int columns in my table! 问题是,我的表中没有int列!

Here is the table structure: 这是表结构:

在此输入图像描述

Here is the query: 这是查询:

在此输入图像描述

If I set the value of @SU to NULL , then it does return all rows as expected. 如果我将@SU的值设置为NULL ,那么它会按预期返回所有行。 When the value is set to the string value of '7000952682' I get the error. 当值设置为字符串值'7000952682'时,我收到错误。

Why is SQL Server trying to convert the nvarchar value to an int? 为什么SQL Server尝试将nvarchar值转换为int?

All branches of a CASE expression have to have the same type. CASE表达式的所有分支必须具有相同的类型。 In this case (no pun intended), it looks like SQL Server is using an integer type and doing an implicit cast of SU to integer. 在这种情况下(没有双关语),看起来SQL Server正在使用整数类型并对SU执行隐式转换为整数。 The problem is that the max value for an integer in SQL Server is roughly 2.1 billion, and the example you gave is using the value 7000952682 , hence the overflow. 问题是SQL Server中一个整数的最大值大约是21亿,你给出的例子是使用值7000952682 ,因此溢出。

You have two options here. 你有两个选择。 You could make everything varchar : 你可以做一切varchar

CASE WHEN @SU IS NULL OR @SU = '' THEN '1' ELSE [SU] END

Or, you could make everything numeric, using a type that won't overflow, eg 或者,您可以使用不会溢出的类型将所有内容都设为数字,例如

CASE WHEN @SU IS NULL OR @SU = ''
     THEN CAST(1 AS numeric(20, 6))
     ELSE CAST([SU] AS numeric(20, 6)) END

As a side note, you could write the first part of your CASE expression more succinctly using COALESCE : 作为旁注,您可以使用COALESCE更简洁地编写CASE表达式的第一部分:

CASE WHEN COALESCE(@SU, '') = '' THEN '1' ELSE [SU] END

Don't use case in the where clause. 不要在where子句中使用case The logic is more simply and accurately expressed as: 逻辑更简单,更准确地表达为:

where (@su is null or @su = '' or @su = su)

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

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