CREATE OR ALTER PROCEDURE [HM].[hm_AttributeWorkflow]

@srcID	  INT,
@dstID    INT,
@basID    INT,
@position SMALLINT

AS
BEGIN

DECLARE @table VARCHAR(MAX)

SELECT @table = CASE WHEN @position = 0 THEN CASE @basID WHEN 16 THEN 'HMF_SalesInvoiceClassification'
														 WHEN 33 THEN 'HMF_WarehouseDocumentClassification'
														 WHEN 34 THEN 'HMF_PurchasingInvoiceClassification'
														 WHEN 45 THEN 'HMF_SalesOrderClassification'
														 WHEN 46 THEN 'HMF_PurchasingOrderClassification'
														 ELSE         ''
											 END
					 ELSE					 CASE @basID WHEN 16 THEN 'HMF_SalesInvoicePositionClassification'
														 WHEN 33 THEN 'HMF_WarehouseDocumentPositionClassification'
														 WHEN 34 THEN 'HMF_PurchasingInvoicePositionClassification'
														 WHEN 45 THEN 'HMF_SalesOrderPositionClassification'
														 WHEN 46 THEN 'HMF_PurchasingOrderPositionClassification'
														 ELSE         ''
											 END
				END

IF @table = '' RETURN 1

DECLARE @posTable VARCHAR(MAX)

SELECT @posTable = CASE @basID WHEN 16 THEN 'DP'
							   WHEN 33 THEN 'MZ'
							   WHEN 34 THEN 'DP'
							   WHEN 45 THEN 'ZP'
							   WHEN 46 THEN 'ZP'
							   ELSE         ''
				   END

DECLARE @fields VARCHAR(MAX)

   SELECT @fields = COALESCE(@fields + ', ', '') + sc.name
     FROM syscolumns AS sc JOIN sysobjects AS so ON sc.id = so.id 
    WHERE so.name = @table AND sc.name LIKE 'CDim_%'
 ORDER BY sc.colorder

DECLARE @request VARCHAR(MAX)

SELECT @request =            ' INSERT INTO SSCommon.' + @table + ' ( Guid, ElementId, st_last_modified, st_shadowdata, ' + @fields + ' ) '

IF @position = 0
BEGIN
	SELECT @request = @request + ' SELECT NEWID(), ' + CONVERT(VARCHAR(20), @dstID) + ' , GETDATE(), NULL, ' + @fields
	SELECT @request = @request + '   FROM SSCommon.' + @table
	SELECT @request = @request + '  WHERE ElementId = ' + CONVERT(VARCHAR(20), @srcID)
END
ELSE
BEGIN
	SELECT @request = @request + ' SELECT NEWID(), pDST.id, GETDATE(), NULL, ' + @fields
	SELECT @request = @request + '   FROM SSCommon.' + @table + ' AS c '
	SELECT @request = @request + '   JOIN HM.' + @posTable + ' AS pSRC ON c.ElementId = pSRC.id '
	SELECT @request = @request + '   JOIN HM.' + @posTable + ' AS pDST ON pSRC.lp = pDST.lp '
	SELECT @request = @request + '  WHERE pSRC.super = ' + CONVERT(VARCHAR(20), @srcID) + ' AND pDST.super = ' + CONVERT(VARCHAR(20), @dstID)
END

EXECUTE (@request)

RETURN 0

END