We allow our uses to alter certain views for reports and what not based on some application field meta data that we keep track of in our application. These fields can be created at run time. I have a standard process in place to alter the views when a field is added or removed. I now need to do this programmatically however, which means I need to be able to pull the current Alter view script, make my modifications, and then execute it against the database. The last two steps are easy enough, but the first part is giving me some trouble.
Design decisions aside (as they are out of my hands in this particular instance). I would like to know how to retrieve the Alter view script that Sql server management studio uses for the View->Edit command.
I require the exact same output as that command because I have comment hooks in my scripts that allow my edits to occur.
Related questions, but not quite what I am looking for.
How do I programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?
In MSSQL, how do I generate a CREATE TABLE statement for a given table?
SSMS uses SMO under the covers. The Scripter can retrieve the definition of any SQL object.
If you want a T-SQL based approach, then use sys.sql_modules, it contains the T-SQL definition of every non-encrypted object in the database, including views.
SELECT [definition]
FROM sys.sql_modules
WHERE [object_id] = OBJECT_ID('dbo.' + @ViewName);
-- you don't need the type check if you are passing in the name of a view
-- you can do the schema check using OBJECT_ID instead of an extra join
-- if you want to reference system_sql_modules it is unlikely they
-- will have dbo schema, if you want to support this use a separate query IMHO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With