【问题标题】:How to fill a column automatically from special values in other column?如何从其他列中的特殊值自动填充列?
【发布时间】:2016-06-15 11:22:30
【问题描述】:

我有个小问题,我有一张这样的桌子

ref_id |ref_name                 | ref_Type     | ref_debit
1      |BVPG Corporate 2M Spain  |              |
2      |BVPG Small 5M 54FZE      |              |
3      |BVPG Corporate 1M Spain  |              |

我想自动填充列 ref_type 和 ref debit。
我手动做了一个子字符串(只是我的许多查询的一部分)

UPDATE t
SET t.ref_type = (substring(t.ref_name,6,10))
FROM ref_table t
INNER JOIN ref_table t1 on t1.ref_id = t.ref_id AND t1.ref_name LIKE'BVBG C%'

如果是 BVPG Corporate 或 Small 我有类似的东西

ref_id |ref_name                 | ref_Type     | ref_debit
1      |BVPG Corporate 2M Spain  | Corporate    | 2M
2      |BVPG Small 5M 54FZE      | Small        | 5M
3      |BVPG Corporate 1M Spain  | Corporate    | 1M

这就是我想要的,我知道该怎么做。 但是当我有一个新行时,我想自动生成这个结果。
我考虑过触发器,但我正在使用 SQL Server Management Studio 我不知道该怎么做,我什至不知道触发器是否是最好的解决方案。

我尝试了类似的方法,但它不起作用(所有行都会更新,即使它以 'BVPG C' 开头)

    if exists(
        select ref_name
        from inserted
        where ref_name like 'BVPG S%')   
      then update

【问题讨论】:

    标签: tsql stored-procedures triggers


    【解决方案1】:

    不要使用触发器 - 您需要一个计算列(请参阅 MSDN)。所以删除你的列并重新添加它们:

    ALTER TABLE ref_table
    ADD ref_type AS substring(ref_name,charindex(' ', ref_name) + 1, charindex(' ', ref_name, charindex(' ', ref_name) + 1) - charindex(' ', ref_name) - 1)
    

    对 ref_debit 执行类似操作。

    虽然你最好在应用程序而不是数据库中进行这种字符串操作...

    【讨论】:

    • 我明白了,谢谢我会努力的。但是,如果我决定在我的应用程序中包含这种操作,那不会降低我的应用程序的性能吗?
    • 这取决于您如何使用计算列。如果您要使用这些值执行搜索,甚至可以索引列,那么通过 SQL 以这种方式执行此操作是值得的。但是,如果您只是为了显示这些值而将它们分开,那么使用具有更好的字符串操作性能和功能的语言进行操作会更好。
    猜你喜欢
    • 2021-06-19
    • 2020-02-04
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多