检查列是否有“字母”或“-”,然后从另一列中获取值

问题描述 投票:0回答:2

我有表 1 数据,我需要根据条件创建另一列

如果 ID 有“-”或“任何字母”,则从发票中获取价值

表1

+---------+---------+
|   id    | invoice |
+---------+---------+
| 1234    |    2534 |
| 9870    |    6542 |
| ABC234  |    9874 |
| 34-5469 |  325416 |
+---------+---------+

预期结果为 id2

+---------+---------+--------+
|   id    | invoice |  id2   |
+---------+---------+--------+
| 1234    |    2534 |   1234 |
| 9870    |    6542 |   9870 |
| ABC234  |    9874 |   9874 |
| 34-5469 |  325416 | 325416 |
+---------+---------+--------+
sql sql-server
2个回答
2
投票

您可以使用

isnumeric
函数来判断 id 是否为
int

select *,
case when isnumeric(id) = 1 then id else invoice end as id2
from [yourtable]

isnumeric
并不总是提供可靠的结果,因此,如果您使用 SQL Server 2012 或 2014 及更高版本,您可能会选择
try_cast

select * 
,case when try_cast(id as int) is not null then id else invoice end as id2
from [yourtable]

2
投票

假设您只是在寻找具有字母或连字符(

-
)的值,您可以使用
CASE
表达式和
LIKE
,如下所示:

SELECT CASE WHEN id LIKE '%[A-z-]%' THEN invoice ELSE id END
FROM dbo.YourTable;

然而,更好的方法是检查

id
是否不重视除数字之外的任何字符:

SELECT CASE WHEN id LIKE '%[^0-9]%' THEN invoice ELSE id END
FROM dbo.YourTable;
© www.soinside.com 2019 - 2024. All rights reserved.