How do I convert, in Classic ASP, this (example) comma separated Querystring
Illinois, Iowa, Wisconsin, Indiana, Kentucky,Missouri to
'Illinois', 'Iowa', 'Wisconsin', 'Indiana', 'Kentuck','Missouri'
I am using Dreamweaver and need this format to select records from a table which contain one of the states in the string Using IN clause.
If you need just the conversion here it is:
origstring = "Illinois, Iowa, Wisconsin, Indiana, Kentucky, Missouri"
convertedstring = "'" &replace(origstring, ", ","', '") &"'"
But let's say you (or anyone else) have a querystring with states:
strinclause = ""
arrstates = Split(Request.QueryString("states"), ",")
if(Ubound(arrstates) > 0) Then
for i=0 to Ubound(arrstates)
'VALIDATE/CLEAN YOUR ARRAY ITEMS AND BUILD YOUR STRING IN THIS WAY:
strinclause = strinclause & "'" &arrstates(i)& "',"
next
'NOW REMOVE LAST COMA
strinclause = Left(strinclause,Len(strinclause)-1)
end if
'HERE YOU CAN USE YOUR STRING THAT WILL BE IN THE FORMAT YOU ASKED
Jut spitballing, but you could do something like this:
<%
Dim qs : qs = Trim("" & Request.QueryString("states") ' e.g. "Illinois, Iowa, Wisconsin, Indiana, Kentucky, Missouri"
Dim cmd : Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = db.connection ' defined elsewhere
cmd.ActiveConnection.CursorLocation = adUseClient ' 3
cmd.CommandType = adCmdText ' 1
cmd.CommandTimeout = 90
dim inp : inp = Split(qs, ",") ' states
dim sql, i : ReDim sql (ubound(inp)) ' for sql
for i = 0 to ubound(inp)
sql(i) = "select ?" ' parameter in string
cmd.Parameters.Append cmd.CreateParameter("#p" & i, adVarChar, adParamInput, 100, inp(i)) ' actual typed parameter object
next
cmd.CommandText = "select id, stock from warehouse where state in (" & Join(sql, " union ") & ")"
Set rs = cmd.Execute
Do While Not rs.eof
response.write "<p>" & rs("id") & ": " & rs("stock") & "</p>"
rs.MoveNext
Loop
Set rs = Nothing
Set cmd = Nothing
%>
Related
Set rs = conn.Execute("SELECT unitcp_qual_var.instance_id," & _
"*FROM qualified_data INNER JOIN unitcp_qual_var ON qualified_data.unit_id = unitcp_qual_var.unit_id AND qualified_data.baseline_id = unitcp_qual_var.baseline_id AND qualified_data.qualified_id = unitcp_qual_var.qualified_id" & _
"WHERE (qualified_data.unit_id = 19419) AND (unitcp_qual_var.port_id = 1) AND (qualified_data.unit_id = 19419) AND (qualified_data.baseline_id = 2) AND (qualified_data.mdu_id = 622) AND (unitcp_qual_var.instance_id = 2);")
' "ORDER BY qualified_data.das_time Asc;")
Here's a quick rewrite adding the required space between your ON conditions and your WHERE clause as well as incorporating the ORDER BY. I'm adding a variable to hold the SQL string so it can be dumped to your immediate/debug window so you can see the output and test instead of dealing with tricky error messages:
strSQL="SELECT unitcp_qual_var.instance_id, *" & _
" FROM qualified_data INNER JOIN unitcp_qual_var ON qualified_data.unit_id = unitcp_qual_var.unit_id AND qualified_data.baseline_id = unitcp_qual_var.baseline_id AND qualified_data.qualified_id = unitcp_qual_var.qualified_id" & _
" WHERE (qualified_data.unit_id = 19419) AND (unitcp_qual_var.port_id = 1) AND (qualified_data.unit_id = 19419) AND (qualified_data.baseline_id = 2) AND (qualified_data.mdu_id = 622) AND (unitcp_qual_var.instance_id = 2)" & _
" ORDER BY qualified_data.das_time Asc;"
'dump out to immediate window/pane (View>>Immediate to activate)
debug.print strSQL
'Run the sql into rs recordset
Set rs = conn.Execute(strSQL)
I'm using a DoCmd.TransferSpreadsheet to import data from Excel to Access.
Everything works fine except some Excel rows that are truncated because there are too much bytes for an Access single row (not field).
I noticed that every field in Access is created as a text(255) while my Excel rows are all no more than 100 characters.
I think that if I manage to import my Excel files creating fields with a default length of 100 chars, I will no longer get truncated data.
Is there a way to set the default text length for Access fields to a specific number?
UPDATE
Decreasing the default field text size in Access 2010 options seems to be ignored when running DoCmd.TransferSpreadsheet
To set the default text length for Access (2007), click the Office button > "Access Options button" > "Object Designers" (in the pane on the left), then under Table Design, enter 50 in the Default Text Field Size box and click OK.
I wrote my own import function, and it works:
' Import from an Excel with a default field length different from 255 (must be < 255)
Function importFromExcel(fileName As String, fieldLength as integer)
Dim my_xl_app As Object
Dim my_xl_worksheet As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Workbooks.Open(fileName)
Set s = my_xl_workbook.Worksheets(1)
Dim fieldsNumber As Integer
Dim recordNumber As Long
fieldsNumber = s.cells(1, s.Columns.Count).End(1).Column
recordNumber = s.cells(s.Rows.Count, 1).End(3).Row
tablename = "[" & Replace(GetFilenameFromPath(fileName), ".", "_") & "]"
On Error Resume Next
DoCmd.RunSQL "DROP TABLE " & tablename
On Error GoTo 0
' Creo tabella
sql = "CREATE TABLE " & tablename & " (F1 TEXT(" & fieldLength & ")) "
DoCmd.RunSQL sql
For i = 2 To fieldsNumber
sql = "ALTER TABLE " & tablename & " ADD COLUMN F" & i & " TEXT(" & fieldLength & ")"
DoCmd.RunSQL sql
Next
' Ora insert
For i = 1 To recordNumber
sql = "INSERT INTO " & tablename & " VALUES ("
For j = 1 To fieldsNumber
sql = sql & " '" & Replace(s.cells(i, j), "'", "''") & "',"
Next
sql = Mid(sql, 1, Len(sql) - 1)
sql = sql & ")"
Next
my_xl_workbook.Close SaveChanges:=False
Set my_xl_app = Nothing
End Function
I would like to connect to my Access tables using VBA. I want to be able to type in a purchase order number, and reference that value in a query to the Access table. I want to print the results of that query to my Excel worksheet. This is what I have so far.. any ideas?
Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Enter Purchase Order Number:")
Range("A1").Value = myValue
Call ADO_Conn(myValue)
End Sub
Sub ADO_Conn(myValue)
Dim conn As New Connection
Dim rstAnswer As New ADODB.Recordset
Dim connected As Boolean
Dim RootPath, DBPath As String
Dim tempString As String
connected = False
RootPath = "Z:\BSD Internship Program\FY14 Intern Files\John Jameson\Vouchers"
DBPath = RootPath & "Acquisition Support Datamart Build 9.11-03.accdb"
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= Z:\BSD Internship Program\FY14 Intern Files\John Jameson\Vouchers\Acquisition Support Datamart 9.1103.accdb;"
connected = True
rstAnswer.Open "SELECT VW_PUB_PURCHASE_ORDER.PO_NO FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
Do Until rstAnswer.EOF
tempString = CStr(rstAnswer!VW_PUB_PURCHASE_ORDER)
Application.ActiveWorkbook.Worksheets("Sheet1").Range("A5").Value = tempString
rstAnswer.MoveNext
Loop
rstAnswer.Close
conn.Close
connected = False
End Sub
A couple of things about your initial query:
rstAnswer.Open "SELECT VW_PUB_PURCHASE_ORDER.PO_NO FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
You are searching only for PO_NO in this query, so that is the only value that will return. If you want more than just that data (as I assume you might), then you want this:
rstAnswer.Open "SELECT * FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
... where the asterisk means "all".
In addition, this bit concerns me:
' " & myValue & " '
You are adding leading and trailing blanks to your search term. This may or may not be what you want, but I assume that you do not want this. You probably want:
'" & myValue & "'
And if your PO_NO is a numeric value, you need to omit the apostrophes:
" & myValue & "
Lastly, I don't think you want to loop at all. The SELECT query will return all the results without requiring you to iterate rows. Maybe you should try getting rid of your "do" loop and using this instead:
Worksheets("Sheet1").Range("A5").CopyFromRecordset rstAnswer
Your query values will then be dropped into a dynamic range starting at the designated sheet & cell.
I didn't test the code so I might not have caught everything, but those jumped out at me.
Hope that helps!
Nate
I need short vba code to convert ms access table field to comma delimited string variable
T1.F to 'A','123','008','A'
A
123
008
A
The following will get your desired string in s :
Dim s as String, rs as Recordset
s = " Select [F] from [T1] "
Set rs = CurrentDb.OpenRecordset(s)
s = ""
While Not rs.EOF
s = s & "'" & rs(0) & "',"
rs.moveNext
Wend
s = Left(s,Len(s) - 1)
rs.close
I'm writing a function in Excel VBA which will be called to extract data from an Access database, I'm using ADO connection. The function Get_g_gtop has parameters defined as bellow. Now, I try to use a command object to get the value from recordset, however, I got the error message 3021 : Either BOF or EOF is true, or current record has been deleted. Requested operations requires a current record. The debug points to the line : Get_g_gtop = rst.Fields(0).Value.
Is there anything wrong with the SQL statement to query in Access? Any advice would be highly appreciate!
Bing
Function Get_g_gtop(ByVal VehType As String, ByVal Speed As Single) As Variant
Dim Dbfilepath As String
Dbfilepath = "C:\Users\sevenice\Desktop\EM Database.accdb"
Set cnn = New ADODB.Connection
cnn.Open "Provider= Microsoft.ACE.OLEDB.12.0;" & " Data Source=" & Dbfilepath & ";" & "Persist Security Info =False;"
'Set rst = New ADODB.Recordset
Set cmd = New ADODB.Command
cmd.ActiveConnection = cnn
'Dim QueryStr As String
Dim S As Single
If StrComp(VehType, "LDV") * StrComp(VehType, "LDT") * StrComp(VehType, "LHD<=14K") * StrComp(VehType, "LHD<=19.5K") = 0 Then
S = 35.6
'QueryStr = "SELECT [g/gtop] FROM [EM Database].[N (t) Data] WHERE [Vehicle Category]= "" & VehType & "" AND S = 35.6 " & " AND [Speed Lower] <= " & Speed & " AND [Speed Upper] >= " & Speed & ";"
cmd.CommandText = "SELECT [g/gtop] FROM [EM Database].[N (t) Data] WHERE [Vehicle Category]= "" & VehType & "" AND S = 35.6 " & " AND [Speed Lower] <= " & Speed & " AND [Speed Upper] >= " & Speed & ";"
'rst.Open QueryStr, cnn
Set rst = cmd.Execute
Get_g_gtop = rst.Fields(0).Value
ElseIf StrComp(VehType, "MHD") * StrComp(VehType, "HHD") * StrComp(VehType, "Urban Bus") = 0 Then
S = 26.7
QueryStr = "SELECT [g/gtop] FROM [EM Database].[N (t) Data] WHERE [Vehicle Category]=" & VehType & " AND S = 26.7 " & " AND [Speed Lower] <= " & Speed & " AND [Speed Upper] >=" & Speed & ";"
rst.Open QueryStr, cnn
Get_g_gtop = rst.Fields(0).Value
End If
End Function
After you open the recordset (Set rst = cmd.Execute) you will have to check whether it contains any data, before you try to access that data, for example:
if not rst.EOF then
'do your stuff with the data
end if
Reference on w3schools.com
The error you are receiving indicates that you are not geting any records from your SELECT-Statement.
Check it as suggested by HansUp.