Use SQL Statement in access 2007 [duplicate] - sql

What's wrong with this code:
Visual Basic 6.0 With access 2007
Private Sub Command1_Click()
Dim Sell_tbl, Stock_Bottle, res As String
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
res = ((Sell_tbl) - (Stock_Bottle))
Adodc1.RecordSource = Sell_tbl
Adodc1.Refresh
Adodc1.Caption = Adodc1.RecordSource
End Sub
Type Mismatch Error
I try to convert its result in other data type but it doesn't work. Can anyone help me?

Neither of these is a recordset, each is a string:
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
You need something on the lines of:
Dim Sell_tbl As DAO.Recordset
Dim Stock_Bottle As DAO.Recordset
Set Sell_tbl = CurrentDB.Openrecordset _
("SELECT Sum((Quantity)*12) As Qty FROM Sell_Detail Where Cateogry='Large'")
Set Stock_Bottle = CurrentDB.Openrecordset _
("Select Sum(No_Of_Bottle) As Btl FROM Add_Bottle Where Cateogry='Large'")
res = Sell_tbl!Qty - Stock_Bottle!Btl
The above is a rough outline, it could do with tidying up.

The reason for the error is because of statement:
s = ((Sell_tbl) - (Stock_Bottle))
If you look above that line, you are setting two string variables to SQL -- which is text not numeric.
You need to open recordsets with those sql strings, then get the results, then perform the math.

It is what I want....
Private Sub Command2_Click()
Dim con As New ADODB.Connection
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& App.Path & "\add_entry.mdb;Persist Security Info=False"
Dim rs As New ADODB.Recordset
Dim rs1 As New ADODB.Recordset
Dim result_hold As Integer
Dim large_tbl As String
Dim sell_large As String
large_tbl = "SELECT Sum(No_Of_Bottle) FROM add_cotton where Cateogry='Large'"
sell_large = "SELECT Sum(Quantity) FROM Sell_Detail where Cateogry='Large'"
rs.Open large_tbl, con, adOpenDynamic, adLockOptimistic
rs1.Open sell_large, con, adOpenDynamic, adLockOptimistic
result_hold = CInt(rs.Fields(0).Value) - CInt(rs1.Fields(0).Value)
Text1.Text = CStr(result_hold)
End Sub
'if u need to retreive whole colum use loop or etc.. but one thing is remember to you two sources
'never attach with single grid...

Related

Get max value from Access database using SQL

I need to get the max value from a column and store it at long varibale.
My VBA code :
Private Sub ADOFromExcelToAccessDstribute()
Dim dstibute_ID As Long
' get the next dstibute id
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim qry As String
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=W:\data\Database.accdb;jet
OLEDB:Database password=123;"
qry = "SELECT Max(distributeSummeryTable.distributeID) AS MaxOfdistributeID FROM
distributeSummeryTable;"
rst.Open qry, cnn, adOpenKeyset, adLockOptimistic
dstibute_ID = rst.MaxOfdistributeID
rst.Close
cnn.Close
'buile the export log
exportReportPacks
If (dstibute_ID = "" Or dstibute_ID = 0) Then
dstibute_ID = 1
End If
'add data to data base
ADOFromExcelToAccessDstributeSummeryTable (dstibute_ID)
ADOFromExcelToAccessFulldistributeSummeryTable (dstibute_ID)
End Sub
This is my database table and the field I want to return
I get an error in my code.
Info online and at StackOverflow didn't solve my issue.
SOLVED,
my syntax was wrong i should use ! insted of .
i try to store null value in long, it make error.
my change was :
If (rst!MaxOfdistributeID <> "") Then
dstibute_ID = rst!MaxOfdistributeID
End If

VBA(AUTOCAD) SQL query to store String Values

I have a small issue, I am trying to code a Macro for Autocad in VBA.
I am trying to read a certain column value through sending a SQL native query that connects to the database server.
The problem is that my String variable descToReturn that's going to hold a value of that column is returning null. I can't seem to figure out where I am wrong. So if anyone can advise that'd be great.
Here's the code below:
Private Sub btnDuplicate_Click()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
Dim BOMLineToCheck As AcadBlockReference
Dim BOMAttributes As Variant
Dim partNoToCheck As String
Dim i As Integer
Dim descToReturn As String
ConnectionString = "Provider=SQLxxxxx.1;Password=xxxx;Persist Security Info=True;User ID=xxxx;Data Source=xx\xx;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=xxx_xxx"
Set cnn = New ADODB.Connection
cnn.ConnectionString = ConnectionString
cnn.Open
'cnn.CommandTimeout = 900
Set rst = New ADODB.Recordset
StrQuery = "SELECT * FROM [My Table Name] WHERE [My Column]='partNoToCheck'"
For Each BOMLineToCheck In ThisDrawing.ModelSpace
If BOMLineToCheck.Name = "BOM3LINE_old" Then
BOMAttributes = BOMLineToCheck.GetAttributes()
For i = 0 To UBound(BOMAttributes)
If BOMAttributes(i).TagString = "PART#" Then
partNoToCheck = BOMAttributes(i).TextString
End If
Next i
End If
rst.Open StrQuery, cnn, adOpenDynamic
With rst
If Not .EOF Then
descToReturn = rst![My Coulmn]
End If
End With
rst.Close
MsgBox descToReturn
Next
End Sub
Look closely for a typo:
descToReturn = rst![My Coulmn]
You probably mean:
descToReturn = rst![My Column]
See the difference?
So, I found the answer, because I am bringing SQL within VBA environment, the syntax was not right and its a weird syntax:
correct Syntax for SQL query:
StrQuery = "SELECT * FROM [My Table] WHERE [My Column]= '" & partNoToCheck & "'"

Is there a limit to the query length being passed to ADODB?

I am currently testing a framework that stores a SQL query in a cell on an excel workbook and then passes the cell value to a variable. This variable then gets executed through rs.Open query, cn where:
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
and I have tried these for "query" :
Dim query as String
Dim query as Variant
or even playing with fixed length queries:
Dim query as String * 9999
In playing with the output of the query string, it cuts off somewhere around 8000. Google is coming up short for me, so I am coming here for answers. Is there a specific limit to what a variable can pass to recordset.Open()?
NB: The connection string I am using for this particular query is :
ConnectionString = "User ID=User;Password=PW;Data Source=DB;Provider=OraOLEDB.Oracle"
But if you know whether there is a system specific limit for Oracle, NetezzaSQL, or MS SQL Server (SQLOLEDB.1) please let me know. I will need to specify the limitations of each in order to define which new queries will need to be converted into stored procedures.
Here is the essentials of the code:
Sub RunQueryTable()
Dim cn As ADODB.Connection
Dim RS As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String
Dim SQLTable As Worksheet
Dim ConnectionString as String
Dim query As String 'Or Dim query As Variant 'Or Dim query As String * 9999
Dim i As Long
etc, etc.
Set SQLTable = Sheet32
Set cn = New ADODB.Connection
Set RS = New ADODB.Recordset
DB = _____
User = ______
PW = ____
ConnectionString = "User ID=" & User & _
";Password=" & PW & _
";Data Source=" & DB & _
";Provider=OraOLEDB.Oracle"
query = SQLTable.Cells(i, 3).Text
cn.Open (ConnectionString)
RS.CursorType = adOpenForwardOnly
RS.Open (query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Output").Cells(1, iCols + 1).Value = RS.Fields(iCols).Name
Next
Worksheets("Output").Cells(2, "A").CopyFromRecordset RS
RS.Close
cn.Close
End Sub
The specific error I am getting from VBA is : "ORA-00923: FROM keyword not found where expected" because the query is getting cut off.
Here's your problem:
query = SQLTable.Cells(i, 3).Text
Consider:
Range("A1").Value=string(12000,"*")
? len(range("a1").value) '>> 12000
? len(range("a1").text) '>> 8221

How to export SQL statement results to an Excel File

I have an Access DataBase and a form in Excel VBA. All the data I input into the DB is input through the VBA form.
This DB contains all the benefits cards we already received this year in the company. But the same employee can ask for the card twice or more, so we'll have more than one record on the DB for him.
What I need is when the number of records is greater than one, the SQL statement result should appear in a Excel report.
I use the SELECT (*) COUNT statement to know when there is more than one record that is compatible with the search criterion. But I can't make the result appear in an Excel file.
Here is my code:
Public Function Relatorio()
Dim sql As String
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rel As String
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & enderecoDB & ";Jet OLEDB:Database"
cn.Open
Set rs = New ADODB.Recordset
sql = "INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=" & enderecoDB & ";', 'SELECT * FROM [Planilha1$]') SELECT * FROM controle WHERE BP = " & controlectform.nmbpbox.Value & ";"
rs.Open sql, cn
End Function
When I run this code it gives me a message saying something like:
Can't locate the OPENROWSET Table exit
I'm not able to install new programs, so I need to do this using only Excel VBA and the Access DB.
How can I make this work?
I don't believe Access supports the OPENROWSET, dynamic table you're working with there. I have a lot of old projects that do this though, so here's my method
Public Function Relatorio()
Dim sql As String
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rel As String
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & enderecoDB & ";Jet OLEDB:Database"
cn.Open
Set rs = New ADODB.Recordset
dim path_To_XLSX
dim name_of_sheet
path_To_XLSX = "c:\temp\output.xlsx"
name_of_sheet = "Planilha1"
sql = sql = "SELECT * INTO [Excel 12.0;Database=" & path_To_XLSX & "]." & name_of_sheet & " FROM controle WHERE BP = '" & controlectform.nmbpbox.Value & "';"
rs.Open sql, cn
'If this application is in an unsecure environment, use the following code instead! This is to prevent a SQL injection, security concern here.
'As it is an Access Database, this is likely overkill for this project
'Create Command Object.
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cn
cmd1.CommandText = "SELECT * FROM controle INTO [Excel 12.0;Database=" & path_To_XLSX & "]." & name_of_sheet & " WHERE BP = ?"
' Create Parameter Object.
Set Param1 = Cmd1.CreateParameter(, adInteger, adParamInput, 5) 'use adVarchar for strings(versus adInteger), https://www.w3schools.com/asp/met_comm_createparameter.asp
Param1.Value = controlectform.nmbpbox.Value
Cmd1.Parameters.Append Param1
Set Param1 = Nothing
Set Rs = Cmd1.Execute()
End Function
I had this challenge so many years ago that I cant remember but this link ring the bell. check if it help.
https://stackoverflow.com/a/28889774/382588
try { connw.Open(); OleDbCommand command; command = new OleDbCommand( "Update Deliveries " + "SET Deliveries.EmployeeID = ?, Deliveries.FIN = ?, Deliveries.TodaysOrders = ? , connw); command.Parameters.Add(new OleDbParameter("#EMPID", Convert.ToDecimal(empsplitIt[1]))); command.Parameters.Add(new OleDbParameter("#FIN", truckSplit[1].ToString())); command.Parameters.Add(new OleDbParameter("#TodaysOrder", "R")); catchReturnedRows = command.ExecuteNonQuery();//Commit connw.Close(); } catch (OleDbException exception) { MessageBox.Show(exception.Message, "OleDb Exception"); }
you can use this, to print the actual SQL.
Private Sub Command2_Click()
Dim db As Database
Dim qr As QueryDef
Set db = CurrentDb
For Each qr In db.QueryDefs
TextOut (qr.Name)
TextOut (qr.SQL)
TextOut (String(100, "-"))
Next
End Sub
Public Sub TextOut(OutputString As String)
Dim fh As Long
fh = FreeFile
Open "C:\Users\rs17746\Desktop\Text_Files\sample.txt" For Append As fh
Print #fh, OutputString
Close fh
End Sub
Here is one more version for you. This will export the results of each query, each to a separate text file.
Private Sub Command0_Click()
Dim qdf As QueryDef
Dim strFileName As String
For Each qdf In CurrentDb.QueryDefs
If Left(qdf.Name, 1) <> "~" Then
'you need to figure out TransferText command. Maybe
'you won't be lazy and expect people to read it to
'you and tutor you on how it works.
strFileName = qdf.Name
'Docmd.TransferText ....
DoCmd.TransferText transferType:=acExportDelim, TableName:=strFileName, FileName:="C:\test\" & strFileName & ".txt", hasfieldnames:=True
End If
Next qdf
MsgBox "Done"
End Sub

Error while storing records from Access field in array

Situation :
I have this code which stores all the records from the field Shipment ID in an array called arrayShipmentID.
Dim conn As New ADODB.Connection
Dim connStr As String
Dim rs As ADODB.Recordset
Dim ShipmentIDSQL As String
Dim arrayShipmentID() As Variant
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "P:\PathToTheAccessDatabase\" & "NewVersion.accdb" & ";"
conn.ConnectionString = connStr
conn.Open
' Store Shipment IDs
Set rs = New ADODB.Recordset
ShipmentIDSQL = "SELECT [Shipment ID] FROM 12Dec"
rs.Open ShipmentIDSQL, conn, adOpenStatic, adLockReadOnly, adCmdText
If Not rs.EOF Then
arrayShipmentID = rs.GetRows
End If
Dim i As Integer
For i = 0 To UBound(arrayShipmentID, 2)
Debug.Print arrayShipmentID(0, i)
Next i
Set rs = Nothing
In order to make sure it works I Debug.Print each element of the array.
Issue :
This code WORKS most of the time, but for some reason, sometimes I get as a value 'subscript out of range' (instead of 181 in my case) for MsgBox UBound(arrayShipmentID, 2) and of course in that case Debug.Print doesn't display anything in the Immediate Window.
Any ideas where could this come from ?
With DAO recordsets you often have to find the recordcount to retrieve all records. That might be the case for ADO as well:
RecordCount = ' Obtain true count of records.
arrayShipmentID = rs.GetRows(RecordCount)
Also, I normally declare the variable as a simple Variant:
Dim arrayShipmentID As Variant