gufran gufran - 3 months ago 6
SQL Question

How to save my query (formula) in SQL Server

I have a default table like this

+--+----------+--------+------+
|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 |
+--+----------+--------+------+


which will be executed by

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 |
+--+----------+--------+------+


How to save this query? So that when I insert new data, this query is automatically executed

I'm use sql server management studio 2012

zpc zpc
Answer

maybe you can used the tigger like below

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