3

The following powershell script seems to generate a "Create" stored procedure script successfully

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$srv = new-object Microsoft.SqlServer.Management.Smo.Server("<SERVER>")
$db = $srv.Databases.Item("<Database>")
$proc = $db.StoredProcedures.Item("<StoredProcedure>")
$proc.Script() > testScript.sql

Is there anyway to create an "Alter" using a similar approach i.e. changing the scripting options? I am referencing a SQL Server 2005 environment.

I could always add a statement to replace "CREATE PROC" with "ALTER PROC" but this seems inelegant...

2

1 Answer 1

3

The following Powershell script seems to work for me:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null 
$srv = new-object Microsoft.SqlServer.Management.Smo.Server("<SERVER>") 
$db = $srv.Databases.Item("<DATABASE>") 
$proc = $db.StoredProcedures | ?{ $_.Name -eq "<STORED PROC>"} 
$retval = $proc.ScriptHeader($true) + $proc.TextBody 
$retval > testScript.sql

Note that the passing true to the following command creates an alter Header:

$proc.ScriptHeader($true) 
Sign up to request clarification or add additional context in comments.

1 Comment

I want to alter a function the same way. I get an error though saying "you cannot call a method on a null-valued expression" and it seem to be refering to $retval. Suggestions? Also the testScript.sql file, is this the file containg the modifications you want to make (ie. the alter script). Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.