简体   繁体   English

根据另一条T-SQL语句自动填充列

[英]Autofill a column according to another T-SQL statement

Sorry to disturb you again. 抱歉再次打扰您。 lol :) 大声笑 :)

I am looking at the answers given on similar questions but they are still not very helpful. 我正在寻找有关类似问题的答案,但它们仍然不是很有帮助。

Here's my case: 这是我的情况:

在此处输入图片说明

I want to change the schema on my table to auto fill one column. 我想更改表上的架构以自动填充一列。

What I understand is the update function is only for values, and would not apply when new values will be entered in the future. 我了解的是,更新功能仅适用于值,并且在将来将要输入新值时将不适用。

I want to be able to set the Gname according to the Grade so that I can have. 我希望能够根据等级设置Gname,以便可以使用。 so that I can have 1 for novice or new, 2 for standard, 3- intermediate and 4- Expert. 这样我可以有1个新手或新手,2个标准人,3-中级和4- Expert。

Can someone help please? 有人可以帮忙吗? or direct me towards the right documentation. 或指导我找到正确的文档。

Thanks to you all 谢谢大家

typically this would be done through the use of a lookup table. 通常,这可以通过使用查找表来完成。

So you would have your table you have then add another table for Gname that would carry the Grade Id 1,2,3,4 and the Name. 因此,您将拥有一个表,然后为Gname添加另一个表,该表将带有1、2、3、4级ID和名称。 Then when you want to add that as a column to your query you would do that through joining your gname table with your table on the ID. 然后,当您要将其作为查询列添加时,可以通过将gname表与ID上的表连接起来来实现。

however since sql-server 2008 there is also a Computed Column https://msdn.microsoft.com/en-us/library/ms188300(v=sql.105).aspx 但是自sql-server 2008起,还有一个计算列https://msdn.microsoft.com/zh-cn/library/ms188300(v=sql.105).aspx

If you want to enact the computed column you could alter your table and add it. 如果要制定计算列,可以更改表并将其添加。

ALTER TABLE TableName
ADD ComputedColumnName AS (CASE WHEN Grade = 1 THEN 'novice' WHEN Grade = 2 THEN 'standard'.....END)

Yet another method some programmers use is to not put the lookup anywhere in the database but rather use an enumeration in their application layer to handle the translation. 一些程序员使用的另一种方法是不将查找放在数据库中的任何位置,而是在其应用程序层中使用枚举来处理翻译。

The first method is less demand of storage space in your database and doesn't require schema/table definition change to rename or add additional gnames. 第一种方法是减少数据库中存储空间的需求,并且不需要更改架构/表定义即可重命名或添加其他gname。 Plus it leads to more data integrity, because I have seen enumerations mess up a pretty significant eCommerce site and cause programmers a lot of headaches trying to debug. 另外,它还导致更多的数据完整性,因为我已经看到枚举将一个非常重要的电子商务站点弄乱了,并引起程序员尝试调试的许多麻烦。

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

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