过程比较来自不同表的两列并进行插入

时间:2014-11-05 22:26:32

标签: sql sql-server sql-server-2008 tsql stored-procedures

我有两张桌子:

  1. 项目字段为fld_id(整数),fld_allocated_hours(整数),fld_project_id(整数)
  2. TIMESHEET,字段为fld_id(整数),fld_allocated_time(整数),fld_project_id(整数)
  3. 我有这个程序:

    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;
    

    我想制作这个程序:

    1. 从参数fld_project_id
    2. 中的表Timesheet中插入allocated_time
    3. 检查表Timesheet中的SUM(fld_allocated_time)列是否小于或等于表Project中的fld_allocated_hours。
    4. 发出插入或错误消息或退出

1 个答案:

答案 0 :(得分:1)

您可以使用IF ... ELSE块来检查条件并根据条件的结果执行适当的操作。为此,您需要将SUM(fld_allocated_time)和fld_allocated_hours的结果存储到变量中,然后:

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