当 ISNUMERIC 等于 1 时,将 nvarchar 转换为 int
CAST nvarchar to int when ISNUMERIC equal 1
我有 table 和 varchar
列。
我需要做的是 select 在此列中具有数值但值介于 100 和 150 之间的所有行
下面的示例代码包含一些数据:
create table test (number nvarchar(10))
insert into test (number) values ('100'), ('140'), ('222ass'), ('2'), ('some text')
第一个想到的是:
select * from test where isnumeric(number) = 1 and cast(number as int) between 100 and 150
但是错误:
Conversion failed when converting the nvarchar value 'some text' to data type int.
注意:当字段为 varchar
时 - 此代码工作正常。
下次试试。我使用子查询。为什么?我认为在子查询中我会有正确的值(子查询中的条件 ISNUMERIC
)并且我可以毫无问题地进行 make cast:
select
number
from (
SELECT
number
FROM test
where isnumeric(number) = 1) ds
where number between 100 and 150
但也有ERROR(同上)
在这个错误之后我抓住了最后的希望(目前的思路)。我添加了第三个子查询:)
select *
from (
select
cast(number as int) n
from (
SELECT
number
FROM test
where isnumeric(number) = 1) ds
) ds2
where n between 100 and 150
但是又出错了:(
知道如何解决我的问题吗?
我也很高兴找出为什么会出现此错误。为什么 MSSQL 不想转换我的数据?
感谢帮助!
PS。 MSSQL 2008 R2
如果您使用 SQL Server 2012 或更高版本,TRY_CONVERT 将解决您的问题:
TRY_CONVERT(int, number)
returns number
转换为 int
,如果这样的转换是可能的,否则 NULL
。
您可以这样使用 CASE
:
SELECT number
FROM (
SELECT CASE WHEN isnumeric(number) = 1 THEN number
ELSE CAST (NULL AS int)
END AS number
FROM test) t
WHERE number BETWEEN 100 and 150
我有 table 和 varchar
列。
我需要做的是 select 在此列中具有数值但值介于 100 和 150 之间的所有行
下面的示例代码包含一些数据:
create table test (number nvarchar(10))
insert into test (number) values ('100'), ('140'), ('222ass'), ('2'), ('some text')
第一个想到的是:
select * from test where isnumeric(number) = 1 and cast(number as int) between 100 and 150
但是错误:
Conversion failed when converting the nvarchar value 'some text' to data type int.
注意:当字段为 varchar
时 - 此代码工作正常。
下次试试。我使用子查询。为什么?我认为在子查询中我会有正确的值(子查询中的条件 ISNUMERIC
)并且我可以毫无问题地进行 make cast:
select
number
from (
SELECT
number
FROM test
where isnumeric(number) = 1) ds
where number between 100 and 150
但也有ERROR(同上)
在这个错误之后我抓住了最后的希望(目前的思路)。我添加了第三个子查询:)
select *
from (
select
cast(number as int) n
from (
SELECT
number
FROM test
where isnumeric(number) = 1) ds
) ds2
where n between 100 and 150
但是又出错了:(
知道如何解决我的问题吗? 我也很高兴找出为什么会出现此错误。为什么 MSSQL 不想转换我的数据?
感谢帮助!
PS。 MSSQL 2008 R2
如果您使用 SQL Server 2012 或更高版本,TRY_CONVERT 将解决您的问题:
TRY_CONVERT(int, number)
returns number
转换为 int
,如果这样的转换是可能的,否则 NULL
。
您可以这样使用 CASE
:
SELECT number
FROM (
SELECT CASE WHEN isnumeric(number) = 1 THEN number
ELSE CAST (NULL AS int)
END AS number
FROM test) t
WHERE number BETWEEN 100 and 150