0

I am building a command string in VBA to be handed over to Microsoft SQL Server Management Studio which looks something like this:

IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp   
GO
CREATE TABLE #temp

However, the command string in VBA does not include line breaks required for the GO statment which causes the execution to fail. Any ideas?

3 Answers 3

1

When you are building your command string, use vbCrLf to create a new line.

Example:

Dim strMyCommand As String

strMyCommand = "IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp" & vbCrLf & _
  "GO" & vbCrLf & _
  "CREATE TABLE #temp"

Debug.Print strMyCommand 
Sign up to request clarification or add additional context in comments.

Comments

0

you cannot use GO in an sql string, even if separated by carriage returns and line feeds... this is a batch separator only known to SQLCMD and SQL Server Management Studio. For the above query you have to issue two calls to your database connection.

For instance, this works (on a local SQL Server instance) :

Sub test()
    Dim oConn As ADODB.Connection
    Set oConn = New Connection
    oConn.ConnectionString = "Provider=SQLNCLI11;Server=(local);Integrated Security=SSPI;"
    oConn.Open
    oConn.Execute "IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp"
    oConn.Execute "Create table #temp(somecolumn int)"

    oConn.Close
End Sub

1 Comment

"GO... is a batch separator only known to SQLCMD and SQL Server Management Studio." This was my initial thought too. Then I re-read fboehlandt's question. I interpret "[the SQL code will] be handed over to Microsoft SQL Server Management Studio" as "I will execute the SQL code in SSMS."
0

We can separate the SQL queries with a semicolon. The following should work without any issues and you only need to make one call to your database connection.

IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp;CREATE TABLE #temp(ID INT);

This works on a local SQL Server instance:

Sub MyTest()
    Dim con As ADODB.Connection
    Set con = New Connection
    con.ConnectionString = "Provider=SQLNCLI11;Server=(local);Integrated Security=SSPI;"
    con.Open
    con.Execute "IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp;Create table #temp(somecolumn int);"

    con.Close
End Sub

Comments

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.