首页 > 解决方案 > 查询时报错(Error convert data type varchar to float)

问题描述

select * from fb_lab_test 
where (report_item_code = 'HBcAb' and result like '%positive%') 
or (
    report_item_code = 'Anti-Hbc' and 
    case isnumeric(result) when 1 then cast(result as float) else 10000.0 end > 0.2
)

我在这个 SQL 中有两个条件,当我使用它们中的任何一个时,都没有错误,但是当我添加 时OR,出现错误:

将数据类型 varchar 转换为 float 时出错

任何人都可以帮忙吗?非常感谢。

这是示例数据

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE fb_lab_test(
    [id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Test_No] [varchar](50) NULL,
    [execute_date] [datetime] NULL,
    [PatientId] [varchar](20) NULL,
    [Visit_Id] [varchar](10) NULL,
    [Patient_Type] [int] NULL,
    [PatientName] [varchar](100) NULL,
    [result_date_time] [datetime] NULL,
    [report_item_name] [varchar](256) NULL,
    [report_item_code] [varchar](50) NULL,
    [result] [varchar](100) NULL
) ON [PRIMARY]
GO

INSERT INTO fb_lab_test values('5910315197','2019-10-31 00:40:53.000','111111','1','1','Tom','2019-10-31 08:56:54.000','test1','KET','-')

标签: sqlsql-serverdatabase

解决方案


SQL Server 可以使用转换值的表达式变得非常有趣。即使看起来是否应该被过滤掉,有时查询处理器还是会评估这些值。有时您可以通过稍微更改查询来解决它。

尝试 ...

select * from fb_lab_test where (report_item_code = 'HBcAb' and result like '%positive%')
union 
select * from fb_lab_test where report_item_code = 'Anti-Hbc' and 
    case isnumeric(result) when 1 then cast(result as float) else 10000.0 end > 0.2

推荐阅读