IF NOT EXISTS (SELECT * FROM sysobjects WHERE Name='Centro_Costos_Prorra_Items' AND xtype='U')
BEGIN
	CREATE TABLE Centro_Costos_Prorra_Items
	(
	Id_Prorrateo		SMALLINT NOT NULL,
	Id_Centro_Costo		CHAR(10) NOT NULL,
	Porc				DECIMAL(10, 5) NULL,
	Activo				TINYINT NULL,
	Id_Alias_Cta_Cont	SMALLINT NOT NULL
	)

	ALTER TABLE Centro_Costos_Prorra_Items ADD CONSTRAINT PK_CCPI_PorId PRIMARY KEY CLUSTERED (Id_Prorrateo ASC, Id_Centro_Costo ASC, Id_Alias_Cta_Cont ASC)

	CREATE NONCLUSTERED INDEX IX_CCPI_PorCC ON Centro_Costos_Prorra_Items
	(
		Id_Centro_Costo ASC,
		Id_Prorrateo ASC,
		Id_Alias_Cta_Cont ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
END
ELSE
BEGIN
	SELECT 
	Id_Prorrateo,
	Id_Centro_Costo,
	ISNULL(Porc, 0) AS Porc,
	ISNULL(Activo, 0) AS Activo
	INTO zCentro_Costos_Prorra_Items
	FROM Centro_Costos_Prorra_Items

	DROP TABLE Centro_Costos_Prorra_Items

	CREATE TABLE Centro_Costos_Prorra_Items
	(
	Id_Prorrateo		SMALLINT NOT NULL,
	Id_Centro_Costo		CHAR(10) NOT NULL,
	Porc				DECIMAL(10, 5) NULL,
	Activo				TINYINT NULL,
	Id_Alias_Cta_Cont	SMALLINT NOT NULL
	)

	ALTER TABLE Centro_Costos_Prorra_Items ADD CONSTRAINT PK_CCPI_PorId PRIMARY KEY CLUSTERED (Id_Prorrateo ASC, Id_Centro_Costo ASC, Id_Alias_Cta_Cont ASC)

	CREATE NONCLUSTERED INDEX IX_CCPI_PorCC ON Centro_Costos_Prorra_Items
	(
		Id_Centro_Costo ASC,
		Id_Prorrateo ASC,
		Id_Alias_Cta_Cont ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)

	INSERT INTO Centro_Costos_Prorra_Items
	(Id_Prorrateo, Id_Centro_Costo, Porc, Activo,Id_Alias_Cta_Cont)
	SELECT Id_Prorrateo, Id_Centro_Costo, Porc, Activo , 0 FROM zCentro_Costos_Prorra_Items

	DROP TABLE zCentro_Costos_Prorra_Items
END
GO

ALTER TABLE Centro_Costos_Prorra_Items  WITH CHECK ADD CONSTRAINT FK_CCPI_CCPT FOREIGN KEY(Id_Prorrateo)
REFERENCES Centro_Costos_Prorrateos (Id_Prorrateo)
GO

ALTER TABLE Centro_Costos_Prorra_Items CHECK CONSTRAINT FK_CCPI_CCPT
GO

ALTER TABLE Centro_Costos_Prorra_Items  WITH CHECK ADD CONSTRAINT FK_CCPI_CC FOREIGN KEY(Id_Centro_Costo)
REFERENCES Centro_Costos (Id_Centro_Costo)
GO

ALTER TABLE Centro_Costos_Prorra_Items CHECK CONSTRAINT FK_CCPI_CC
GO


