alter PROCEDURE [dbo].[s4rKlient] @KlientExid INT
AS
BEGIN
	SET NOCOUNT ON;
	declare @CustomerGuid uniqueidentifier;
	declare @CustomerShortName nvarchar(40);
	declare @CustomerLongName nvarchar(200);
	declare @CustomerType int;
	declare @Active int = 1;
	declare @TaxNumber nvarchar(20);
	declare @PostalCode nvarchar(20);
	declare @City nvarchar(80);
	declare @Street nvarchar(80);
	declare @House nvarchar(10);

	declare @Dostawcy int;

	Select
		@CustomerShortName = Knt_Nazwa1,
		@CustomerLongName = Knt_Nazwa1 + Knt_Nazwa2,		
		@TaxNumber = [Knt_NipKraj],
		@PostalCode = Knt_KodPocztowy,
		@City = knt_miasto,
		@Street = Knt_Ulica,
		@House = Knt_NrDomu
	FROM CDN.Kontrahenci 	
	WHERE Knt_KntId = @KlientExid;

	select @Dostawcy = count(*) from cdn.KntOdbiorcy where Odb_OdbKntID = @KlientExid;
	if @Dostawcy >0
		set @CustomerType = 3;
	else
		set @CustomerType = 1;

	select @CustomerGuid=CUS_GUID from sales4rent_vip_prod.dbo.CUSTOMER   
		inner join sales4rent_vip_prod.dbo.CUSTOMER_ORGANIZATION on CUO_GUID_CUS = CUS_GUID
		where CUO_ID_ORG = 1 and CUO_EXID_CUS = @KlientExid;

	if @CustomerGuid is null
	begin
		SET @CustomerGuid  = newid()
		-- insert customer
		insert sales4rent_vip_prod.dbo.CUSTOMER
		( 
			CUS_GUID,
			CUS_TYPE,
			CUS_SHORT_NAME,
			CUS_LONG_NAME,
			CUS_ACTIVE,
			CUS_TAX_NUMBER,
			CUS_ADD_DATE
		)
		values 
		(
			@CustomerGuid,
			@CustomerType,
			@CustomerShortName,
			@CustomerLongName,
			@Active,
			@TaxNumber,
			Getdate()
		)

		-- insert address
		insert sales4rent_vip_prod.dbo.ADDRESS
		(
			ADR_GUID_CUS,
			ADR_ID_TYPE,
			ADR_COUNTRY,
			ADR_CITY,
			ADR_POSTALCODE,
			ADR_STREET,
			ADR_HOUSENUMBER,
			ADR_ACTIVE
		)
		values
		(
			@CustomerGuid,
			1,
			'Polska',
			@City,
			@PostalCode,
			@Street,
			@House,
			1
		)

		insert sales4rent_vip_prod.dbo.CUSTOMER_ORGANIZATION
		(
			CUO_ID_ORG,
			CUO_GUID_CUS,
			CUO_EXID_CUS
		)
		values
		(
			1,
			@CustomerGuid,
			@KlientExid
		)
	end
	else begin
		-- update
		update sales4rent_vip_prod.dbo.CUSTOMER
		set 			
			CUS_TYPE = @CustomerType,
			CUS_SHORT_NAME = @CustomerShortName,
			CUS_LONG_NAME = @CustomerLongName,
			CUS_ACTIVE = @Active,
			CUS_TAX_NUMBER = @TaxNumber
		where CUS_GUID = @CustomerGuid;

		update sales4rent_vip_prod.dbo.ADDRESS
		set 			
			ADR_CITY = @CustomerType,
			ADR_POSTALCODE = @CustomerShortName,
			ADR_STREET = @CustomerLongName,
			ADR_HOUSENUMBER = @Active			
		where ADR_GUID_CUS = @CustomerGuid;
	end;
END;