DECLARE @Len TINYINT
SELECT @len =
    c.max_length 
FROM    
    sys.columns c
INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN 
    sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN 
    sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
    c.object_id = OBJECT_ID('TmpHavaleh') AND c.name = 'AutoId'
IF @len = 9 
ALTER TABLE dbo.Tmp_Over_Under_Row ALTER COLUMN AutoId NUMERIC(19,0)
ELSE IF @len = 8 
ALTER TABLE dbo.Tmp_Over_Under_Row ALTER COLUMN AutoId BIGINT

DELETE FROM dbo.Tmp_Over_Under_Row WHERE AutoId NOT IN(SELECT Autoid FROM TmpHavaleh)
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Tmp_Over_Under_Row_TmpHavaleh]') AND parent_object_id = OBJECT_ID(N'[dbo].[Tmp_Over_Under_Row]'))
ALTER TABLE [dbo].[Tmp_Over_Under_Row]  WITH CHECK ADD  CONSTRAINT [FK_Tmp_Over_Under_Row_TmpHavaleh] FOREIGN KEY([AutoId])
REFERENCES [dbo].[TmpHavaleh] ([AutoId])
ON DELETE CASCADE


SELECT @len =
    c.max_length 
FROM    
    sys.columns c
INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN 
    sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN 
    sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
    c.object_id = OBJECT_ID('Havaleh') AND c.name = 'AutoId'
IF @len = 9 
ALTER TABLE dbo.Over_Under_Row ALTER COLUMN AutoId NUMERIC(19,0)
ELSE IF @len = 8 
ALTER TABLE dbo.Over_Under_Row ALTER COLUMN AutoId BIGINT

DELETE FROM dbo.Over_Under_Row WHERE AutoId NOT IN(SELECT Autoid FROM Havaleh)
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Over_Under_Row_Havaleh]') AND parent_object_id = OBJECT_ID(N'[dbo].[Over_Under_Row]'))
ALTER TABLE [dbo].[Over_Under_Row]  WITH CHECK ADD  CONSTRAINT [FK_Over_Under_Row_Havaleh] FOREIGN KEY([AutoId])
REFERENCES [dbo].[Havaleh] ([AutoId])
ON DELETE CASCADE
