我有一个数据集(大约900k行),我需要根据'('或')'分割数据。例如 表A数据: -
> Vendor Is_Active
ABC(1263) 1
efgh (187 1
pqrs 890ag) 1
xyz 1
lmno(488) 1
(9867-12) 1
输出
ID Name
1263 ABC
187 efgh
890ag pqrs
xyz
488 lmno
9867-12
我尝试了查询
SELECT
vendor,
CASE WHEN vendor LIKE '%(%' OR vendor LIKE '%)%'
THEN REPLACE(REPLACE(RIGHT(Vendor, charindex(' ', reverse(vendor)) - 1),'(',''),')','')
END AS 'test'
FROM
tableA
错误: - 消息536,级别16,状态4,行13无效长度参数 传递给RIGHT函数。
答案 0 :(得分:1)
嗯。我在想:
select v.*, v2.name,
replace(stuff(v.x, 1, len(v2.name) + 1, ''), ')', '') as id
from (values ('ABC(1263)'), ('abc'), ('(1234)')) v(x) cross apply
(values (left(v.x, charindex('(', v.x + '(') - 1))) v2(name);
我发现apply
对重复的字符串操作很有用。
答案 1 :(得分:1)
SELECT
(CASE WHEN Vendor LIKE '%(%)' THEN SUBSTRING(Vendor,CHARINDEX('(',Vendor)+1,CHARINDEX(')',Vendor)-CHARINDEX('(',Vendor)-1)
WHEN Vendor LIKE '%(%' THEN SUBSTRING(Vendor,CHARINDEX('(',Vendor)+1,LEN(Vendor))
WHEN Vendor LIKE '%)%' THEN SUBSTRING(Vendor,CHARINDEX(' ',Vendor)+1,(CHARINDEX(')',Vendor)-CHARINDEX(' ',Vendor))-1)
ELSE ''
END )AS ID ,
(CASE WHEN Vendor LIKE '%(%)' THEN SUBSTRING(Vendor,1,CHARINDEX('(',Vendor)-1)
WHEN Vendor LIKE '%(%' THEN SUBSTRING(Vendor,1,CHARINDEX('(',Vendor)-1)
WHEN Vendor LIKE '%)%' THEN SUBSTRING(Vendor,1,CHARINDEX(' ',Vendor))
ELSE Vendor END ) AS Name
FROM Table A
答案 2 :(得分:1)
您可以删除字符(
和)
,然后搜索号码。检查此查询
declare @t table (
vendor varchar(100)
)
insert into @t values
('ABC(1263)')
,('efgh (187')
,('pqrs 890ag)')
,('xyz')
,('lmno(488)')
,('(9867-12)')
select
ID = case when p = 0 then '' else substring(v, p, len(v)) end
, Name = case when p = 0 then v else left(v, p - 1) end
from
@t
cross apply (select v = replace(replace(vendor, '(', ''), ')', '')) q1
cross apply (select p = patindex('%[0-9]%', v)) q2
输出
ID Name
---------------
1263 ABC
187 efgh
890ag pqrs
xyz
488 lmno
9867-12