Use ATNDB
go

if (Select COUNT(*) from Warehouse) < 1
Begin
EXEC	[dbo].[Warehouse_Insert]
		@Code = 1,
		@Detail = N'انبار مرکزی',
		@RecorderRef = 1,
		@RecordDate = '1390/01/01',
		@OfficeDetailRef = 1

End

update FactorHeader set WarehouseRef = 1 where WarehouseRef is null

Update FactorHeader
Set TotalPaid = isnull(Tp,0)+Cost1th+Cost2th-Rebate 
FROM FactorHeader Inner join 
	(SELECT FactorHeader.Serial,Sum(TotalPrice) as TP 
	 FROM FactorHeader Left Join FactorDetail ON FactorHeader.Serial = FactorDetail.FactorHeaderRef  
	 Group by FactorHeader.Serial) K 
 ON K.Serial = FactorHeader.Serial 
