Reputation: 338
I am trying to execute an entire file of SQL commands on SQL Server from a vb.net app. The issue is that if the SQL file contains any CREATE PROCEDURE
commands, I get the following error:
A critical error has occurred. 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch. Incorrect syntax near the keyword 'PROC'
Dim sql = sqlFile.ReadToEnd()
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("SiteSqlServer").ToString), cmd As New SqlCommand
With cmd
.Connection = conn
.CommandType = CommandType.Text
.CommandText = sql
.CommandTimeout = 300
End With
conn.Open()
cmd.ExecuteNonQuery
conn.Close()
How can I execute sql files over a SqlConnection
containing CREATE PROCEDURE
commands?
Upvotes: 0
Views: 442
Reputation: 216263
You could leave the GO
separator in your script, but you should execute the script using the Microsoft.SqlServer.Smo
objects that you can find in the
C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies
(or the appropriate dir for your version)
Dim cmd = File.ReadAllText("d:\temp\create.sql")
Using con = new SqlConnection("....")
Dim svrConnection = new ServerConnection(con)
Dim server = new Server(svrConnection)
Dim col = new StringCollection()
col.Add(cmd)
server.ConnectionContext.ExecuteNonQuery(col)
End Using
You need to have a reference (and imports) to the following assemblies
Upvotes: 0
Reputation: 754268
The issue is that each CREATE PROCEDURE
needs to be the first statement in a batch (as the error message clearly says).
If you'd be executing your .sql
in SQL Server Management Studio, you could use GO
as separators:
....
GO
CREATE PROCEDURE dbo.SomethingOrAnother......
but this GO
is a SSMS-specific separator - not a general SQL statement.
There's really no "magic" way to execute a complete .sql
script file against SQL Server from VB.NET - what I usually do are these steps:
.sql
file into a stringGO
separatorThat way, any CREATE PROCEDURE ....
will be the first statement in a separate batch, and then your script should work just fine from VB.NET.
Upvotes: 2