How do you force a rename???
Rename failed for Table 'dbo.x. (Microsoft.SqlServer.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.2531.0+((Katmai_PCU_Main).090329-1045+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Rename+Table&LinkId=20476
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
Object '[dbo].[x]' cannot be renamed because the object participates in enforced dependencies. (Microsoft SQL Server, Error: 15336)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.4035&EvtSrc=MSSQLServer&EvtID=15336&LinkId=20476
Find the "enforced dependencies", then remove or disable them.
By "enforced dependencies", it means Schema binding, so you'll have to look specifically for that.
Here's a query to look for schema binding references to your object:
select o.name as ObjName, r.name as ReferencedObj
from sys.sql_dependencies d
join sys.objects o on o.object_id=d.object_id
join sys.objects r on r.object_id=d.referenced_major_id
where d.class=1
AND r.name = #YourObjectName
As I noted in the comments, there is no way to FORCE-ibly override Schema Binding. When you use Schema Binding, you are explicitly saying "Do not let me or anyone else override this." The only way around Schema Binding is to undo it, and that's intentional.
I had the same issue , my problem was that i has a COMPUTED FIELD using the column i was trying to rename.
by running the query from the selected answer i was able to tell that had enforced dependencies, but i was not able to see exactly what was the problem
Try this:
/*
Example 1: Rename a table dbo.MyTable -> dbo.YourTable
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES #SchemaName=N'dbo', #EntityName=N'MyTable', #Debug=1;
EXEC sp_rename N'dbo.MyTable', N'YourTable', N'OBJECT'
Example 2: Rename a column dbo.MyTable.MyColumn -> dbo.MyTable.YourColumn
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES #SchemaName=N'dbo', #EntityName=N'MyTable', #ColumnName=N'MyColumn' #Debug=1;
EXEC sp_rename N'dbo.MyTable.MyColumn', N'YourColumn', N'COLUMN'
*/
CREATE Procedure dbo.USP_DROP_ENFORCED_DEPENDENCIES
(
#SchemaName sysname = 'dbo',
#EntityName sysname,
#ColumnName sysname = NULL,
#Debug bit = 0
)
AS
BEGIN
SET NOCOUNT ON;
SET ROWCOUNT 0;
DECLARE #ReferencingEntitySchema sysname, #ReferencingEntityName sysname, #ReferencingEntityType nvarchar(8), #SqlScript nvarchar(512);
DECLARE ReferencingEntitiesCursor CURSOR LOCAL FORWARD_ONLY
FOR
SELECT OBJECT_SCHEMA_NAME(dep.referencing_id) AS [schema]
,referencing_entity.name
,CASE referencing_entity.type
WHEN 'V' THEN N'VIEW'
ELSE /*IF, FN, TF*/ N'FUNCTION'
END as [type]
FROM sys.sql_expression_dependencies AS dep
INNER JOIN sys.objects AS referencing_entity
ON dep.referencing_id = referencing_entity.object_id
WHERE dep.referenced_entity_name = #EntityName
AND dep.referenced_schema_name = #SchemaName
AND is_schema_bound_reference = 1
AND ((#ColumnName IS NULL AND dep.referenced_minor_id = 0) OR COL_NAME(dep.referenced_id, dep.referenced_minor_id) = #ColumnName)
OPEN ReferencingEntitiesCursor
FETCH NEXT FROM ReferencingEntitiesCursor
INTO #ReferencingEntitySchema, #ReferencingEntityName, #ReferencingEntityType;
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES #SchemaName=#ReferencingEntitySchema, #EntityName=#ReferencingEntityName, #Debug=#Debug;
--The goal is to produce the following script:
/*
DROP FUNCTION dbo.UFN_SOME_FUNCTION;
OR
DROP VIEW dbo.UFN_SOME_VIEW;
*/
SET #SqlScript = N'DROP ' + #ReferencingEntityType + N' ' + #ReferencingEntitySchema + '.' + #ReferencingEntityName;
IF(#Debug = 1)
RAISERROR (#SqlScript, 0/*severity*/, 0/*state*/) WITH NOWAIT;
EXEC (#SqlScript);
FETCH NEXT FROM ReferencingEntitiesCursor
INTO #ReferencingEntitySchema, #ReferencingEntityName, #ReferencingEntityType;
END
CLOSE ReferencingEntitiesCursor;
DEALLOCATE ReferencingEntitiesCursor;
END
GO
In the SQL Server Object Browser, right-click on the table with the issue and select View Dependencies. Next in the view listed, Right-click (view) and select SCRIPT to CREATE VIEW in New SQL Query Editor window, then remove WITH SCHEMABINDING from the CREATE VIEW t-sql script and run the revised CREATE VIEW t-sql. This unlinks the schema dependency from the table. I was able to recreate the table at this point (DROP, RENAME, etc).
Note:
Schema binding can occur on functions and other objects in your db.
Use of View Dependencies on the object throwing the error is essential
to fix the issue.
BTW:
I originally added schema binding to enable view indexing. Keeping a
good index on the underlying table(s) may mitigate the performance hit
of not having one on the view.
View Dependencies
More on Schema Binding
I had an issue like this. I dropped constraints on this DB object, renamed the DB object then recreated these constraints. This solved my problem.
I used this script to get dependent view with schemabingings:
select distinct o.name, o.type from sys.sql_expression_dependencies dep inner join sys.objects o on dep.referencing_id=o.object_id where referenced_id = OBJECT_ID(<your dependency owner object>) and o.type = 'V'
Related
While updating (Click on OK button, or Script on SSMS Wizard page),
SSMS got Error: Object reference not set to an instance of an object. (SqlMgmt)
Although there is no problem to do that action with system procedure (EXEC sys.sp_updateextendedproperty) and this will be execute successfully, but it seems that SSMS can't generate this action on wizard page (Stored Procedure Properties).
I had reinstall SSMS on my local system, but it didn't worked!
Same Error exists on every local system of our client and developer that connect to this instance! and I believe that this is a problem on instance wide of server, not SSMS on client side.
There is no Problem for update extended properties from other Object (like Tables, Views, function, etc), but just Stored Procedure!
I think maybe there is some dirty records in some System Tables on the msdb Database!!!
I solve it myself!
The Problem was that I had an Extended Property with a NULL value on all my Stored Procedures!!!
So to solve this problem should update all of them and generate the Not NULL value for them.
Below sample code will be update all the values of entire stored procedures that are exists with the NULL values in their extended properties (Just replace the YOUR_EXTENDED_PROPERTY_NAME with your own extended property name that have NULL value and should be update):
DECLARE #Query AS NVARCHAR (MAX);
DECLARE c CURSOR FOR
----------------------------------------------------
SELECT 'begin try EXEC sys.sp_updateextendedproperty #name=''YOUR_EXTENDED_PROPERTY_NAME'', #value='''' , #level0type=''SCHEMA'',#level0name='''
+ schemaName + ''', #level1type=N''PROCEDURE'',#level1name=N''' + spname + ''' End try Begin catch End catch'
FROM (
SELECT Ob.name spname,
EX.name extended_name,
sch.name AS schemaName,
EX.value
FROM sys.extended_properties AS EX
JOIN sys.objects AS Ob ON Ob.object_id = EX.major_id
JOIN sys.schemas AS sch ON sch.schema_id = Ob.schema_id
WHERE Ob.type = 'P'
AND EX.value IS NULL
) t;
----------------------------------------------------
OPEN c;
FETCH NEXT FROM c
INTO #Query;
WHILE ##fetch_status <> -1
BEGIN
EXECUTE sp_executesql #Query;
FETCH NEXT FROM c
INTO #Query;
END;
CLOSE c;
DEALLOCATE c;
Question is that, why Microsoft let to insert the NULL value and then got ERROR Object reference not set to an instance of an object. on them!!!
I have writing a Change script to update the schema in the Production DB. I have to drop a View and recreate them since one of the column in that view is removed now.
I'm planning to use,
DECLARE #sql NVARCHAR(MAX);
SET #sql = '<View Definition>';
EXEC sp_executesql #sql;
If any, What are the pitfalls of using this approach ? What are the alternatives that you would suggest ?
I'm having the whole script under a transaction with a Try catch block. So when there is no error the script will be committed else rolled back.I tried to use CREATE VIEW Command as below, but I get error after introduction TRASACTION and TRY-CATCH BLOCKS.This reason why am going for Dynamic SQL statement - EXEC sp_executesql.
The error is "CREATE VIEW MUST BE THE ONLY STATEMENT IN THE BATCH"
IF EXISTS ( SELECT * FROM sys.views WHERE name = 'VwViewName')
BEGIN
DROP VIEW VwViewName
END
IF NOT EXISTS ( SELECT * FROM sys.views WHERE name = 'VwViewName')
BEGIN
CREATE VIEW VwViewName
<VIEW DEFINITION>
END
Since you are running schema update, you should comply minimal things like
make it repeatable
have it in your versioning system
and test it in your testing environment before running in production.
In order to make it re-runable it's common practice to check if the object exists and drop it, and then to create it again.
Dynamic SQL will not add any functionality that the IF clause has.
For example:
IF EXISTS(SELECT * FROM sys.views WHERE name = 'MyView')
BEGIN
DROP VIEW [MyView]
END
GO
CREATE VIEW MyView AS
SELECT [Columns list ]
FROM [MyTable]
GO
The only case that I know which justifies dynamic SQL is if you want to preserve grant / deny, in such case you can use following syntax.
IF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'MyView')
BEGIN
EXEC sp_executesql N'CREATE VIEW MyView AS SELECT 1 AS Dummy'
END
GO
ALTER VIEW MyView AS
SELECT [Columns list ]
FROM [MyTable]
go
GRANT ....
I wouldn't create a Dynamic SQL to fill the few times that I have to repeat the names in any of the scripts below. IMHO the deployment script should be as plain as possible.
Is there a way to drop all objects in a db, with the objects belonging to two different schemas?
I had been previously working with one schema, so I query all objects using:
Select * From sysobjects Where type=...
then dropped everything I using
Drop Table ...
Now that I have introduced another schema, every time I try to drop it says something about I don't have permission or the object does not exist. BUT, if I prefix the object with the [schema.object] it works. I don't know how to automate this, cause I don't know what objects, or which of the two schemas the object will belong to. Anyone know how to drop all objects inside a db, regardless of which schema it belongs to?
(The user used is owner of both schemas, the objects in the DB were created by said user, as well as the user who is removing the objects - which works if the prefix I used IE. Drop Table Schema1.blah)
Use sys.objects in combination with OBJECT_SCHEMA_NAME to build your DROP TABLE statements, review, then copy/paste to execute:
SELECT 'DROP TABLE ' +
QUOTENAME(OBJECT_SCHEMA_NAME(object_id)) + '.' +
QUOTENAME(name) + ';'
FROM sys.objects
WHERE type_desc = 'USER_TABLE';
Or use sys.tables to avoid need of the type_desc filter:
SELECT 'DROP TABLE ' +
QUOTENAME(OBJECT_SCHEMA_NAME(object_id)) + '.' +
QUOTENAME(name) + ';'
FROM sys.tables;
SQL Fiddle
Neither of the other questions seem to have tried to address the all objects part of the question.
I'm amazed you have to roll your own with this - I expected there to be a drop schema blah cascade. Surely every single person who sets up a dev server will have to do this and having to do some meta-programming before being able to do normal programming is seriously horrible. Anyway... rant over!
I started looking at some of these articles as a way to do it by clearing out a schema: There's an old article about doing this, however the tables mentioned on there are now marked as deprecated. I've also looked at the documentation for the new tables to help understand what is going on here.
There's another answer and a great dynamic sql resource it links to.
After looking at all this stuff for a while it just all seemed a bit too messy.
I think the better option is to go for
ALTER DATABASE 'blah' SET SINGLE_USER WITH ROLLBACK IMMEDIATE
drop database 'blah'
create database 'blah'
instead. The extra incantation at the top is basically to force drop the database as mentioned here
It feels a bit wrong but the amount of complexity involved in writing the drop script is a good reason to avoid it I think.
If there seem to be problems with dropping the database I might revisit some of the links and post another answer
try this with sql2012 or above,
this script may help to delete all objects by selected schema
Note: below script for dbo schema for all objects but you may change in very first line #MySchemaName
DECLARE #MySchemaName VARCHAR(50)='dbo', #sql VARCHAR(MAX)='';
DECLARE #SchemaName VARCHAR(255), #ObjectName VARCHAR(255), #ObjectType VARCHAR(255), #ObjectDesc VARCHAR(255), #Category INT;
DECLARE cur CURSOR FOR
SELECT (s.name)SchemaName, (o.name)ObjectName, (o.type)ObjectType,(o.type_desc)ObjectDesc,(so.category)Category
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
INNER JOIN sysobjects so ON so.name=o.name
WHERE s.name = #MySchemaName
AND so.category=0
AND o.type IN ('P','PC','U','V','FN','IF','TF','FS','FT','PK','TT')
OPEN cur
FETCH NEXT FROM cur INTO #SchemaName,#ObjectName,#ObjectType,#ObjectDesc,#Category
SET #sql='';
WHILE ##FETCH_STATUS = 0 BEGIN
IF #ObjectType IN('FN', 'IF', 'TF', 'FS', 'FT') SET #sql=#sql+'Drop Function '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('V') SET #sql=#sql+'Drop View '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('P') SET #sql=#sql+'Drop Procedure '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('U') SET #sql=#sql+'Drop Table '+#MySchemaName+'.'+#ObjectName+CHAR(13)
--PRINT #ObjectName + ' | ' + #ObjectType
FETCH NEXT FROM cur INTO #SchemaName,#ObjectName,#ObjectType,#ObjectDesc,#Category
END
CLOSE cur;
DEALLOCATE cur;
SET #sql=#sql+CASE WHEN LEN(#sql)>0 THEN 'Drop Schema '+#MySchemaName+CHAR(13) ELSE '' END
PRINT #sql
EXECUTE (#sql)
I do not know wich version of Sql Server are you using, but assuming that is 2008 or later, maybe the following command will be very useful (check that you can drop ALL TABLES in one simple line):
sp_MSforeachtable "USE DATABASE_NAME DROP TABLE ?"
This script will execute DROP TABLE .... for all tables from database DATABASE_NAME. Is very simple and works perfectly. This command can be used for execute other sql instructions, for example:
sp_MSforeachtable "USE DATABASE_NAME SELECT * FROM ?"
I have many triggers for which I'd like to build a list of table using a wildcard, then update the existing triggers on them by adding some column names to the trigger. The column names will be the same in each trigger, but I'm not clear how build the list of tables or how to loop through the list in a single alter trigger statement. I assume I'll have to use a cursor....
There is no magic wand to say "add this code to all the triggers" (or any other object type, for that matter).
For many object types, for batch editing you can quickly generate a script for multiple objects using Object Explorer Details and sorting and/or filtering within that view. For example, if you highlight "Stored Procedures" in Object Explorer, they're all listed in Object Explorer Details, and you can select multiple objects, right-click, and Script Stored Procedure as > CREATE To >
Since triggers are nested under tables, there isn't a handy way to do this (nor are triggers an entity type you can select when you right-click a database and choose Tasks > Generate Scripts). But you can pull the scripts from the metadata quite easily (you'll want Results to Text in Management Studio when running this):
SET NOCOUNT ON;
SELECT OBJECT_DEFINITION([object_id])
+ CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10)
FROM sys.triggers
WHERE type = 'TR';
You can take the output, copy and paste it into the top pane, then once you have added your new code to each trigger, you'll have to do a little more work to do, e.g. search/replace 'CREATE TRIGGER' for 'ALTER TRIGGER'. You could do that as part of the query too, but it relies on the creator(s) having consistent coding conventions. Since some triggers might look like this...
create trigger
... you may have to massage some by hand.
You can also filter the query above if you are only interested in a certain set of tables. For example, to only alter triggers associated with tables that start with Sales you could say:
AND OBJECT_NAME(parent_id) LIKE N'Sales%';
Or only for tables in the Person schema:
AND OBJECT_SCHEMA_NAME(parent_id) = N'Person';
Anyway once you have made all necessary adjustments to the script, you can just run it. A lot easier than expanding every single table and generating a script for those triggers.
In addition to Aarons suggestion, which worked great on a bunch of complex triggers with inconsistent object naming convention, I then attempted to cook something up so I'd remember what I did in 3 months. Enjoy. Create or alter the SP then execute with no params.
CREATE PROCEDURE SP_ALTER_CONTOUR_TRIGS
--sp to bulk edit many triggers at once
--NO ERROR HANDLING!
AS
DECLARE
#sql VARCHAR(500),
#tableName VARCHAR(128),
#triggerName VARCHAR(128),
#tableSchema VARCHAR(128)
DECLARE triggerCursor CURSOR
FOR
SELECT
so_tr.name AS TriggerName,
so_tbl.name AS TableName,
t.TABLE_SCHEMA AS TableSchema
FROM
sysobjects so_tr
INNER JOIN sysobjects so_tbl ON so_tr.parent_obj = so_tbl.id
INNER JOIN INFORMATION_SCHEMA.TABLES t
ON
t.TABLE_NAME = so_tbl.name
WHERE
--here's where you want to build filters to make sure you're
--targeting the trigs you want edited
--BE CAREFUL!
--test the select statement first against sysobjects
--to see that it returns what you expect
so_tr.type = 'TR'
and so_tbl.name like '%contours'
and so_tr.name like'%location_id'
ORDER BY
so_tbl.name ASC,
so_tr.name ASC
OPEN triggerCursor
FETCH NEXT FROM triggerCursor
INTO #triggerName, #tableName, #tableSchema
WHILE ( ##FETCH_STATUS = 0 )
BEGIN
--insert alter statement below
--watch out for cr returns and open and close qoutes!
--seems to act finicky if you don't use schema-bound naming convention
SET #sql = '
ALTER TRIGGER ['+ #tableSchema +'].['
+ #triggerName + '] ON ['+ #tableSchema +'].['
+ #tableName + ']
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT ['+ #tableSchema +'].['+ #tableName + ']
(OBJECTID, Contour, Type, Shape, RuleID, Override)
SELECT
a.OBJECTID, a.Contour, a.Type, a.Shape, a.RuleID, a.Override
FROM
(SELECT
OBJECTID, Contour, Type, Shape, RuleID, Override
FROM inserted)
AS a
END
'
PRINT 'Executing Statement - '+ #sql
EXECUTE ( #sql )
FETCH NEXT FROM triggerCursor
INTO #triggerName, #tableName, #tableSchema
END
CLOSE triggerCursor
DEALLOCATE triggerCursor
How to I get the SCHEMA when doing a select on sysobjects?
I am modifing a stored procedure called SearchObjectsForText which returns only the Name but I would also like to include the SCHEMA.
Right now it is doing something similar to this:
SELECT DISTINCT name
FROM sysobjects
I would like to know what tables need to be joined to return the SCHEME for each 'name'.
If you mean SQL Server 2005 or higher, use sys.objects instead of sysobjects:
SELECT sys.objects.name, sys.schemas.name AS schema_name
FROM sys.objects
INNER JOIN sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id
2005 introduced schemas. up to 2000, users equaled schemas. The same query for SQL Server 2000:
SELECT sysusers.name AS OwnerName, sysobjects.name
FROM sysobjects
INNER JOIN sysusers ON sysobjects.uid = sysusers.uid
On Sql Server 2005 (and above) you can use the sys.objects view:
select
name as ObjectName,
schema_Name(schema_id) as SchemaName
from
sys.objects
In Sql Server 2000 (and below), "schema" had a different conceptual meaning. Note from MSDN:
In earlier releases of SQL Server, databases could contain an entity called a "schema", but that entity was effectively a database user. SQL Server 2005 is the first release of SQL Server in which a schema is both a container and a namespace.
Could you use the Information_Schema view(s) instead?
SELECT DISTINCT table_name, table_schema
FROM INFORMATION_SCHEMA.TABLES
According to the MSDN page (for SQL Server 2008 and above),
Do not use INFORMATION_SCHEMA views to determine the schema of an object. The only reliable way to find the schema of a object is to query the sys.objects catalog view.
However, it seems that they're probably referring to an issue where you have a table name and are trying to find its schema, which wouldn't work if there were multiple tables with the same name (in different schemas). If you're querying for multiple results (not just trying to find the schema for a specific table), then it should be fine.
I would favor using the more focused "sys" views - sys.procedures instead of sys.objects. You'll need to join it with the sys.schemas view to get schema name and such.
select
p.name,
s.name 'Schema',
p.type_desc, p.create_date, p.modify_date
from
sys.procedures p
inner join
sys.schemas s ON p.schema_id = s.schema_id
I would start to get away from using "sysobjects" since Microsoft clearly states in Books Online that "sysobjects" is subject to removal in a future release:
This SQL Server 2000 system table is included as a view for backward compatibility. We recommend that you use the current SQL Server system views instead. To find the equivalent system view or views, see Mapping SQL Server 2000 System Tables to SQL Server 2005 System Views. This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.
Marc
Just to repeat what's already been suggested here, here's what I've used, to get a list of Tables, Stored Procedures, Views and Functions in my database:
SELECT schema_Name(schema_id) as SchemaName,
[name], -- Name of the Table, Stored Procedure or Function
[type] -- 'V' for Views, 'U' for Table, 'P' for Stored Procedure, 'FN' for function
FROM sys.objects
WHERE [type_desc] IN ( 'USER_TABLE', 'SQL_STORED_PROCEDURE', 'VIEW', 'SQL_SCALAR_FUNCTION')
AND [name] NOT LIKE 'sp_%'
AND [name] NOT LIKE 'fn_%'
ORDER BY 3 DESC, -- type first
1 ASC, -- then schema
2 ASC -- then function/table name
...and here's what our good friend Northwind would return...
In SQL 200:
select DISTINCT
name as ObjectName,
USER_NAME(uid) as SchemaName
from
sysobjects
In earlier releases of SQL Server, databases could contain an entity called a "schema", but that entity was effectively a database user.
Have included an option to delete all objects starting with certain prefix and optionally from certain schema.
By the way, I added extra query to get all types which are not stored on sysobjects by default.
I have uploaded entire sample script to GitHub:
DropAll_Dnn_Objects.sql
Part 1: Temporary Stored Procedure:
IF OBJECT_ID('_temp_DropAllDnnObjects') IS NOT NULL
DROP PROCEDURE _temp_DropAllDnnObjects;
GO
CREATE PROCEDURE _temp_DropAllDnnObjects
#object_prefix NVARCHAR(30),
#schema_name sysname = NULL
AS
BEGIN
DECLARE #sname sysname, #name sysname, #type NVARCHAR(30)
DECLARE #object_type NVARCHAR(255), #sql NVARCHAR(2000), #count INT = 0
DECLARE curs CURSOR FOR
SELECT sname, [name], xtype
FROM (
SELECT SCHEMA_NAME(schema_id) as sname, [name], [type] as xtype
FROM sys.objects
WHERE [type] IN ('U', 'P', 'FN', 'IF', 'TF', 'V', 'TR')
AND name LIKE #object_prefix + '%'
AND (#schema_name IS NULL OR schema_id = SCHEMA_ID(#schema_name))
UNION ALL
SELECT SCHEMA_NAME(schema_id) as sname, [name], 'TYPE' as xtype
FROM sys.types
WHERE is_user_defined = 1
AND [name] LIKE #object_prefix + '%'
AND (#schema_name IS NULL OR schema_id = SCHEMA_ID(#schema_name))
) a
ORDER BY CASE xtype
WHEN 'P' THEN 1
WHEN 'FN' THEN 2
WHEN 'IF' THEN 3
WHEN 'TF' THEN 4
WHEN 'TR' THEN 5
WHEN 'V' THEN 6
WHEN 'U' THEN 7
WHEN 'TYPE' THEN 8
ELSE 9
END, name
OPEN curs;
FETCH NEXT FROM curs INTO #sname, #name, #type;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #count = #count + 1
-- Configuration point 2
SET #object_type = CASE #type
WHEN 'P' THEN 'PROCEDURE'
WHEN 'FN' THEN 'FUNCTION'
WHEN 'IF' THEN 'FUNCTION'
WHEN 'TF' THEN 'FUNCTION'
WHEN 'TR' THEN 'TRIGGER'
WHEN 'V' THEN 'VIEW'
WHEN 'U' THEN 'TABLE'
WHEN 'TYPE' THEN 'TYPE'
END
SET #sql = REPLACE(REPLACE(REPLACE('DROP <TYPE> [<SCHEMA>].[<NAME>];',
'<TYPE>', #object_type),
'<SCHEMA>', #sname),
'<NAME>', #name)
BEGIN TRY
PRINT #sql
EXEC(#sql)
END TRY
BEGIN CATCH
PRINT 'ERROR: ' + ERROR_MESSAGE()
END CATCH
FETCH NEXT FROM curs INTO #sname, #name, #type;
END;
PRINT CONCAT('Objects Found: ', #Count)
PRINT ''
PRINT '------------------------------------------------------'
PRINT ''
CLOSE curs;
DEALLOCATE curs;
RETURN #Count
END;
GO
It will continue on errors (and display the error message). It will return a count of all objects found.
Part 2: Call Stored Procedure with parameters:
You can create a WHILE loop in order to run the command until no object is left (dependencies), as follows:
DECLARE #count INT = 1
WHILE #count > 0 EXEC #count = _temp_DropAllDnnObjects 'dnn';
SET #count = 1
WHILE #count > 0 EXEC #count = _temp_DropAllDnnObjects 'aspnet';
SET #count = 1
WHILE #count > 0 EXEC #count = _temp_DropAllDnnObjects 'vw_aspnet';
GO
Part 3: Finally, get rid of the procedure:
IF OBJECT_ID('_temp_DropAllDnnObjects') IS NOT NULL
DROP PROCEDURE _temp_DropAllDnnObjects;
GO
Instead of a view, why not use this to populate a temporary table you can use?
This is the solution I use in stored procedures
This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically
select #sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'
exec (#sql)
of course #tables is a dynamic table in the stored procedure