IF object_id('dbo.PChangeCenterCompany','P') IS NOT NULL BEGIN DROP PROCEDURE dbo.PChangeCenterCompany END GO CREATE PROCEDURE PChangeCenterCompany ( @CompNo VARCHAR(50) ) AS BEGIN DECLARE @Sql VARCHAR(8000) DECLARE @NewId VARCHAR(20) DECLARE @OldId VARCHAR(20) DECLARE @TableName VARCHAR(200) DECLARE @ColumnName VARCHAR(200) DECLARE @Cursor bit SET @Cursor = 0 SELECT @OldId = FId FROM TCompany WHERE FNo = @CompNo IF @@ROWCOUNT = 0 BEGIN RAISERROR ('公司编号不存在', 18, 1) RETURN END IF @OldId = '1' BEGIN RAISERROR ('已经是总公司', 18, 1) RETURN END DELETE TBasicDataChanges SELECT @NewId = dbo.FNNewId() BEGIN TRAN ChangeCengerCompany declare #List cursor for SELECT a.name , b.name FROM sysobjects AS a,syscolumns AS b WHERE a.id = b.id AND b.name LIKE '%CompId' AND a.type = 'U' AND a.name != 'TTrialControl' AND a.name != 'TBizLog' open #List fetch #List into @TableName,@ColumnName while @@fetch_status=0 begin SET @Cursor = 1 --把现有的总公司改成子公司 SELECT @Sql = ' UPDATE ' + @TableName + ' SET ' + @ColumnName + ' = ' + @NewId + ' WHERE ' + @ColumnName + '=1' print @Sql EXEC (@Sql) IF @@ERROR > 0 BEGIN GOTO Error END --把子公司转成总公司 SELECT @Sql = ' UPDATE ' + @TableName + ' SET ' + @ColumnName + ' = 1 WHERE ' + @ColumnName + '=' + @OldId print @Sql EXEC (@Sql) IF @@ERROR > 0 BEGIN GOTO Error END fetch #List into @TableName,@ColumnName end close #List deallocate #List SET @Cursor = 0 UPDATE TStockOutBill SET FReceiverId = @NewId WHERE FReceiverId = 1 AND FStockOutType = 5 IF @@ERROR > 0 BEGIN GOTO Error END UPDATE TStockOutBill SET FReceiverId = 1 WHERE FReceiverId = @OldId AND FStockOutType = 5 IF @@ERROR > 0 BEGIN GOTO Error END DELETE TCompanyTree IF @@ERROR > 0 BEGIN GOTO Error END UPDATE TCompany SET FId = @NewId WHERE FId = 1 IF @@ERROR > 0 BEGIN GOTO Error END UPDATE TCompany SET FId = 1 WHERE FId = @OldId IF @@ERROR > 0 BEGIN GOTO Error END EXEC PCreateCompanyTreeNode 1 IF @@ERROR > 0 BEGIN GOTO Error END COMMIT TRAN ChangeCengerCompany RETURN ERROR: ROLLBACK TRAN ChangeCengerCompany IF @Cursor = 1 BEGIN CLOSE #List DEALLOCATE #List END END GO EXEC PChangeCenterCompany '新的总公司编号' SELECT * FROM TCompany SELECT * FROM TUser UPDATE TCompany SET FParentId = 1 WHERE FId != 1