DECLARE @Len VARCHAR(2)
DECLARE @NameType VARCHAR(10)
DECLARE @sqlCommand VARCHAR(100)

DELETE FROM dbo.Tmp_Over_Under_Row WHERE NOT EXISTS(SELECT * FROM dbo.TmpHavaleh WHERE Autoid = dbo.Tmp_Over_Under_Row.AutoId)

SELECT @NameType= t.name
, @len = 
    c.precision
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 @NameType = 'Numeric' 
EXEC('ALTER TABLE dbo.Tmp_Over_Under_Row ALTER COLUMN Autoid ' + @NameType + '(' + @Len + ',0) Null')
ELSE
EXEC('ALTER TABLE dbo.Tmp_Over_Under_Row ALTER COLUMN Autoid ' + @NameType )

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


