gpt4 book ai didi

sql-server - 如果不是数字或 SQL 中的实际数值,则获取 null

转载 作者:行者123 更新时间:2023-12-03 16:38:05 25 4
gpt4 key购买 nike

如果 isnumeric() 函数返回 1 或 NULL(如果它返回 0),我正在尝试获取字符串的数值。但我只在它是数字时获取,如果非数字,我将获取 1 或 null。是否可以使用类似下面的代码返回数值(而不是 1)?

select '14-154877-0' as actual_string, replace('14-154877-0', '-', '') as numeric_value, nullif(isnumeric(replace('14-154877-0', '-', '')), 0) as numeric_value_or_null /* Here I wold like to return the numeric value instead of 1 */

select 'some text' as actual_string, replace('some text', '-', '') as numeric_value, nullif(isnumeric(replace('some text', '-', '')), 0) as numeric_value_or_null /* OK */

示例数据

插入语句是 excel 连接函数的结果。

如前所述,我使用了 case 表达式和 try_convert()(对于 MSSQL 2012)函数,它们工作正常。有没有更好的方法来进行这种插入?

if object_id('tempdb..#temp_table') is not null
begin
drop table #temp_table;
end;

create table #temp_table (
int_column int,
varchar_column varchar(50)
);

insert into #temp_table (int_column, varchar_column) values (case when isnumeric(replace('111----111', '-', '')) = 1 then replace('111----111', '-', '') end, 'string data 1');
insert into #temp_table (int_column, varchar_column) values (case when isnumeric(replace('text', '-', '')) = 1 then replace('text', '-', '') end, 'string data 2');
insert into #temp_table (int_column, varchar_column) values (try_convert(int, replace('258--', '-', '')), 'string data 3');
insert into #temp_table (int_column, varchar_column) values (try_convert(int, replace('123', '-', '')), 'string data 4');

select * from #temp_table;

/*
| int_column | varchar_column |
| 111111 | string data 1 |
| NULL | string data 2 |
| 258 | string data 3 |
| 123 | string data 4 |
*/

最佳答案

也许:

SELECT value as actual_string
, replace(value, '-', '') as numeric_value
, CASE ISNUMERIC(replace(value, '-', ''))
WHEN 1 THEN CAST(replace(value, '-', '') AS FLOAT)
ELSE NULL END AS numeric_value_or_null
FROM TableName

Fiddle inside

关于sql-server - 如果不是数字或 SQL 中的实际数值,则获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13379208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com