SQL Server: list of views referencing other views - sql-server

SQL Server: I would like to produce a list of views that reference other views.
The reason for this so that views can be created int the proper sequence, not having to resort to obscure view names to accomplish this.
Oracle provides this solution:
select * from USER_DEPENDENCIES
where type = 'VIEW'
and referenced_type = 'VIEW'
Which produces the desired result.
I have not found anything similar in SQL Server; I have been referencing INFORMATION_SCHEMA and its various components without success.

Here's a DMV query to get you started.
use tempdb
drop table if exists t
go
create table t(id int, a int, b int)
go
create or alter view v1 as select id, a from t
go
create or alter view v2 as select * from v1
go
select schema_name(v.schema_id) view_schema_name, v.name view_name, d.referenced_entity_name
from
sys.views v
join sys.sql_expression_dependencies d
on v.object_id = d.referencing_id
which outputs
view_schema_name view_name referenced_entity_name
--------------------- -------------- ---------------------------
dbo v1 t
dbo v2 v1

Take a look at sp_depends.
sp_depends 'YourViewNameHere'
You will get 2 recordsets. The first shows the objects that the view depends on, and the second shows the objects that depend on the view.

Related

Is there a way to identify if a column is not been used in a SQL Server Database?

I have a big database and a lot tables and I would like to identify what columns are not been called by any store procedure or any query, or not in use.
I'm not sure if this is what you're looking for, but in your DB under views there's a folder for System Views - three of which are the following. Looking in all_objects look for the table name, then use the object_id of that table to select from the other queries. There may be other meta-data here that is appropriate for your need.
SELECT *
FROM sys.all_objects
SELECT *
FROM sys.all_columns
WHERE object_id = 981578535
SELECT *
FROM sys.all_views
WHERE object_id = 981578535
After an investigation I have found a new feature of SQL Server called Query Store where you can find in disk the executions with other information. If you have a SQL Server 2016 instance you can find it in the properties of the data base. There you can change the amount of days to capture and then you can in theory try to find the columns in question. The idea of this technology is to give you more options for performance tuning.
You can find the information with this query :
SELECT TOP 10 qt.query_sql_text, q.query_id,
qt.query_text_id, p.plan_id, rs.last_execution_time
FROM sys.query_store_query_text AS qt
JOIN sys.query_store_query AS q
ON qt.query_text_id = q.query_text_id
JOIN sys.query_store_plan AS p
ON q.query_id = p.query_id
JOIN sys.query_store_runtime_stats AS rs
ON p.plan_id = rs.plan_id
where qt.query_sql_text LIKE '%ColumnToFind%'
ORDER BY rs.last_execution_time;
Credits: Query Store

T-SQL table creation in source

I'm starting a new SQL Server Azure DB from scratch. I want to establish a strong source control so I want to be careful in how I create all my tables.
What is the best method to check if the table exists and only execute my CREATE TABLE statement if it does not exist yet? I'm working with passing dynamic SQL to a stored procedure that checks for the tables existence, but that is so limiting. There has to be a preferred way to do this out there. I mean I could preface every query with:
IF NOT EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].j[myTable]') AND type in(N'U'))
BEGIN
CREATE TABLE myTable(....)
END
But that's pretty repetitive.
More simply:
IF NOT EXISTS (SELECT * FROM sys.tables WHERE Name = N'myTable')
CREATE TABLE myTable .......
Idea: use the more focused sys.tables catalog view, instead of the all-encompassing sys.objects - then you don't have to remember those rather unintuitive type values..... - but yes, that is the safest way to do this kind of code.
As of SQL Server 2016, you can also use the
DROP TABLE IF EXISTS myTable;
CREATE TABLE myTable .......
command (which is new - see here: https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/)

Use TSql to find the original table that a column within a view came from

If I create a view such as:
create view View1 as
select Table1.Column1 from Table1
Is there a way to find Table1 given only the name View1. It's easy enough to find the columns within View1 by querying sys.columns where the object_id is equal to the object_id of the view name from sys.objects but how can you tell what is the underlying table that the column within the view came from?
Execute sp_describe_first_result_set with #browse_information_mode = 1. This will return a result set with the underlying table name and column name of each view column along with other meta-data. Source information will be NULL for view columns derived from expressions but other meta-data (e.g. data type information) will be included.
EXEC sp_describe_first_result_set
#tsql=N'SELECT * FROM dbo.YourView;'
, #params = NULL
, #browse_information_mode = 1;
Note that sp_describe_first_result_set was introduced in SQL Server 2012 so this will not work in prior versions of SQL Server.

How do I create and use a stored procedure for SQL-Sever which will delete the data in all tables in a database with VS 2010?

I've been using the entities framework with ASP.NET MVC and I'm looking for an easy and fast way to drop all of the information in the database. It takes quite a while to delete all of the information from the entities object and then save the changes to the database (probably because there are a lot of many-to-many relationships) and I think it should be really fast to just remove all of the information with a stored procedure but I'm not sure how to go about this. How do I create and use a stored procedure for SQL-Sever which will delete the data in all tables in a database with VS 2010? Also if I do this will the command be compatible with other version of SQL-Server? (I'm using 2008 on my testing comptuer, but when I upload it I not sure if my hosting company uses 2008 or 2005).
Thanks!!
This solution will work well in terms of deleting all your data in your database's tables.
You can create this stored proc right within Visual Studio on your SQL Server 2008 development server. It'll work well in any version of SQL Server (2000+).
CREATE PROC NukeMyDatabase
AS
--order is important here. delete data in FK'd tables first.
DELETE Foo
DELETE Bar
TRUNCATE TABLE Baz
I prefer TRUNCATE TABLE, as it's faster. It'll depend on your data model, as you can't issue a TRUNCATE TABLE on a table referenced by a foreign key constraint (i.e. parent tables).
You could then call this stored proc using Entity Framework after adding it to your .edmx:
myContext.NukeMyDatabase();
I recently faced a similar problem in that I had to clear over 200+ tables that were interlinked through many foreign key constraints.
The critical issue, as p.campbell pointed out, is determining the correct order of DELETE statements.
The foreign key constraints between tables essentially represent a hierarchy. If table 3 is dependent on table 2, and table 2 is dependent on table 1, then table 1 is the root and table 3 is the leaf.
In other words, if your going to delete from these three tables, you have to start with the table that has no dependencies and work your way up. That is the intent of this code:
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
;WITH c AS
(
SELECT
parent_object_id AS org_child,
parent_object_id,
referenced_object_id,
1 AS Depth
FROM sys.foreign_keys
UNION ALL
SELECT
c.org_child,
k.parent_object_id,
k.referenced_object_id,
Depth + 1
FROM c
INNER JOIN sys.foreign_keys k
ON c.referenced_object_id = k.parent_object_id
WHERE c.parent_object_id != k.referenced_object_id
),
c2 AS (
SELECT
OBJECT_NAME(org_child) AS ObjectName,
MAX(Depth) AS Depth
FROM c
GROUP BY org_child
UNION ALL
SELECT
OBJECT_NAME(object_id),
0 AS Depth
FROM sys.objects o
LEFT OUTER JOIN c
ON o.object_id = c.org_child
WHERE c.org_child IS NULL
AND o.type = 'U'
)
SELECT #sql = #sql + 'DELETE FROM ' + CAST(ObjectName AS VARCHAR(100))
+ ';' + CHAR(13) + CHAR(10) /** for readability in PRINT statement */
FROM c2
ORDER BY Depth DESC
PRINT #sql
/** EXEC (#sql) **/
exec sp_MSForEachTable 'truncate table ?';
But I would recommend a different approach: take a backup of the empty database and simply restore this backup before each run. Even better, have no database at all and have your application be capable of deploying the database itself, using a schema version upgrade set of scripts.

sql server: looking for table usage through out database

How would I figure out what type of sql code such as procs, functions, views etc. are interacting with my table called TABLE1 through out a given database. Sample code would be very helpful for me.
thanks
select so.name, so.xtype
from sysobjects so (nolock)
inner join syscomments sc (nolock) on sc.id = so.id
where sc.text like '%tablename%'
This code will search all SQL Server objects for a reference to your table. You have to run this query for each database.
If a stored procedure uses your table it will appear in this query. The same is true of functions, views, and triggers.
xtype tells you the type of object.
Here are the possible xtype values:
D = Field names
F = Foreign Key
FN = Function
P = Stored Procedures
PK = Primary Key
S = System Tables
U = User tables
V = Hidden tables
Not enough info in your question, but one thing you can do is use SQL Profiler to profile where INSERTs, UPDATEs, and DELETEs are coming from.
I assume you are talking about how an app is interacting with data and what name (of say a sproc) is doing the insert / update / delete.
Look at SQL Profiler, it comes with your client tools install. Filter it to only show connections to your database (either db name or ID).
If you've been good and created your SPs/views/functions after your table was created, sp_depends will tell you evertyhing referencing the table. Exept for dynamic sql that is.

Resources