2017-10-17 31 views
1

我有一列需要拆分和更新2其他列字符串的SQL。SQL拆分和更新

column a : 
1000 aa testing it 
1000 bb tested 
1000 cc done 
1000 dd complete 

我有一个名为柱后,其中有2个字母的数字必须进来 和我有一个名为列状况,在这里休息得来

这一定是最终的结果:

column post: 
1000 aa 
1000 bb 
1000 cc 
1000 dd 

列状态必须为

testing it 
tested 
done 
complete 
+0

的Microsoft SQL Server managemnet工作室 –

+0

是否所有的值列如下相同的模式?即1000个aa,1000个bb等 –

+0

请尝试下面的通用解决方案。我根据第二个空格分隔了字符串。希望它有帮助 –

回答

2
update table_name 
set post SUBSTRING(a, 1, 7) 

update table_name 
set status SUBSTRING(a, 9, 100) 

(即100只是为了确保你把所有)

+0

谢谢,这是最简单的方法;) –

2

使用窗口Substring功能:

结果:

column a   column post column status 
1000 aa testing it 1000 aa  testing it 
1000 bb tested  1000 bb  tested 
1000 cc done  1000 cc  done  
1000 dd complete 1000 dd  complete 

Click here用于演示

+1

如果他有像'100000 dd完整'的数据怎么办? –

+0

问题中的每一行都遵循相同的模式。因此,我在查询中也遵循了这个模式。 –

+0

不,你可能是在这里,但总是试图用OP(如你问)澄清它或提供通用的解决方案,将照顾所有场景:) –

3

有一个在第二空间拆分串的逻辑。

declare @name varchar(100) 
set @name = '1000 aa testing it' 

SELECT @name as original_string, 
substring(@name, 1,charindex(' ', @name, CHARINDEX(' ',@name) + 1)) as post , 
substring(@name, charindex(' ', @name, CHARINDEX(' ',@name) + 1),len(@name)-charindex(' ', @name, CHARINDEX(' ',@name) + 1)+1) as status 

输出:

original_string  post  status 
------------------- -------- ------------ 
1000 aa testing it 1000 aa testing it 

sql demo

1

这应有助于逻辑找到第1和第2个空的发生,并用它拆分字符串。 Demo

create table t(str varchar(100)); 

insert into t(str) values('1000 aa testing it'); 
insert into t(str) values('1000 bb tested'); 
insert into t(str) values('1000 cc done'); 
insert into t(str) values('1000 dd complete') 
insert into t(str) values('10000 dd complete'); --Test Case found in comment 


select substring(str, 1, P2.Pos - 1) as [column post] 
     ,substring(str, P2.Pos +1, len(str)) as [column status] 
from t 
cross apply (select (charindex(' ', str))) as P1(Pos) 
cross apply (select (charindex(' ', str, P1.Pos+1))) as P2(Pos);