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

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.

Related

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.

Need to identify a table in all objects in database

I need to identify a table that is mentioned anywhere in database (in stored proc, views, and, etc.). I tried to find a query online, but couldn't find it. Any help would be great!
I use the free SQL Search plugin for MS Management Studio for things like that: http://www.red-gate.com/products/sql-development/sql-search/
I often use this snippet when I'm looking for dependencies. In this case, you would replace the text with what you're searching (assuming you're on MS SQL Server):
USE [DBNAME]
SELECT OBJECT_NAME(id)
FROM syscomments
WHERE [text] LIKE '%enter_search_here%'
GROUP BY OBJECT_NAME(id)
You can also look for specific object types by adding a check for object property:
WHERE OBJECTPROPERTY(id, 'IsTable') = 1
Here is a LIST of useful object properties!

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';

Where is the table/view script generated and how to get it?

Say I have written a Create Table script in a query window and run it. So the table got created. Now, where is this script file being generated (system table). I mean if I do a
select * from sys.syscomments
I will get the script for stored procedure or function in the "Text" column. Likewise any way of getting the same for table or view?
Any DMV etc...
Thanks in advance
I'm not sure where the script is stored, but if you're looking to be able to view the scripted language to create the table, in SQL2008 R2 (and I'm pretty sure SQL2008) SSMS can generate the script on the fly. Just select your Table (or View, SP, etc...) and right click. From the context menu, choose Script Table as Create To (or whatever other modification you choose from the list). Then you have a choice of output locations-the New Query Editor Window is probably easiest to see your results. From there you have the base language for that table's creation and you can modify or save it from there.
below query is also works for views
select * from sys.syscomments
For getting script of tables , you have to
Right Click on database >> tasks >> Generate Scripts >> choose objects (select tables)
I think that is the possible way of getting table scripts.
For views you can use the column VIEW_DEFINITION in:
SELECT *
FROM INFORMATION_SCHEMA.VIEWS
I don't think there is an equivalent for tables because tables don't require a stored definition because the table itself is the definition. If you need to copy table structures then the best method is probably to use:
SELECT *
INTO NewTable
FROM OldTable
WHERE 0 = 1
You could try generating your own scripts using the system views and creating dynamic SQL, something like this would get you started
This does not create constraints, and there maybe things I've missed, or cause it to break but the general gist is there. You could also do this outside of SQL as demonstrated quite nicely In this Answer.
HOWEVER I should add I do not condone the use of these methods. There are few scenarios I can think of where it would be necessary to programatically copy a tables structure in this fashion. If it is necessary to copy structures as a one off you'd be better off doing this using the generate script functions that are built into SSMS.

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;