select *
from fb_lab_test
where (report_item_code = 'HBcAb')
or (report_item_code = 'Anti-Hbc' and
case isnumeric(result) when 1 then cast(result as float) else 10000.0 end > 0.2)将数据类型varchar转换为浮动的
错误
这是样本数据
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','-')在这个示例数据中,isnumeric将返回假阳性,但是不应该对case isnumeric(result) when 1 then cast(result as float) else 10000.0 end > 0.2进行评估,因为在示例日期中没有名为‘Anti’的report_item_code,这很奇怪。
发布于 2020-08-03 11:47:06
根本不要使用isnumeric()。只需使用try_函数:
select t.*
from fb_lab_test t
where report_item_code = 'HBcAb' or
(report_item_code = 'Anti-Hbc' and
coalesce(try_cast(float_result), 10000.0) > 0.2
);避免在case子句中使用where表达式也是一个好主意。他们基本上是短路优化器。
在本例中,您希望包含非数字值。更常见的是,这将被排除在外。您可以让NULL比较排除它们。这种逻辑是:
select t.*
from fb_lab_test t
where report_item_code = 'HBcAb' or
(report_item_code = 'Anti-Hbc' and
try_cast(float_result) > 0.2 -- excludes non-NULL values
);https://stackoverflow.com/questions/63224190
复制相似问题