简体   繁体   中英

SQL Server Update Column based on value from another table

Please assist if I should use a trigger or procedure. I am trying to update the ScaleRating in table GSelfAssessment from GRatingScale if the Score in GSelfAssessment falls between the minimum and maximum score in GRatingScale.

GSelfAssessment table

在此处输入图片说明

GRatingScale Table

在此处输入图片说明

Preferably this should be achieved for each row on either update or insert. I believe SQL trigger is the most appropriate one. I understand the inserted/deleted concept inside a trigger after my research. Eg

CREATE TRIGGER [dbo].[TR_GSelfAssessment_update] ON [dbo].[GSelfAssessment]
FOR UPDATE
AS
BEGIN

    UPDATE GSelfAssessment
    SET GSelfAssessment.ScaleRating= (Select )---this is where i have a problem-----
  END

I believe there is Guru out here who can give me solution to this. I will learn a lot.

SQL Server supports computed columns. If you want ScaleRating to always be aligned with the rest of the data, then that is the best approach:

alter table GSelfAssessment
    add ScaleRating as ( . . . );

This adds a new "column" that gets calculated when the value is used in a query. If the computation is expensive or you want to build an index, then use persisted so the value is actually stored with the rest of the data -- and recalculated when needed.

You can add the computed column in the create table statement as well. If you have already created the table, you can drop the column and re-add it or modify it.

You should not have that column. Join to the rating table when you need to. You can create a view if it makes it easier.

select … 
from GSelfAssessment  a
inner join 
GRatingScale  r 
on (a.Score>r.MinScore and a.Score<=r.MaxScore)

Adjust/create view as required

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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