[英]Inserting calculated column into existing table
我有一列,里面有一串長度不等的文本。 我想從 position 1 和 output 開始的字符串中的前 4 個字符僅在存在直接匹配時才返回到表中。 因此,如果我只想返回 PDFG 而不是返回 ADHR 或任何其他組合,那么下面的代碼對我來說就可以了。
use DB
select
substring(description, 1, 4) as newcol from table1 where substring(description, 1, 4) like '%ABCD%'
但是我想將此計算列保存到現有表中,所以像這樣;
use DB
alter table table1
add newcol as ("and then the rest of the code above")
我不確定如何重新排序我的代碼以適應新查詢,感謝任何幫助。
以下是一些示例數據:
來自此的 output 應存儲在名為 table1 的現有表中的 newcol 中。 示例數據中新列中的唯一值應為 PDFG
如果匹配,則使用case
表達式返回前 4 個字符,否則返回 null。
Alter table table1
add newcol as case when description like 'ABCD%' then substring(description, 1, 4) end
或者,甚至更簡單
Alter table table1
add newcol as case when description like 'ABCD%' then 'ABCD' end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.