Am trying to write script for removing Constraints.
I have the below function to select the Constarints in my DataBase
SELECT name FROM sys.foreign_keys
And I have written alter scripts using the above scripts
SELECT 'ALTER TABLE ' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT ' + name FROM sys.foreign_keys
Using the above query how can I execute these constraints ?
I can use DROP DATABASE DBName
. But am just trying to drop tables by dropping Constraints.
is it possible without going for SP ? Or any easy ways I can proceed?
To drop (table) check constraints, use the DROP CHECK clause of the ALTER TABLE statement. When you drop a check constraint, all packages and cached dynamic statements with INSERT or UPDATE dependencies on the table are invalidated. The name of all check constraints on a table can be found in the SYSCAT.
Drop all the constraint in Oracle begin for r in ( select table_name, constraint_name from user_constraints where table_name='&1' ) loop execute immediate 'alter table '|| r. table_name ||' drop constraint '|| r. constraint_name; end loop; end; OR select 'alter table '||owner||'.
DROP TABLE always removes any indexes, rules, triggers, and constraints that exist for the target table.
To drop a foreign key from a table, use the ALTER TABLE clause with the name of the table (in our example, student ) followed by the clause DROP CONSTRAINT with the name of the foreign key constraint. In our example, the name of this constraint is fk_student_city_id .
Well you can always copy the output from the bottom pane, paste it into the top pane, and hit F5. Or you can build a string to execute directly:
DECLARE @sql NVARCHAR(MAX) = N''; SELECT @sql += N' ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)) + ' DROP CONSTRAINT ' + QUOTENAME(name) + ';' FROM sys.foreign_keys; PRINT @sql; -- EXEC sp_executesql @sql;
(When you are happy with the PRINT
output, comment it out and uncomment the EXEC
. Note that the print output will be truncated to 8K in Management Studio but the variable really holds the entire command.)
Also I don't know how this really relates to whether you are using a stored procedure or not, or why you are trying to do it "w/o going for SP"... this query can be run as a stored procedure or not, it all depends on how often you're going to call it, where the procedure lives, etc.
This worked for me in SQL Server 2008:
DECLARE @SQL NVARCHAR(MAX) = N''; SELECT @SQL += N' ALTER TABLE ' + OBJECT_NAME(PARENT_OBJECT_ID) + ' DROP CONSTRAINT ' + OBJECT_NAME(OBJECT_ID) + ';' FROM SYS.OBJECTS WHERE TYPE_DESC LIKE '%CONSTRAINT' AND OBJECT_NAME(PARENT_OBJECT_ID) = 'YOUR_TABLE'; PRINT @SQL --EXECUTE(@SQL)
Of course, uncomment the EXECUTE(@SQL)
when ready to run
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With