How to create ALTER scripts instead of CREATE scripts using SMO (Server Management Object)
Asked Answered
H

5

6

I am using the Microsoft.SqlServer.Management.Smo classes to script out SQL scripts for stored procedures, tables, views etc. I am doing this for putting them in source control.

Instead of the CREATE scripts for stored procedures, how can I get ALTER scripts for them? Is there an setting / option in the ScriptingOptions' properties?

Heuer answered 1/7, 2010 at 16:51 Comment(1)
As a workaround, once the scripts are created, I'm reading them, changing the CREATE to ALTER and writing them back out.Heuer
H
1

There seems to be no setting for ALTER scripts. The property with ScriptingOptions.ScriptDrops as true creates the drop statements. The downside to this is that the permissions would have to reassigned.

Closing this question.

Heuer answered 9/7, 2010 at 16:22 Comment(1)
I agree - I tried this before and never found a method for scripting out an alter. I ended up resulting to using the ScriptingOptions (msdn.microsoft.com/en-us/library/…) to specify a check for existence and drop if found.Pentheus
L
4

The StoredProcedure class has a method that creates ALTER statements.

https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.storedprocedure.scriptheader(v=sql.120).aspx

Usage

var sprocHeader = sproc.ScriptHeader(forAlter: true);
var sprocBody = sproc.TextBody;
Longbow answered 3/9, 2015 at 15:35 Comment(1)
This actually is the key point for SP creating "alter" script. Thanks !Erythromycin
A
2
  1. Use the normal scriptingoptions and tools for SMO c#
  2. then simply use.

    foreach (string line in script)
                {
                    string l = line.Replace("CREATE FUNCTION", "ALTER FUNCTION");
                }
    
  3. Ta Da. :).

Actinoid answered 22/7, 2011 at 10:7 Comment(0)
H
1

There seems to be no setting for ALTER scripts. The property with ScriptingOptions.ScriptDrops as true creates the drop statements. The downside to this is that the permissions would have to reassigned.

Closing this question.

Heuer answered 9/7, 2010 at 16:22 Comment(1)
I agree - I tried this before and never found a method for scripting out an alter. I ended up resulting to using the ScriptingOptions (msdn.microsoft.com/en-us/library/…) to specify a check for existence and drop if found.Pentheus
H
1

Have a look at DBSourceTools.

It is a GUI tool to script all objects in a SQL Database to disk, specifically for source-code control of databases.The back-end uses SMO.

Hypnoanalysis answered 26/7, 2010 at 5:14 Comment(0)
Q
0

I use this in compare between servers. toSP is the textbody of the SP. If there is none on the "TO" server I do Create() otherwise it is Alter() for the loaded up StoredProcedure spT

If toSP = "" Then  ' Empty
    spT.Create()
Else
    spT.Alter()
End If
Qualls answered 1/6, 2011 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.