简体   繁体   中英

Procedure to compare two columns from different tables and make the insert

I have two tables:

  1. PROJECT with fields fld_id (integer), fld_allocated_hours (integer), fld_project_id (integer)
  2. TIMESHEET with fields fld_id (integer), fld_allocated_time (integer), fld_project_id (integer)

And I have this procedure:

CREATE PROCEDURE sp_insert_allocated_time(p_project_id integer, p_allocated_time integer)
  RETURNS void 
  AS
BEGIN   
INSERT INTO dbo.Timesheet(fld_id, fld_project_id,fld_allocated_time)
from
(
  SELECT p.fld_id, p.fld_allocated_hours t.fld_allocated_time
  FROM dbo.Project p
  INNER JOIN dbo.Timesheet t
  ON p.fld_id=t.fld_id
  where t.fld_project_id = p_project_id
)AS Alias
GROUP BY fld_id, fld_allocated_days, fld_allocated_time
having SUM(fld_allocated_time) < fld_allocated_hours;
END;

I want to make this procedure:

  1. Insert the allocated_time in table Timesheet from parameter fld_project_id
  2. Check if the column SUM(fld_allocated_time) from table Timesheet is smaller or equals with fld_allocated_hours from table Project.
  3. Make the insertion or error message or exit

you can use IF...ELSE block to check the condition and do appropriate action based on the result of condition. for that you need to store the result of SUM(fld_allocated_time) and fld_allocated_hours into variables and then:

IF @sumResult <= @allocatedTime 
BEGIN
--do some stuff
END
ELSE
BEGIN
--do some other stuff
END

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