How to script views by a pattern

Naomi Nosonovsky 8,351 Reputation points
2025-05-09T14:14:17.4433333+00:00

Hi,

I'm wondering if there is a simple way to script views definitions by some pattern, e.g. views in a particular schema and named using 'ndb' in the name?

Thanks in advance.

SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
181 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 58,866 Reputation points
    2025-05-09T21:31:10.6+00:00

    I'm not sure I follow exactly what you want but it sounds like you want to capture the view definition for a subset of views. While you can get this from sys.sql_modules I personally would find it easier to just get the views from sys.views you care about and then reach into sys.sql_modules for the definition. I'd probably do something like this.

    SELECT v.object_id, v.name, s.name, m.definition
    FROM sys.views v 
    	JOIN sys.schemas s ON v.schema_id = s.schema_id
    	JOIN sys.sql_modules m ON v.object_id = m.object_id
    WHERE s.name = 'stg' AND v.name like '%ndb%'
    

    Given the above query you can do whatever you want with the definition. I'm unclear what your goal is. It seems like you're trying to generate dynamic SQL which takes the existing view definition, replaces CREATE VIEW with CREATE OR ALTER VIEW and then injecting some GO commands. Seems like your SELECT logic for that is correct.


1 additional answer

Sort by: Most helpful
  1. Naomi Nosonovsky 8,351 Reputation points
    2025-05-09T20:29:38.69+00:00

    I used the following code which seems to work:

    DECLARE @SQL NVARCHAR(MAX)
    SET NOCOUNT ON 
    SELECT @SQL = STRING_AGG(REPLACE(definition, ' VIEW', ' OR ALTER VIEW'), CHAR(13)+CHAR(10) + 'GO' + CHAR(13) + CHAR(10)) FROM sys.sql_modules m
    WHERE OBJECT_NAME(m.object_id) LIKE 'view_stg_ndb%'
    
    select @SQL
    
    

    I needed to output results to text and set it to big number in the Tools/Options.

    0 comments No comments

Your answer