Monday, 6 June 2016

Find  all stored procedures or Function in a specific SQL Server schema 


Use the information_schema.routines (which is fairly standard across RDBMSs such as MSSQL,Mysql):
If your proc names start "tSQLt" then they are probably in a schema, so you can find them with:

select
    'PROCEDURE  [' + routine_schema + '].[' + routine_name + ']'
from 
    information_schema.routines where routine_name like 'tSQLt%' and routine_type = 'PROCEDURE'  --OR routine_type = 'FUNCTION' 

If you wanted to execute all these drop statements, you can build a single execute using FOR XML PATH as follows:
declare @sql varchar(max)

set @sql = (
select
    'DROP PROCEDURE [' + routine_schema + '].[' + routine_name + '] ' 
from 
    information_schema.routines where routine_schema = 'tSQLt' and routine_type = 'PROCEDURE'FOR XML PATH ('')
)

exec (@sql)

Could not drop object 'dbo.Table1' because it is referenced by a FOREIGN KEY constraint

1.Firstly, you need to drop your FK.
To get all foreign key relationships referencing your table, you could use this SQL

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TableName')


SELECT 
'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(parent_object_id) +
'.[' + OBJECT_NAME(parent_object_id) + 
'] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TableName')
2.Then drop the constraint.
3.Then Drop Table .

No comments:

Post a Comment