line breaks in SQL query string from VBA - sql

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?

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

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

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

Related

Table '#temptable' does not exist when executing drop table [#temptable] from code behind

I'm using a bulkcopy to a temp table that then will be used to MERGE to the main table. All is working but when I try dropping my temp table, I get an error saying 'Table '#temptable' does not exist'
Basically I do the following.
'get data from excel to a datatable.
Dim cmd As New OleDbCommand(sqlstring, excelConnection)
dt.Load(cmd.ExecuteReader())
'create sql connection
Using sqlcon As SqlConnection =
New SqlConnection(ConfigurationManager.ConnectionStrings("SQLCON").ConnectionString)
sqlcon.Open()
'create temp table
Dim sqlcmd As New SqlCommand("create table #tbltemp (ID int, FirstName nvarchar(50),LastName nvarchar(50),JobDesc nvarchar(50))", sqlcon)
sqlcmd.ExecuteNonQuery()
Try
'start bulcopy
Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(sqlcon)
'map columns
Dim mapID As New SqlBulkCopyColumnMapping("ID", "ID")
bulkcopy.ColumnMappings.Add(mapTMID)
Dim mapFName As New SqlBulkCopyColumnMapping("FirstName", "FirstName")
bulkcopy.ColumnMappings.Add(mapFName)
Dim mapLName As New SqlBulkCopyColumnMapping("LastName", "LastName")
bulkcopy.ColumnMappings.Add(mapLName)
End Using 'end bulkcopy using
'Inserts new records to main from temptable
Dim mergesql As String = "merge into dbo.Main as Target " & _
"using #tbltemp as Source " & _
"on " & _
"(Target.ID = Source.ID) " & _
"when not matched then " & _
"insert (ID,FirstName,LastName) values (Source.ID,Source.FirstName,Source.LastName);"
sqlcmd.CommandText = mergesql
sqlcmd.ExecuteNonQuery()
'Clean up stuff
cmd.CommandText = "DROP TABLE [#tbltemp]"
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
'close sql con
sqlcon.Close()
End Try
'close excel con
excelConnection.Close()
End Using ' end using sqlcon
Like I said, everything seems to be working except for dropping the table. Does this means that temp table has been dropped automatically?
I tried running some tests and searched around but no luck.
cmd is the OleDbcommand associated with you excelconnection and not a SqlCommand associated with your Database connection.
Incidently, I use this technique all the time and you can also create the temporary table as...
Select Top 0 * Into #tbltemp From dbo.Main
This save on defining the columns in a static create table statement.
Also if you are working with temp tables a lot within the same connection then you can check it exists and drop it using...
If Object_Id('TempDB..#tbltemp') Is Not Null Drop Table #tbltemp
SQL Server will automatically drop temp tables when the connection closes, so there isn't actually any need for you to do this.
Not sure why it is failing on the drop part though. You might not have the right permissions.

How to check if a database and tables exist in sql server in a vb .net project?

Can anyone tell me how I would go about checking if a database and tables exists in sql server from a vb.net project? What I want to do is check if a database exists (preferably in an 'If' statement, unless someone has a better way of doing it) and if it does exist I do one thing and if it doesn't exist I create the database with the tables and columns. Any help on this matter would be greatly appreciated.
Edit:
The application has a connection to a server. When the application runs on a PC I want it to check that a database exists, if one exists then it goes and does what it's supposed to do, but if a database does NOT exist then it creates the database first and then goes on to do what it's supposed to do. So basically I want it to create the database the first time it runs on a PC and then go about it's business, then each time it runs on the PC after that I want it to see that the database exists and then go about it's business. The reason I want it like this is because this application will be on more than one PC, I only want the database and tables created once, (the first time it runs on a PC) and then when it runs on a different PC, it sees that the database already exists and then run the application using the existing database created on the other PC.
You can query SQL Server to check for the existence of objects.
To check for database existence you can use this query:
SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase'
To check for table existence you can use this query against your target database:
SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U'
This below link shows you how to check for database existence is SQL Server using VB.NET code:
Check if SQL Database Exists on a Server with vb.net
Referenced code from above link:
Public Shared Function CheckDatabaseExists(ByVal server As String, _
ByVal database As String) As Boolean
Dim connString As String = ("Data Source=" _
+ (server + ";Initial Catalog=master;Integrated Security=True;"))
Dim cmdText As String = _
("select * from master.dbo.sysdatabases where name=\’" + (database + "\’"))
Dim bRet As Boolean = false
Using sqlConnection As SqlConnection = New SqlConnection(connString)
sqlConnection.Open
Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
Using reader As SqlDataReader = sqlCmd.ExecuteReader
bRet = reader.HasRows
End Using
End Using
End Using
Return bRet
End Function
You could perform the check in another way, so it's done in a single call by using an EXISTS check for both the database and a table:
IF NOT EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase')
BEGIN
-- Database creation SQL goes here and is only called if it doesn't exist
END
-- You know at this point the database exists, so check if table exists
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U')
BEGIN
-- Table creation SQL goes here and is only called if it doesn't exist
END
By calling the above code once with parameters for database and table name, you will know that both exist.
Connect to the master database and select
SELECT 1 FROM master..sysdatabases WHERE name = 'yourDB'
and then on the database
SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'yourTable'
i dont know the exact vb syntax but you only have to check the recordcount on the result
For tables and other objects inside a database, I usually do it this way but it's really personal preference.
IF OBJECT_ID('dbo.blah') IS NOT NULL
BEGIN
END
For VB.NET, I'd wrap this in a stored procedure and call that. I'm sure there are also ways to do this with Linq.
You can use This query for check database
IF DB_Id('YourDatabaseName') IS NOT NULL
BEGIN
PRINT 'DB EXISTS'
END
ELSE
BEGIN
PRINT 'DB NOT EXISTS'
END
Friend Function CheckDatabaseExists(server As String, database As String) As Boolean
Dim connString As String = "Data Source=" + server + ";Initial Catalog=master;Integrated Security=SSPI"
Dim cmdText As String = "select * from master.dbo.sysdatabases where name='" + database + "'"
Dim bRet As Boolean = False
Using sqlConnection As SqlConnection = New SqlConnection(connString)
sqlConnection.Open
Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
Using reader As SqlDataReader = sqlCmd.ExecuteReader
bRet = reader.HasRows
End Using
End Using
End Using
Return bRet
End Function
Public Function SQLDatabaseExist(ByVal DefaultConnectionString As String, ByVal DataBaseName As String) As Boolean
Try
'CREATE DATABASE
Dim SqlString As String = ""
SqlString = "SELECT CASE WHEN EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'" & DataBaseName & "') THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END"
Dim ExcRet As Integer = 0
Using connection As New SqlConnection(DefaultConnectionString)
Dim command As New SqlCommand(SqlString, connection)
command.Connection.Open()
ExcRet = command.ExecuteScalar()
command.Connection.Close()
command.Dispose()
End Using
Return ExcRet
Catch ex As Exception
Return False
End Try
End Function

Adding records to the table programatically

i am trying to append some records from a certain table to a new table ,
when i try it i am unable to append to the values
to the new table i.e "Table1" in this case what might be the reason for the data not getting appended to the table?
From what I can tell from your code you are just appending records from one table in your database into another table in the same database. You don't need to use a Recordset object to accomplish this; an INSERT INTO query will accomplish what you want.
Dim strSQL as String
Dim db as DAO.Database
Set db = CurrentDb
strSQL = "INSERT INTO Table1 ( UPI, COMPANY ) " & _
"SELECT INPUT_TBL.ID, INPUT_TBL.COMPANY FROM INPUT_TBL"
db.Execute strSQL, dbFailOnError
Set db = Nothing
Note that I used CurrentDb for the db object, under the assumption that the current database is the same one at C:\Users\test.accdb. If that's not the case, then you will need to do one of two things:
If you can add both of these tables as linked tables to the database you are running this code in, you can just use the same code as above. Instructions on how to add tables from an external database to your current database are available here: http://office.microsoft.com/en-us/access-help/import-or-link-to-data-in-another-access-database-HA001227658.aspx#BM3 and many other places on the internet.
If you can't add linked tables to your database for some reason, you can add IN clauses to the previous SQL string, which would become:
Dim strSQL as String
Dim db as DAO.Database
Dim dbname as String
Set db = CurrentDb
dbname = "C:\Users\test.accdb"
strSQL = "INSERT INTO Table1 ( UPI, COMPANY ) IN """ & dbname & """ " & _
"SELECT INPUT_TBL.ID, INPUT_TBL.COMPANY FROM INPUT_TBL IN """ & dbname & """"
db.Execute strSQL, dbFailOnError
Set db = Nothing
This code would allow you select the data from Table1 in the external database and add it to INPUT_TBL in the same external database.

Change data type of column in multiple tables in Access with VBA

I am fairly new to using VBA in MS Access and I am having trouble embedding SQL statements into VBA code. I have a database with almost 200 tables, and I would like to change the data type of one column (named lake) in each table to a "text" data type. I wrote the following code, but keep getting a syntax error for the ALTER TABLE statement.
Public Sub changeDataType()
Dim db As DAO.Database
Dim table As DAO.TableDef
Set db = CurrentDb
For Each table In db.TableDefs
DoCmd.RunSQL "ALTER TABLE" & table.Name & "ALTER COLUMN [lake] TEXT(100);"
Next
Set db = Nothing
End Sub
Can anyone tell me why I'm getting the syntax error?
Thanks,
Paul
this statement will not be correct:
DoCmd.RunSQL "ALTER TABLE" & table.Name & "ALTER COLUMN [lake] TEXT(100);"
if, for instance "table.Name" = "myTable", the resulting statement will look like this:
DoCmd.RunSQL "ALTER TABLEmyTableALTER COLUMN [lake] TEXT(100);"
try adding a space to separate the name, like this:
DoCmd.RunSQL "ALTER TABLE [" & table.Name & "] ALTER COLUMN [lake] TEXT(100);"

How to check table exist or not exist

How to check table is there or not?
Using VB 6.0
cmd.CommandText = "drop table t1"
cmd.Execute
Above code is working fine, but if table is not exist then it showing “table does not exit”
How to check table exist or table not exist?
Need VB CODE help?
If you just want to drop the table without throwing an error message, you can use the following SQL if you're using MySQL.
DROP TABLE t1 IF EXISTS
Other databases have a similar feature, but the syntax is different. To do the same in MSSQL:
IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 't1') DROP TABLE t1;
Although that looks very ugly.. there must be a better syntax to get the same result.
For a Jet MDB (and perhaps generically for many OLEDB Providers) you can use an approach like:
Private Sub Main()
Dim cnDB As ADODB.Connection
Set cnDB = New ADODB.Connection
cnDB.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Jet OLEDB:Engine Type=5;Data Source='sample.mdb'"
'Check presence of table --------------
Dim rsSchema As ADODB.Recordset
Set rsSchema = _
cnDB.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, "t1", Empty))
If rsSchema.BOF And rsSchema.EOF Then
MsgBox "Table does not exist"
Else
MsgBox "Table exists"
End If
rsSchema.Close
Set rsSchema = Nothing
'--------------------------------------
cnDB.Close
End Sub
You'd be better off checking for existence of the table concerned, rather than trying to drop it.
The SQL syntax is dependent on the database server/engine you're using, but for Sql Server you could use something like:
Sql Server 2000:
SELECT 1 as Exists FROM sysobjects WHERE name = 't1'
Sql Server 2005/2008:
SELECT 1 as Exists FROM sys.objects WHERE name = 't1'
You can then use VB like:
Dim rs as Recordset
Dim iExists as Integer
rs = cmd.Execute
On Error Goto DoesNotExist
rs.MoveFirst
iExists = CInt(rs!Exists)
DoesNotExist:
If iExists = 1 Then
' Put code here for if the table exists
Else
' Put code here for if the table does not exist
End If
Note: This code needs tidying up and "productionising" (i.e. I haven't actually tested that it works as I don't have VB6 on this machine)