IF OBJECT_ID('PClearBill') IS NOT NULL BEGIN DROP PROC PClearBill END GO CREATE PROC PClearBill ( @CompId VARCHAR(100), @BillName VARCHAR(200) ) AS BEGIN DECLARE @sql VARCHAR(MAX) DECLARE @DelSql VARCHAR(MAX) DECLARE @TableName VARCHAR(MAX) DECLARE @MatchName VARCHAR(MAX) SELECT @TableName = @BillName + 'Bill' SELECT @MatchName = @BillName DECLARE @Count INT SELECT @Count = 0 WHILE @Count < 3 BEGIN SELECT @DelSql = '' SELECT @sql = 'SELECT FBillId INTO #Bill FROM '+@TableName+' WHERE FCompId = ' + @CompId SELECT @DelSql = @DelSql + ' DELETE ' + name + ' WHERE FBillId IN(SELECT FBillId FROM #Bill )'FROM sysobjects WHERE name LIKE @MatchName + '%' SELECT @sql = @sql + @DelSql PRINT @SQL EXEC (@SQL) SELECT @Count = @Count + 1 END END GO IF OBJECT_ID('PClearCompanyBill') IS NOT NULL BEGIN DROP PROC PClearCompanyBill END GO CREATE PROC PClearCompanyBill ( @CompId VARCHAR(100) ) AS BEGIN EXEC PClearBill @CompId,'TConsume' EXEC PClearBill @CompId,'TMemberSale' EXEC PClearBill @CompId,'TExpenses' EXEC PClearBill @CompId,'TOtherIncome' EXEC PClearBill @CompId,'TStockIn' EXEC PClearBill @CompId,'TStockOut' EXEC PClearBill @CompId,'TTakeStock' END GO SELECT ' EXEC PClearCompanyBill ' + CAST(FId AS VARCHAR) FROM TCompany WHERE FId != 0