简体   繁体   English

将计算列插入现有表

[英]Inserting calculated column into existing table

I have a column with a string of text inside of it that varies in length.我有一列,里面有一串长度不等的文本。 I want to return the first 4 characters in the string starting from position 1 and output them into a table only if there is a direct match.我想从 position 1 和 output 开始的字符串中的前 4 个字符仅在存在直接匹配时才返回到表中。 So if I want to return just PDFG and not return ADHR or any other combination then the below code works just fine for me.因此,如果我只想返回 PDFG 而不是返回 ADHR 或任何其他组合,那么下面的代码对我来说就可以了。

use DB
select 
substring(description, 1, 4) as newcol from table1 where substring(description, 1, 4) like '%ABCD%'

however I would like to persist this calculated column into an existing table, so something like this;但是我想将此计算列保存到现有表中,所以像这样;

use DB
alter table table1
add newcol as ("and then the rest of the code above")

I am not sure how to reorder my code to fit the new query any help is appreciated.我不确定如何重新排序我的代码以适应新查询,感谢任何帮助。

Here is some sample data:以下是一些示例数据:

  • PDFG_2013 AHSDHDF PDFG_2013 AHSDHDF
  • ADHR_2310 ADGDGEE ADHR_2310 ADGDGEE
  • DATW_5142 NFBSAEE DATW_5142 NFBSAEE

The output from this should be stored in newcol within an existing table called table1.来自此的 output 应存储在名为 table1 的现有表中的 newcol 中。 The only value in new column from the sample data should be PDFG示例数据中新列中的唯一值应为 PDFG

Use a case expression to return the first 4 characters if matching, otherwise null.如果匹配,则使用case表达式返回前 4 个字符,否则返回 null。

Alter table table1
add newcol as case when description like 'ABCD%' then substring(description, 1, 4) end

Or, even simplier或者,甚至更简单

Alter table table1
add newcol as case when description like 'ABCD%' then 'ABCD' end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM