Find procedures referencing non-existing tables - sql

I am wondering if there is a simple way to list all stored procedures that are referencing non-existing tables other than going through them 1 by 1 and looking at the code.

At least few variants:
Using T-SQL:
SELECT
OBJECT_NAME(referencing_id) AS [Procedure/View],
referenced_entity_name AS [Missing object]
FROM
sys.sql_expression_dependencies
WHERE
is_ambiguous = 0
AND OBJECT_ID(referenced_entity_name) IS NULL
Paid tool Redgate SQL Prompt, by using Finding invalid objects. It has one month trial period

I would recommend using a ready-made solution. For example, Find Invalid Objects in SQL Complete perfectly searches all calls to non-existent objects not only within the definition of stored procedures, but also for all database objects (triggers, views, functions, etc.).

The other answer has the entities covered. To query the procs and their activity, use the code below. It shows activity since the last server restart. You can use this to find procs that have not been executed in years.
SELECT *
FROM sys.dm_exec_procedure_stats

Related

What is the best way to find DML references to objects in SQL Server?

Something I have always struggled with is finding DML references to tables in SQL server at the company I work. We have our code held in TFS source control and deployed to a shared development environment so I can search using either file searching or t-sql code. The challenge I have is that I can easily find all references to a table name but I can't find a good way to filter further to a particular statement like UPDATE/INSERT/MERGE.
A large challenge in this is that the company I work at has a lot of dynamic SQL so I think the best method will be some form of text searching. The other challenge is that coding is written as each developer sees fit so an UPDATE statement will not be written in any 'standard' way throughout the code base - i.e. the table name could be on the same line as the DML statement or on a separate line.
I have been able to use some basic regular expression searching in Visual Studio to find instances where the keyword is on the same line as the table name but I don't know how to search for it being 'close'.
Has anybody else faced this issue and found a good way to search for this information? What I would love is a tool where you put in a t-sql reserved keyword and an object name and the tool shows you all references.
One way to at least see all the code across Views, SP, Functions, etc is to run this:
--will show you all source code from procs, views, functions etc
select *
from syscomments
--or better to join it on sysobjects and display only view source code for example
select o.id,o.name,c.text
from syscomments c
inner join sysobjects o on o.id = c.id
where o.[Type] = 'V'
I found once I have all of this, I can then do easy searching in Excel or via Notepad++.
I hope that helped.

Renaming a column without breaking the scripts and stored procedures

I want to modify a column name to new name present in a table
but here problem i want to manually modify the column name present in Triggers or SP's.
Is there a any better way of doing it.
To rename a column am using this
sp_RENAME 'Tablename.old_Column', 'new_column' , 'COLUMN';
similarly how can i do it for triggers or SP's.? without opening each script?
Well, there are a bunch of 3rd party tools that are promising this type of "safe rename", some for free and some are not:
ApexSQL has a free tool for that, as MWillemse wrote in his answer,
RedGate have a commercial tool called SQLPrompt that also have a safe renaming feture, However it is far from being free.
Microsoft have a visual studio add-in called SQL Server Data Tools (or SSDT in the short version), as Dan Guzman wrote in his comment.
I have to say I've never tried any of these specific tools for that specific task, but I do have some experience with SSDT and some of RedGate's products and I consider them to be very good tools. I know nothing about ApexSQL.
Another option is to try and write the sql script yourself, However there are a couple of things to take into consideration before you start:
Can your table be accessed directly from outside the sql server? I mean, is it possible that some software is executing sql statement directly on that table? If so, you might break it when you rename that column, and no sql tool will help in this situation.
Are your sql scripting skills really that good? I consider myself to be fairly experienced with sql server, but I think writing a script like that is beyond my skills. Not that it's impossible for me, but it will probably take too much time and effort for something I can get for free.
Should you decide to write it yourself, there are a few articles that might help you in that task:
First, Microsoft official documentation of sys.sql_expression_dependencies.
Second, an article called Different Ways to Find SQL Server Object Dependencies that is written by a 13 years experience DBA,
and last but not least, a related question on StackExchange's Database Administrator's website.
You could, of course, go with the safe way Gordon Linoff suggested in his comment, or use synonyms like destination-data suggested in his answer, but then you will have to manually modify all of the columns dependencies manually, and from what I understand, that is what you want to avoid.
Renaming the Table column
Deleting the Table column
Alter Table Keys
Best way use Database Projects in Visual Studio.
Refer this links
link 1
link 2
you can do what #GorDon suggested.
Apart from this,you can also play with this query,
select o.name, sc.* from sys.syscomments sc inner join sys.objects o
on sc.id=o.object_id where sc.text like '%oldcolumnname%'
this will return list of all proc and trigger.Also you can modify filter to get exact list.then it will be very easy for you to modify,manually.
But whatever you decide,don't simply drop old column.
To be safe,even keep back up.
This suggestion relates to Oracle DB, however there may be equivalent solutions in other DBMS's.
A temporary solution to your issue is to create a pseudocolumn. This solution looks a little hacky because the syntax for a pseudocolumn requires an expression. The simplest expression I can think of is the case statement below. Let me know if you can make it more simple.
ALTER TABLE <<tablename>> ADD (
<<new_column_name>> AS (
CASE
WHEN 1=1 THEN <<tablename>>.<<old_column_name>>
END)
);
This strategy basically creates a new column on the fly by evaluating the case statement and copying the value of <<old_column_value>> to <<new_column_value>>. Because you are dynamically interpolating this column there is a performance penalty vs just selecting the original column.
The one gotcha is that this will only work if you are duplicating a column once. Multiple pseudocolumns cannot contain duplicate expressions in Oracle.
The other strategy you can consider is to create a view and you can name the columns whatever you want. You can even INSERT/UPDATE/DELETE (execute DML) against views, but this would give you a whole new table_name, not just a new column. You could however rename the old table, and name your view the same as your old table. This also has a performance penalty vs just accessing the underlying table.
You might want to replace that text in definition. However, you will be needing a dedicated administrator connection in sql server. Versions also vary in setting up a dedicated administrator connection. Setting up the startup parameter by adding ;-T7806 under advanced. And by adding Admin: before the servername upon logging in. By then, you may be able to modify the value of the definition.

Stored procedure dependencies in SQL Server Management Studio

I don't know much about the MS world, but now it happens to be that I have to use SQL Server Management Studio 2008.
My problem: I have a column in a table, and I need to see all the stored procedures that may be acting on it.
I tried right-clicking and going 'View Dependencies' but that doesn't seem to be returning everything that it should be.
Questions like this one: SQL Server Dependencies have answers that offer 3 types of solutions
Paid third party tools.
Writing your own scripts.
Exporting everything into text files and grepping them.
WTF? Am I missing something obvious? Is that actually how things work? I would imagine that this is a very common use case: you want to alter table and you want to make sure you won't break anything. Or if say you're looking at a new project with a DB for the first time and you want to see how certain columns get populated with stored procedures. Is there actually no quick and easy built-in workflow to do this?
If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).
It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??
Use this query:
SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%YOUR COLUMN %'
AND ROUTINE_TYPE='PROCEDURE'
I have spent a good amount of time trying to find a way to identify column level dependencies in a quick way without having to search text or use third party applications. The other challenge is finding dependencies across multiple databases where table names may repeat, which will cause false positives when searching SP text.
As of SQL 2008, there is a function that returns dependencies across databases on a field level.
The code below works with a few exceptions:
It will fail if there are stored procedures with invalid references on tables/fields that have been deleted (Incidently I found this to be useful to find SPs that had been accidentally broken by table modifications).
It doesn't find all dependencies in cases where the SP is using temp tables in unusual ways.
In some cases I found that it was returning false positives for complex stored procedures.
MSDN Documentation
This code should be run from within the database where the SP is in order to be able to cross to other database dependencies.
SELECT
--SP, View, or Function
ReferencingName = o.name,
ReferencingType = o.type_desc,
--Referenced Field
ref.referenced_database_name, --will be null if the DB is not explicitly called out
ref.referenced_schema_name, --will be null or blank if the DB is not explicitly called out
ref.referenced_entity_name,
ref.referenced_minor_name
FROM sys.objects AS o
cross apply sys.dm_sql_referenced_entities('dbo.' + o.name, 'Object') ref
where o.type in ('FN','IF','V','P','TF')
I wonder why you cannot see the dependencies via the 'View Dependencies' dialog because it works perfectly fine for me. Nevertheless you can query the 'sys.sql_expression_dependencies' system view and obtain the dependency information that you want.
Example
SELECT OBJECT_NAME(referencing_id),OBJECT_NAME(referenced_id)
FROM sys.sql_expression_dependencies
WHERE referenced_id = OBJECT_ID('XXX')
You can of course project other information that you might need.
List of All Dependent Objects in single query.
select distinct A.name from sys.procedures A inner join sys.sql_dependencies B
on A.object_id = B.object_id;
OR
select distinct A.name from sys.objects A inner join sys.sql_dependencies B
on A.object_id = B.object_id where A.type_desc = 'mentioned your Object Type';

Dynamically generated SQL security concerns (sql injection etc.)

We are in the process of developing an "API" for one of our products. This will allow the user to define which columns they wan't to return from their "queries" and we will build the needed SQL.
I know that you should always use parameterized queries to avoid SQL injection attacks. However is there any security risks when building a statement where the columns returned are defined by the users? Lets say we have the following api request. This is just an example to illustrate what I mean :)
/api/customers/getall?fields=Name,Phone,Email&where=Zip=1000
The SQL will be
SELECT Name, Phone, Email FROM Customers WHERE Zip = #Zip
I'm not thinking about just taking the fields parameter and building the SQL directly around that, it will probably be made into a list and returned with some default columns like Id and Modified.
What should you be aware of in this situation? And how would you protect against attacks?
-- Christian
Create a Stored Procedure
This will let you check the input Stings and you should be on the safe side.
See:
MSDN Create Stored Procedures
First, I do a query to get the fields of the selected table(s) from the INFORMATION_SCHEMA.COLUMNS metadata table.
Querying database metadata
The column names pulled from the database are safe to use. Then I compared the fields in the SELECT clause with the "safe fields list". If one of the selected fields isn't on the clean list, then remove it or don't run the generated SQL at all.

SQL query to get the source of a Stored Procedure

I'm using a DB2 database and I'm hoping for a query which will iterate over all stored procedures in a single database and print out the source code of each. No fancy formatting or performance requirements.
The reason for this (in case there's a better way of doing it) is I'm trying to track down usages of a particular table in our stored procs, so I want to be able to do a simple text search through all of them.
Also, I've got access to SQuirreL SQL client if anyone knows of a way via that.
Ah, figured it out. For other's reference:
select ROUTINENAME, TEXT from syscat.routines
where definer not in ('SYSIBM') AND ROUTINESCHEMA='databaseName'
I know this is old, but your answer started me on the right track. We are also using DB2, but don't have syscat.routines visible to us. However we do have SYSIBM.SYSROUTINES and that allows similar by doing
SELECT SCHEMA,
NAME,
TEXT
FROM SYSIBM.SYSROUTINES
WHERE SCHEMA = '<SCHEMA>'
and NAME = '<NAME>'
FOR FETCH ONLY WITH UR;