2017-10-17 57 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);