簡體   English   中英

當列中已經有數據時,是否可以更改列的數據類型

[英]is it possible to change data type of column when the column already has data in it

例如數據類型為varchar的列(xx),其中包含值,例如“ cons”,“ alts”,以將其轉換為int ...如果無法這樣做,我們還有哪些其他選擇

更新值之后。 像這樣:

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的列中的數據,並且此后無法檢查准確性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM