10

Is there a way to get the statement that created a view for an existing view in SQL Server 2008? I thought there was a stored procedure or some metadata that had this data, but I'm not finding anything.

Braiam
  • 1
  • 11
  • 47
  • 78
rosscj2533
  • 9,195
  • 7
  • 39
  • 56

7 Answers7

22

Have you had a look at sp_helptext?

sp_helptext 'dbo.name_of_view'

SQL SERVER – Stored Procedure to display code (text) of Stored Procedure, Trigger, View or Object

DJDaveMark
  • 2,669
  • 23
  • 35
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • The result is splitted in different rows: how to have the actual content in a single string to be used to generate a single sql statement? – ff8mania May 06 '15 at 17:50
  • Full syntax is: `sp_helptext [ @objname = ] 'name' [ , [ @columnname = ] computed_column_name ]` from [the official MS docs](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-helptext-transact-sql). – DJDaveMark Jun 20 '19 at 20:15
8

Right click on the view and script it.

HLGEM
  • 94,695
  • 15
  • 113
  • 186
7

It's in sys.sql_modules. Other schema tables like INFORMATION_SCHEMA ones only contain the first 4000 characters of the definition (they truncate).

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
3

Right click on the View name, then left click "SCRIPT VIEW as", then left click "ALTER TO", then left click "NEW QUERY EDITOR WINDOW" -- bingo, your there! To print, click on the script screen and then send to your printer using your toolbar printer icon or click on FILE>>PRINT. Of course, be careful to exit without making any changes. This works the same for stored procedures.

3

You can see the script as code, and copy paste it into an editor like this:

SELECT 
    v.TABLE_NAME, 
    v.VIEW_DEFINITION 
FROM 
    INFORMATION_SCHEMA.VIEWS v 
WHERE 
    v.TABLE_NAME LIKE '%%'

and insert the view name you want.

TT.
  • 15,774
  • 6
  • 47
  • 88
1

In case it helps someone in the future, here's a little script I put together to output the creation script for all views in a database.

DECLARE @definition varchar(max)
DECLARE @view CURSOR
SET @view = CURSOR FOR
    SELECT m.definition FROM sys.views v INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
OPEN @view
FETCH NEXT FROM @view INTO @definition
WHILE @@FETCH_STATUS = 0 BEGIN
    PRINT @definition
    PRINT 'GO'
    FETCH NEXT FROM @view INTO @definition
END CLOSE @view DEALLOCATE @view
Alain
  • 26,663
  • 20
  • 114
  • 184
0

USER needs ViewDefinition rights to view Definition column (SQL Create Statement)

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 10 '23 at 20:52