In my db in most of the tables there are two columns "IsActive" and "IsDeleted", both are of type BIT. What I need to do is, remove the column "IsDeleted" from the table, but before removing copy the reverse values of IsDeleted To IsActive column.
Following are different scenarios:
1.If both "IsActive" and "IsDeleted" exist simply copy the reverse values of "IsDeleted" to "IsActive" and then delete the column "IsDeleted".
2.If IsDeleted exist but not IsActive, simply rename the column "IsDeleted" to "IsActive" and then reverse all the values.
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
Now I want to do same for all the tables in the db. How to do it? I don't want to write the query manually for each table. In the generic query The table name and the constraint name are not know.
EDIT: I've tried following so far
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'
But its giving me error:
From here I got how to delete constraint when its name is not known Incorrect syntax near '@ConstraintName'