简体   繁体   English

SQL CASE 语句需要处理 Text

[英]SQL CASE statement needs to handle Text

Apologies if this has been asked before - I've spent a couple of hours searching but not found anything that's helped.抱歉,如果之前有人问过这个问题 - 我花了几个小时搜索但没有找到任何有帮助的东西。

It's quite simple really - I've been asked to create a query which includes a field that when it was set up (not by me) was created as a VARCHAR instead of an INT.这真的很简单 - 我被要求创建一个查询,其中包含一个字段,该字段在设置时(不是由我)创建为 VARCHAR 而不是 INT。

I need to do some calculations on this field, however some users have been entering text into it, so the calculations fail as it can't convert the data to an INT.我需要对这个字段做一些计算,但是有些用户已经在其中输入了文本,因此计算失败,因为它无法将数据转换为 INT。

Is there anything I can add to a CASE statement to handle where there's text?有什么我可以添加到 CASE 语句来处理有文本的地方吗?

I was thinking something like the below, but don't know what the actual code is:我在想类似下面的东西,但不知道实际的代码是什么:

CASE
    WHEN [Field1] IS TEXT THEN 1 ;
    ELSE [Field2] as [Chose name]
END

Edit: Note that this is in MS SQL Server.编辑:请注意,这是在 MS SQL Server 中。 Thanks.谢谢。

In SQL Server, you can use try_convert() and isnull() for this:在 SQL Server 中,您可以try_convert()使用try_convert()isnull()

isnull(try_convert(int, field), 1)

try_convert() attempts you cast field to an int . try_convert()尝试将field转换为int When that fails, null is returned;如果失败,则返回null you can trap that with isnull() and turn the result to 1 instead.您可以使用isnull()捕获它并将结果改为1

Note that this only works as long as field is not null (otherwise, you would get 1 as a result).请注意,这仅在field不为null时才有效(否则,您将获得1结果)。

In SQL Server在 SQL Server 中

Declare @Salary varchar(100);                                
Set @Salary = 50000;                                       
Select Case when ISNUMERIC(@Salary) = 1 then 1 
            else 0 end as [Check]

May be this will be Helpful.可能这会有所帮助。

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

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