在db中的所有表中将值从一列复制到另一列

时间:2015-02-04 11:21:19

标签: sql sql-server

在我的db中,在大多数表中有两列“IsActive”和“IsDeleted”,两者都是BIT类型。 我需要做的是,从表中删除“IsDeleted”列,但在删除之前复制IsDeleted To IsActive列的反向值。

以下是不同的情况:

1.如果存在“IsActive”和“IsDeleted”,只需将“IsDeleted”的反向值复制到“IsActive”,然后删除“IsDeleted”列。

2.如果IsDeleted存在但不存在IsActive,只需将“IsDeleted”列重命名为“IsActive”,然后反转所有值。

IF COL_LENGTH('table_name','IsDeleted') IS NOT NULL
 BEGIN
 IF COL_LENGTH('table_name','IsActive') IS NOT NULL
  BEGIN
   UPDATE table_name
   SET  IsActive = ~IsDeleted
  END
 ELSE
  BEGIN
   EXEC sp_RENAME 'table_name.IsDeleted', 'IsActive', 'COLUMN'
   UPDATE table_name
   SET  IsActive = ~IsActive
 END
 ALTER TABLE table_name
 DROP CONSTRAINT DF_table_name_IsDeleted
 ALTER TABLE table_name DROP COLUMN IsDeleted
END

现在我想对db中的所有表做同样的事情。 怎么做?我不想为每个表手动编写查询。 在通用查询中,不知道表名和约束名。

修改 到目前为止我已经尝试过了

EXEC sp_MSforeachtable '
IF COL_LENGTH(''?'',''IsDeleted'') IS NOT NULL
    BEGIN
        IF COL_LENGTH(''?'',''IsActive'') IS NOT NULL
        BEGIN
            UPDATE ?
            SET  IsActive = ~IsDeleted
        END
        ELSE
        BEGIN
            EXEC sp_RENAME ''?.IsDeleted'', ''IsActive'', ''COLUMN''
            UPDATE ?
            SET  IsActive = ~IsActive
        END 
        DECLARE @ConstraintName nvarchar(200)
        SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
        WHERE PARENT_OBJECT_ID = OBJECT_ID(''?'')
        AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N''IsDeleted''
                        AND object_id = OBJECT_ID(N''?''))
        IF @ConstraintName IS NOT NULL
        BEGIN
            ALTER TABLE ?
            DROP CONSTRAINT @ConstraintName
        END
    ALTER TABLE ? 
    DROP COLUMN IsDeleted
    END'

但它给了我错误:

here我得到了如何在名称未知时删除约束     '@ConstraintName'附近的语法不正确

0 个答案:

没有答案