简体   繁体   English

SQL ASP.NET-将nvarchar转换为int(如果为数字)

[英]SQL ASP.NET - Convert nvarchar to int if numeric

I have an nvarchar field called [DBO] which contains either a numeric age (like 32) or other nvarchar valuesl ike Unknown or 12/10/2013 我有一个名为[DBO]的nvarchar字段,其中包含数字年龄(如32)或其他nvarchar值,例如Unknown或12/10/2013

What I'm trying to achieve is to convert [DBO] to int if it's numeric. 我要实现的是将[DBO]转换为数字(如果为数字)。 This is the code I currently have, but it's obviously not working. 这是我目前拥有的代码,但显然不起作用。

SELECT * FROM [PeopleTable] WHERE CAST([DBO] AS INT)=32

It always gives me an error for [DBO]'s value not being an int. 由于[DBO]的值不是整数,总是给我一个错误。 I was trying to use "CASE" but I can't see how to implement that in my command. 我试图使用“ CASE”,但看不到如何在命令中实现。

You should be able to pull all records that are numeric only and then do your cast. 您应该能够提取仅数字记录的所有记录,然后进行转换。

SELECT * 
FROM [PeopleTable] P
WHERE CAST(P.[DBO] AS INT) = 32
AND ISNUMERIC(P.[DBO]) = 1

Try this: 尝试这个:

SELECT * FROM [PeopleTable] P
WHERE ISNUMERIC(P.[DBO]) = 1) AND CAST(P.[DBO] AS INT) = 32

I would use 我会用

select 
    convert(int,[dbo])
from @t
where not ([dbo] like '%[^0-9]%')

If you use ISNUMERIC , you'll get an error if you have a decimal value in your data. 如果使用ISNUMERIC ,则如果数据中有十进制值,则会出现错误。

SELECT * FROM
            (
            SELECT *,
              CAST((CASE isnumeric(ColumnName) 
                      WHEN 0 THEN NULL 
                      ELSE CAST(ColumnName AS DECIMAL(10, 2)) 
                    END) AS INT) AS ColumnName1 
            FROM tablename
            ) T
WHERE ColumnName1 = yourNumber

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

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