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.