IF (EXISTS(Select * from sys.sysprocedure where LCase(proc_name) = LCase('FillSaleOrderLines_RegService')))
THEN Drop procedure FillSaleOrderLines_RegService
END IF

GO

create procedure DBA.FillSaleOrderLines_RegService( in @GuestNum integer,in @CreditNo integer ) 
begin
  declare @SaleOrderID integer;
  declare @ServiceNo integer;
  declare @SumCredit numeric(12,4);
  declare @Qty numeric(12,4);
  declare @ServiceName varchar(40);
  declare @NameToInsert varchar(100);
  declare @TipDDS integer;
  declare @DDSType integer;
  declare @SaleLineID integer;
  set @SaleOrderID = (select first ID from SaleOrders where GuestNum = @GuestNum and DocType = 0);
  select SC.Service,SC.SumCredit,SC.NumberServices,S.ServiceName,S.TipSdelka,VS.TipDDS into @ServiceNo,@SumCredit,@Qty,@ServiceName,@TipDDS,@DDSType
    from ServiceCredits as SC join Services as S on S.ServiceNo = SC.Service
      join VidSdelki as VS on S.TipSdelka = VS.N
    where SC.GuestNo = @GuestNum and SC.CreditNo = @CreditNo;
  set @NameToInsert = isNull((select Stoinost from SvoServiceCreditsStn where Glava = @CreditNo and Svoistvo = 1),'');
  if @NameToInsert = '' then
    set @NameToInsert = @ServiceName
  end if;
  set @SaleLineID = GetCounter('SaleOrderLineID');
  insert into SaleOrderLines( Id,DocId,ItemId,Qty,SellPrice,Discount,VatRate,RowSum,ItemName,SaleLineGuid,RegQty ) 
    values( @SaleLineID,@SaleOrderID,@ServiceNo,@Qty,@SumCredit*(1+(if @DDSType = 2 then abs(bvrDDSPart) else 0 endif)),0,
    (if @TipDDS = 1 then abs(bvrDDSPart) else 0 endif),@Qty*@SumCredit*(1+(if @DDSType = 2 then abs(bvrDDSPart) else 0 endif)),@NameToInsert,convert(varchar(50),NEWID()),@Qty ) ;
  insert into SaleOrderLines_Links( SaleLineID,Book_RegNum,ServiceCreditNo ) 
    values( @SaleLineID,0,@CreditNo ) 
end