2015-11-08 52 views
0

如用於列(xx)的列(xx)其中數據類型爲varchar並且其中包含值,例如'cons','alts'以將其轉換以int ... 如果不可能這樣做我們有什麼其他選項是否有可能在列中已經有數據時更改列的數據類型

+0

不能'cons,alts'不能轉換爲'INT'。可能只有當**現有數據隱式轉換爲INT時 –

+0

如果你有一個預定義的對應關係,即cons = 1 alts = 2等,如果你沒有那麼多的值可能是可能的 – Mihai

+0

如果你不能進行隱式轉換,你總是可以使用update語句將數據修改爲允許它的值 - 比如cons = 1,ALTs = 2等 – Takarii

回答

0

更新後的值。事情是這樣的:

update t 
    set column = NULL 
    where column not like '%[^0-9]%' or column not like '-[^0-9]%'; 

alter t alter column int; 

一旦值是有效的,你應該能夠修改類型,在列假設一堆其他條件(涉及限制使用等)。

編輯:

如果你想創建一個參考表,通常你會添加新列。這是討厭的,因爲列被重新排序。所以,你可以使用這個技巧:

create table columnRef (
    columnRefId int not null identity primarykey, 
    value varchar(255) unique 
); 

insert into columnRef(value) 
    select distinct column from t; 

alter table t add newvalue varchar(255); 

update t newvalue = column; 

update t 
    column = cast(columnRefId as varchar(255)) 
    from t join 
     columnRef cr 
     on t.newvalue = cr.value; 

alter t modify column int; 

alter t drop newvalue; 

寫在這之後,我意識到,你不需要newvalue。但是,不知何故,我不適合修改用於join的列中的數據,並且之後無法檢查準確性。