如何在SQL Server中保存我的查询(公式)

时间:2016-09-05 00:28:52

标签: sql sql-server sql-server-2012

我有一个像这样的默认表

+--+----------+--------+------+
|Id|class_name|class_id|medals|
+--+----------+--------+------+
|1 |7IPA1     |7       |3     |
|2 |7IPA2     |7       |2     |
|3 |7IPA3     |7       |5     |
|4 |8IPA1     |8       |1     |
|5 |8IPA2     |8       |7     |
|6 |8IPA3     |8       |3     |
+--+----------+--------+------+

将由

执行
UPDATE MYTABLE 
SET CLASS_ID = SUBSTRING(CLASS_NAME,1,4)


+--+----------+--------+------+
|Id|class_name|class_id|medals|
+--+----------+--------+------+
|1 |7IPA1     |7IPA    |3     |
|2 |7IPA2     |7IPA    |2     |
|3 |7IPA3     |7IPA    |5     |
|4 |8IPA1     |8IPA    |1     |
|5 |8IPA2     |8IPA    |7     |
|6 |8IPA3     |8IPA    |3     |
+--+----------+--------+------+

如何保存此查询?因此,当我插入新数据时,会自动执行此查询

我正在使用sql server management studio 2012

3 个答案:

答案 0 :(得分:2)

您不希望将此作为更新。相反,您希望拥有计算列

alter table mytable add class_id as (left(class_name, 4));

当然,在执行此命令之前,您需要确保列名(class_id)不在表中。

答案 1 :(得分:1)

也许你可以使用下面的跳跳器

create trigger trigger_class_id on MYTABLE 
After 
  insert
as 
UPDATE 
  MYTABLE 
SET 
  CLASS_ID = SUBSTRING(CLASS_NAME, 1, 4) WHERE ID=inserted.ID

答案 2 :(得分:0)

您可以使用tigger或添加此查询以及插入查询。  那么你的查询就是。

Insert into MYTABLE (class_name,class_id,medals) values('','','')
UPDATE MYTABLE 
SET CLASS_ID = SUBSTRING(CLASS_NAME,1,4)