Sql Server存储过程根据某些条件返回结果

时间:2013-06-27 11:35:04

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

我这里有两张桌子 SQL FIDDLE ;

A =tb_status 
B=tb_overhead 


CREATE TABLE tb_status(
    id_estat tinyint IDENTITY(1,1) NOT NULL,
    status_name_estat varchar(50) NOT NULL,
    status_code_estat varchar(20) NULL,
)
INSERT tb_status (status_name_estat,status_code_estat) VALUES ('Admin', 'A')
INSERT tb_status (status_name_estat,status_code_estat) VALUES ('Project Manager', 'B')
INSERT tb_status (status_name_estat,status_code_estat) VALUES ('Office Assistance', 'C')
INSERT tb_status (status_name_estat,status_code_estat) VALUES ('Developer', 'D')
INSERT tb_status (status_name_estat,status_code_estat) VALUES ('Accounts', 'Acc')
INSERT tb_status (status_name_estat,status_code_estat) VALUES ('Staff', 'S')


CREATE TABLE tb_overhead(
    estat_id_oh int NOT NULL,
    overhead_oh decimal(18, 0) NOT NULL,
    hrsperday_oh decimal(18, 0) NOT NULL,
    startdate_oh datetime NOT NULL,
    enddate datetime NULL
) 

INSERT tb_overhead (estat_id_oh,overhead_oh,hrsperday_oh,startdate_oh,enddate) VALUES (2, 2,8 ,'2010-05-21 11:57:56.037', NULL)
INSERT tb_overhead (estat_id_oh,overhead_oh,hrsperday_oh,startdate_oh,enddate) VALUES (4, 2, 8,'2010-05-21 11:57:56.037' , NULL)
INSERT tb_overhead (estat_id_oh,overhead_oh,hrsperday_oh,startdate_oh,enddate) VALUES (8, 2 ,8 ,'2012-02-02 00:00:00.000 ', NULL)
INSERT tb_overhead (estat_id_oh,overhead_oh,hrsperday_oh,startdate_oh,enddate) VALUES (9, 2, 8,'2013-02-02 00:00:00.000', NULL)

我创建SP-,其中必须更新表A并在表B中插入新记录,条件是currentDate必须大于last start,然后将enddate设置为减去 - 1天,否则它将不会插入并显示msg请输入有效日期

Alter proc updateStatus_InsertOverHead
(
@eid int,
@sName varchar(250),
@sCode varchar(250),
@overHead decimal,
@hrs decimal,
@currentStartDate datetime,
@result varchar(max) output
)
as begin
update tb_status set status_name_estat=@sName , status_code_estat=@sCode 
where id_estat=@eid; 

declare @lastStartDate datetime; 
select @lastStartDate= startdate_oh from tb_overhead where estat_id_oh=@eid and enddate is null;

IF @lastStartDate <@currentStartDate
    BEGIN
    update tb_overhead set enddate= DATEADD(day,-1,@currentStartDate) where estat_id_oh=@eid and enddate is null;
    insert into tb_overhead values(@eid,@overHead,@hrs,@currentStartDate,null);
    set @result='Record Updated ';
    END
ELSE
  BEGIN
   set @result = 'Invaild Attemp current date must be greater then previous date'
  END   

END 

执行时遇到错误

declare @msg varchar(max),@myDate datetime;
set @myDate = DATEADD(YEAR,-2,getdate());
exec updateStatus_InsertOverHead 4,'Jr Developer','jrD',3,8,@myDate,@msg=@msg output
select @msg as result;

过程或函数'updateStatus_InsertOverHead'需要参数'@result',这是未提供的。

同样在SQLFILLDE中我如何创建SP

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

declare @msg varchar(max),@myDate datetime
set @myDate  = DATEADD(YEAR,-2,getdate())
exec updateStatus_InsertOverHead 4,'Jr Developer','jrD',3,8,@myDate,@result=@msg output
select @msg as result;

SQL Fiddle DEMO