set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[STPCreateGood]

    @Title  nvarchar(1000)='',
    @Code   nvarchar(1000)='' ,
    @BarCode   nvarchar(1000)='' ,
    @Type  int,
    @FstUnit   nvarchar(1000)='',
    @SecUnit   nvarchar(1000)='',
    @UnitRate  real,
    @OrderPoint  real,
    @SalePrice1  money,
    @SalePrice2  money,
    @SalePrice3  money,
    @SalePrice4  money,
    @SalePrice5  money,
    @VisitorPer  real,
    @Comment  nvarchar(1000)='',
    @DiscountPer  real,
    @UserPrice  money,
    @GroupId1  Integer,
    @Groupid2  Integer,
    @SerialNo  bit,
	@weight real,
	 @term nvarchar(1000)=''
AS

declare 		@Identity int ,@duplicate bit;

if @groupid1=0 set @groupid1=null
if @groupid2=0 set @groupid2=null
if @UnitRate=0  set @UnitRate=1
begin try
	begin TRANSACTION   

	INSERT INTO StockTbl
		(Title, Type, FstUnit, SecUnit, UnitRate, OrderPoint, SalePrice1, SalePrice2, SalePrice3, SalePrice4, SalePrice5, VisitorPer, 
		Comment, DiscontPer, UserPrice, GroupID1, GroupID2, SerialNo, Weight, Term)
		VALUES     (@Title,@Type,@FstUnit,@SecUnit,@UnitRate,@OrderPoint,@SalePrice1,@SalePrice2,@SalePrice3,@SalePrice4,@SalePrice5,@VisitorPer,@Comment,@DiscountPer,@UserPrice,@GroupID1,@GroupID2,@SerialNo,@weight,@term)
	set @Identity=@@IDENTITY

	if @Code='' set @code=@Identity
	if @BarCode='' set @Barcode=@Identity

	if exists(select goodsyscode from stocktbl where code=@code or Barcode=@Barcode)
			raiserror (50401,16,1)   -- Duplicate code
	else
		begin
			UPDATE    StockTbl
			SET              Code =@code, BarCode =@Barcode
			WHERE     (GoodSyscode = @Identity)
			commit  
			return @Identity
		end
end try
begin catch
	rollback  

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT,@Err int;

set @err=error_number()
if @err>50000 
	begin
		raiserror (@err,16,1)
	end
else
	begin
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY();

		RAISERROR (@ErrorMessage, -- Message text.
				   @ErrorSeverity, -- Severity.
				   1 -- State.
				   );
	end
return -1
end catch