SSMS - get DDL of all views in a schema - sql

I have a SQL Server database with several schemas, each of them contains several views.
I need to create the same views in other databases so I would like to get the DDL of all the views in a script, generated through SQL.
In Oracle it was quite easy, accessing ALL_VIEWS and referencing the QUERY column.
How can i do the same in SQL Server?
Thanks
EDIT
I know I can right click and get the script of an object in SSMS, I need to do this for 20/30 views, and don't want to do it manually
I'm trying to avoid as much as possible to do manual work. I want to have a query which generates the scripts for all objects in one or more schemas.
This is because the schemas are evolving quickly, with new views being created. I need to reproduce them in several other databases and I'm trying to have a solid procedure for deploying

With the Views node highlighted in Object Explorer, open Object Explorer Details (F8 or Shift+F8 if I recall correctly).
This will open a window with all the views in a list, and you highlight the views you want and right-click > script. Here you can sort by name, filter by schema (probably what you mean by "owner"), etc.
I'm not sure how you can possibly select 20 or 30 views in any scenario without introducing the possibility of human error.
You can write a script that does something similar, with Results to Text, e.g.
SET NOCOUNT ON;
SELECT 'GO' + OBJECT_DEFINITION(object_id)
FROM sys.views
WHERE schema_id = SCHEMA_ID(N'schema_name');
The problem is Management Studio has crippling limits to text output, even after customizing Tools > Options > Query Results > SQL Server > Results to Text and setting that to the max (8,192). So if any of your views are longer than 8,192 characters, you'll need to work around that somehow.
But really, Larnu is right. Your views should be in source control, and that should be your source for deployment, not some manual extraction from the database.

If you want to get the view definitions from a query, you can use sql_modules.
select m.definition
from sys.sql_modules m
join sys.objects o on o.object_id = m.object_id
join sys.schemas s on s.schema_id = o.schema_id
where o.type = 'V'
and s.name in ('your', 'schemas', 'here')
Customize as desired to select the views you want.

You can get views, schemas and definitions by quite standard way:
select * from information_schema.views

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.

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.

SSMS: How to view a stored procedure/view/function without scripting?

i want to look at the definition of a stored procedure, view, or user-defined function.
In SQL Server Management Studio 2005 the only way i've found to do this is:
Right-click
Script stored procedure as
ALTER To
New Query Editor Window
goto 1
i don't want to script it, i want to look at it.
My task today in SSMS is to quickly go through the stored procedures to find one i'm interested in. i've loaded up Enterprise Manager in Windows XP mode (MMC snap-in doesn't run nativly in 64-bit), and my job is much easier:
Push enter
goto 1
i'm trying to find the way to look at a stored procedure - i'm not interested in scripting it.
I did some quick google searches and found this.
Copy and Paste from website:
-- Get Stored Procedure Content
-- Name = Stored Procedure Name.
-- Colid = Multiple lines, their sequence.
SELECT text
FROM syscomments
WHERE id = (SELECT id FROM sysobjects WHERE name = '{0}')
ORDER BY colid
Depending on where the information is, have you tried to filter them "to find one I'm interested in"?
SELECT text
FROM syscomments c
INNER JOIN sysobjects o
ON o.id = c.id
WHERE o.type = 'P'
and o.Name = '{0}'
FOR XML PATH('')
exec sp_helptext N'<stored proc name>'
Example:
exec sp_helptext N'mydatabase.dbo.myStoredProc'
This will shows all the lines of the procedure without having to maneuver the GUI to the sp.
Using syscomments has potential problem: big procedures are splitted in several rows and sometimes important identifiers are divided into 2 parts. Like:
row1: .....veryimportantide
row2: ntifier.....
so, if you are looking for veryimportantidentifier - you will never find it. (for example - looking for all references of it)
When I look for something and it is very important - I generate scripts of all objects and navigate there using something like Notepad++ or Visual Studio
I found a solution for preview the stored function in SQL Server Management Studio 2012. It is non-programmer solution :)
Find chosen function in Object Explorer.
Click on it right mouse button.
Choose Modify.
Function preview is displayed. You can copy it to NotePad ++ and analyse.
I hope this will be helpful.