【发布时间】:2012-11-02 23:19:29
【问题描述】:
如果 isumeric() 函数返回 1,则我试图获取字符串的数值,如果返回 0,则返回 NULL。但我只有在它是数字时才会得到 1,如果不是数字,我会得到 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 |
*/
【问题讨论】:
-
可以发布具有期望结果的示例数据吗? :D
-
我添加了一些示例代码,因为我想使用它。如果 isumeric() 返回 1,我只想插入列的数值,否则插入 NULL 值。我正在使用 SQL Server 2012。
标签: sql-server tsql isnumeric