SQL in VBA Function - excel

I have a VBA Function, and I want to add the following SQL, however being a newbie I don't know how to break the query in the code.
The query:
strSQL = "select (SELECT COUNT (DISTINCT CUSTOMER_ACCOUNT.ID) AS NUMBER_OF_ACCOUNTS_NOT_DELETED FROM CUSTOMER_ACCOUNT INNER JOIN
ACCOUNT ON CUSTOMER_ACCOUNT.ACCOUNT_ID=ACCOUNT.ID
WHERE
Convert(datetime,convert(char(10),[CUSTOMER_ACCOUNT].CREATED_ON,101))
BETWEEN '2009-01-01' AND '2009-12-31' AND CUSTOMER_ACCOUNT.DELETED!='1' AND ACCOUNT.DELETED !='1'
)
-
(SELECT COUNT (DISTINCT dLOAD_ACCOUNT_DETAIL.ACCOUNT_NUMBER) AS NOT_ACTIVE_ACCOUNTS
FROM dbo.LOAD_ACCOUNT_DETAIL LEFT OUTER JOIN
ACCOUNT ON dbo.LOAD_ACCOUNT_DETAIL_0.ID = dbo.ACCOUNT.ID WHERE
ACCOUNT_STATUS !='1') AS DIFFERENCE
buting the whole thing in quotes dont work...!

Depending on how you are running your query, you often have to break your query up into smaller chunks (less than ~200 characters, I forget exact amount).
This is done by breaking it into an array of strings:
Either:
QueryArry = Array("Your ","Query ","here ")
Using Marg's method this becomes:
QueryArry = Array("Your ", _
"Query ", _
"here ")
Or you can do it like this:
Dim QueryArry(0 to 100) as String
QueryArry(0)="Your "
QueryArry(1)="Query "
QueryArry(2)="Here "
WARNING: In every case make sure to add a space before the end of each quote... because these lines get appended together and without the extra space would be "YourQueryHere" Instead of "Your Query Here".
Dan

Dim myString As String
myString = "You can " & _
"use '& _' to concatenate " & _
"strings over multiple lines."

You can also break it up like this:
strSQL = "select ( "
strSQL = strSQL & "SELECT COUNT (DISTINCT CUSTOMER_ACCOUNT.ID) AS NUMBER_OF_ACCOUNTS_NOT_DELETED FROM CUSTOMER_ACCOUNT INNER JOIN "
strSQL = strSQL & "ACCOUNT ON CUSTOMER_ACCOUNT.ACCOUNT_ID=ACCOUNT.ID "
...
I prefer this way to the strSQL = "..." & _ "..." & _ "..." over multiple lines, but potato / potato...

Related

MSAccess 2007 Select Query RecordSet RecordCount from Excel 2007 VBA always returns 0 [duplicate]

Working in Access 2010 against an Access DB, I created a query in the QBE. As part of an overly complex quarterly reporting process, I now need to be able to execute that query with different parameters via VBA code. The SQL for the query is now embedded in my VBA module, and is modified on the fly, then executed. When run in the QBE, this particular instance of the query returns 400+ rows of data, but none are returned when executed in VBA via this code:
Dim Data As New ADODB.Recordset
Dim SQLString As String
SQLString = "SELECT PatientStatSchedDataDump.PtCompID, AppType.ProviderW, " & _
"PatientStatSchedDataDump.Date, PatientStatSchedDataDump.Status " & _
"FROM (AppType INNER JOIN PatientStatSchedDataDump ON AppType.AType = " & _
"PatientStatSchedDataDump.Type) LEFT JOIN GroupType ON AppType.Group = " & _
"GroupType.Group " & _
"WHERE (((PatientStatSchedDataDump.PtCompID) Like 'ClientName*' ) " & _
"AND ((PatientStatSchedDataDump.Date) BETWEEN #1/1/2014# AND #3/31/2014#) " & _
"AND ((GroupType.[Sort Order]) IN ('A', 'B', 'C', 'D', 'E')))"
Data.Open Source:=SQLString, ActiveConnection:=CurrentProject.Connection
If Not Data.EOF And Not Data.BOF Then
'the IF is never true - EOF & BOF are always True
NewSheet.Cells(InstCountRow + InstCount + 2, 1).CopyFromRecordset Data
End If
Data.Close
Set Data = Nothing
Again, if I create a new query in Access, paste the SQL code into the SQL window and run it, I get 400+ rows of results with this exact query
A query run from ADO requires ANSI wild cards: % instead of *; and _ instead of ?.
So change this ...
"WHERE (((PatientStatSchedDataDump.PtCompID) Like 'ClientName*' ) "
to this ...
"WHERE (((PatientStatSchedDataDump.PtCompID) Like 'ClientName%' ) "
If you want one query which works the same when run from ADO as it does when run in the QBE, you can use ALike instead of Like. With ALike, the db engine always expects ANSI wildcards.
"WHERE (((PatientStatSchedDataDump.PtCompID) ALike 'ClientName%' ) "

No value given for one or more required parameter error for VBA in Excel

I have a SQL data table which contains below data.
In this I need to get the "Component" data which are structured under "Item" and after that each component will be considered as "Item" and recursive CTE comes here. I have executed the below code for this, but I am facing with error. Please help me to sort this out.
revQueryString = "with ReqCTE as (" & _
"SELECT Item, Component, qtyper, 0 as lvl FROM STRUCT " & _
"where Item = ? " & _
"Union all " & _
"select Folders.Item, Folders.Component, Folders.qtyper, Child.lvl +1 from ReqCTE as Child " & _
"join STRUCT as Folders on Folders.Item = Child.Item); " & _
"select * from ReqCTE;"
Also I have attached the input and required Output for this task.
Input:
Required Output:

SQLClient Command Parameter Query String Length

I am connecting to a SQL Server and am trying to limit the results by adding parameters. The first parameter I added, #sdate, worked just fine. But, now I am trying to add a second parameter which is not working. I want the field, LP_EOC_DATA.PL, to only be returned if the length of the string is greater than 6 characters long. The code below executed, and like I say, the dates returned were correct, but it also returned values from LP_EOC_DATA.PL that had string lengths less than 6. Please let me know if you know how to get this to work. Thanks in advance.
Sub doSQL()
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim myReader As SqlDataReader
Dim sqlString As String = "SELECT LP_EOC_DATA.PL as PLs, LP_EOC_DATA.cDate as ReadDate, LP_EOC_LOV.LOCATION as Location " &
"FROM LP_EOC_DATA INNER JOIN LP_EOC_LOV ON LP_EOC_DATA.PIC = LP_EOC_LOV.PIC " &
"WHERE LP_EOC_DATA.cDate > (#sdate) AND LEN(LP_EOC_DATA.PL) > #slen1 " &
"UNION SELECT dbo.VT_DATA.PL as PLs, dbo.VT_DATA.cDate as ReadDate, dbo.VT_LOV.LOCATION as Location " &
"FROM dbo.VT_DATA INNER JOIN dbo.VT_LOV ON dbo.VT_DATA.PIC = dbo.VT_LOV.PIC " &
"WHERE dbo.VT_DATA.cDate > (#sdate) AND LEN(dbo.VT_DATA.PL) > #slen1 " &
"ORDER BY ReadDate;"
myConn = New SqlConnection("SERVER=ServerName;UID=uName;" &
"PWD=Password;")
myCmd = myConn.CreateCommand
myCmd.CommandText = sqlString
myCmd.Parameters.AddWithValue("#sdate", DateTimePicker1.Value)
myCmd.Parameters.AddWithValue("#slen1", 6)
'myCmd.Parameters.AddWithValue("#rx1", "'%[^0-9a-z]%'")
'myCmd.Parameters.AddWithValue("#rx2", " dbo.VT_DATA.PL NOT LIKE '%[^0-9a-z]%'")
myConn.Open()
myReader = myCmd.ExecuteReader()
Table.Load(myReader)
DataGridView1.Visible = True
DataGridView1.DataSource = Table
lblTotal.Text = Table.Rows.Count
End Sub
Also, as you can see, I am looking to add another parameter that only returns alphanumeric results from the same LP_EOC_DATA.PL field. I haven't got quite that far yet, but if you see something I'm doing wrong there too, I'd appreciate the input.
It helps if you format your SQL a little more. There's some structure, but it still comes off as a big wall of text. It's even harder for us to debug than it is for you, since we don't know your schema at all. There are also a number of other little things you should do different before we even address the question (Using block so connection is closed in case of exception, avoid AddWithValue() for index safety, isolate SQL from user interface, etc):
Function doSQL(StartDate As DateTime) As DataTable
Dim result As New DataTable
Dim sqlString As String = _
"SELECT LP_EOC_DATA.PL as PLs, LP_EOC_DATA.cDate as LPRReadDate, LP_EOC_LOV.LOCATION as Location " &
"FROM LP_EOC_DATA " &
"INNER JOIN LP_EOC_LOV ON LP_EOC_DATA.PIC = LP_EOC_LOV.PIC " &
"WHERE LP_EOC_DATA.cDate > #sdate AND LEN(COALESCE(LP_EOC_DATA.PL,'')) > #slen1 " &
"UNION " &
"SELECT dbo.VT_DATA.PL as PLs, dbo.VT_DATA.cDate as ReadDate, dbo.VT_LOV.LOCATION as LPRLocation " &
"FROM dbo.VT_DATA " &
"INNER JOIN dbo.VT_LOV ON dbo.VT_DATA.PIC = dbo.VT_LOV.PIC " &
"WHERE dbo.VT_DATA.cDate > #sdate AND LEN(COALESCE(dbo.VT_DATA.PL,'')) > #slen1 " &
"ORDER BY ReadDate;"
Using myConn As New SqlConnection("SERVER=ServerName;UID=uName;" &
"PWD=Password;"), _
myCmd As New SqlCommand(sqlString, myConn)
myCmd.Parameters.Add("#sdate", SqlDbType.DateTime).Value = StarDate
myCmd.Parameters.Add("#slen1", SqlDbType.Int).Value = 6
myConn.Open()
result.Load(myCmd.ExecuteReader())
End Using
Return result
End Function
And then call it like this:
Dim tbl As DataTable = doSql(DateTimePicker1.Value)
DataGridView1.Visible = True
DataGridView1.DataSource = tbl
lblTotal.Text = tbl.Rows.Count
As for the question, there are a few possibilities: NULL values can give unexpected results in this kind of situation (the code I posted already accounts for that). You may also have trouble with certain unicode whitespace padding your character count. Another possibility is char or nchar fields instead of varchar or nvarchar, though I don't think that's the issue here.
This is not an answer to the question per se but a reply to the request for an XML literal example. As that requires a few lines of code, I'd rather not put it in a comment.
Dim sql = <sql>
SELECT *
FROM MyTable
WHERE MyColumn = #MyColumn
</sql>
Dim command As New SqlCommand(sql.Value, connection)
Note that the element name can be anything you want but I usually use 'sql' when it's for SQL code.

errors importing CSV (delimited) into DAO database using vba and SQL from

I am stymied by an SQL mediated import of a CSV file using VBA code. I am using a Third EXCEL macro/spreadsheet, to analyze a LEFT JOIN of 2 files, one as an XLXS and the other as a CSV.
I suspect that part of the problem may be how the SQL command is used, for a FROM reference to an excel file. I am using Excel VBA, 2010, The 14 Database Access Engine.
I want to end with an SQL statement that pulls from an external comma delimited CSV file
I anticipate heading the macro with this pseudo code, in a stand-alone macro enabled excel file:
dbEngine = CreateObject(DAO.engine ... )
set DB = dbEngine.OpenDatabase(theNormalExternalExcellFile,....)
For the SQL statement, in pseudo-code, I want this:
SELECT fields
FROM [Table$] ' a normal external excel file
LEFT JOIN [an external CSV, comma delimited file]
ON...
GROUP...
I can successfully import an XLXS, or the CSV, independently, in a simple SQL statement, yet when I place the outside file references within an SQL's FROM clause, I get one of two errors, depending on how I play with the code: an Invalid File Path, or an error in the FROM Clause. The path is -not- invalid.
The error is shown, below, where it occurs, at the recordset instruction.
I also provide alternative SQL strings, which I had played with to test where in the code the error is generated.
'the Seating Chart
strPathSource = ThisWorkbook.Worksheets("Logic").Range("rngPathSource")
'strFileNameSource = ThisWorkbook.Worksheets("Logic").Range("rngFileNameSource")
'strFileNameSourceWOExt = Left(strFileNameSource, Len(strFileNameSource) - 4)
'the attendance
strPathAttendance = ThisWorkbook.Worksheets("Logic").Range("rngPathAttendance")
strFileNameAttendance = ThisWorkbook.Worksheets("Logic").Range("rngFileNameAttendance")
strFolderAttendance = ThisWorkbook.Worksheets("Logic").Range("rngFolderAttendance")
strFileNameAttendanceWOExt = Left(strFileNameAttendance, Len(strFileNameAttendance) - 4)
Set dbE = CreateObject("Dao.DBEngine.120")
Set db = dbe.OpenDatabase(strPathSource, True, False, "Excel 12.0;HDR=Yes")
''Set db = DAO.OpenDatabase(strFolderAttendance, True, False, "text;HDR=Yes;FMT=Delimited(,)")
'[Master$] is a tab on the spreadsheet at strPathSource
'[Attendance#csv]
' This reference to the table at strPathAttendance which otherwise works: [Attendance#csv]
' when not inside the FROM clause
strSQL = _
"SELECT tM.Job, Count(tA.Name) AS CountOfName" _
& " FROM [Master$] tM" _
& " LEFT JOIN" _
& " (SELECT * FROM [text;HDR=Yes;FMT=Delimited(,);Database='" _
& strPathAttendance & "'].[" & strFileNameAttendanceWOExt & "#csv]) tA" _
& " ON (tM.GivenName = tA.GivenName) AND (tM.SurName = tA.SurName)" _
& " GROUP BY tM.Job" _
& " ORDER BY tM.Job, Count(tA.Name)"
'Debug.Print strSQL
' This is the reported value for the string, strSQL, particularly the FROM clause:
' SELECT tM.Job, Count(tA.Name) AS CountOfName FROM [Master$] tM LEFT JOIN
' (SELECT * FROM
' [text;HDR=Yes;FMT=Delimited(,);Database=T:\Solutions Team Shared Folder\Seats -
' Attendance\Attendance.csv].[Attendance#csv]) tA
' ON (tM.GivenName = tA.GivenName) AND (tM.SurName = tA.SurName)
' GROUP BY tM.Job ORDER BY tM.Job, Count(tA.Name)
'' putting a single or double quote, around the database path, does not change the error
Set rstR = db.OpenRecordset(strSQL)
'Error:
' 'T:\...\...\Attendance.csv' is not a valid path. Make sure that
' the path name is spelled correctly and that you are connected to the server
' on which the file resides.
' ALT SQL strings, to test what's going on.
'strSQL = _
' "Select * FROM [Attendance#csv]"
'strSQL = _
' "Select * FROM (Select * FROM [Excel 12.0;HDR=Yes;Database=" & strPathSource & "].[Master$])"
'strSQL = _
' "SELECT * FROM [text;HDR=Yes;FMT=Delimited(,);Database=" _
' & strPathAttendance & "].[" & strFileNameAttendanceWOExt & "#csv]"
'strSQL = _
' "Select * FROM [Excel 12.0;HDR=Yes;Database=" & strPathSource & "].[Master$]"
When connected to text files with Jet/ACE SQL, the database parameter needs to reference the directory path not any specific text file. The period qualifier will then specify the individual file.
Therefore, simply remove the file name and extension from strPathAttendance (without quotes). So query should look like the below:
SELECT tM.Job, Count(tA.Name) AS CountOfName
FROM [Master$] tM
LEFT JOIN
(SELECT * FROM
[text;HDR=Yes;FMT=Delimited(,);Database=T:\Solutions Team Shared Folder\Seats -
Attendance].[Attendance#csv]) tA
ON (tM.GivenName = tA.GivenName) AND (tM.SurName = tA.SurName)
GROUP BY tM.Job
ORDER BY tM.Job, Count(tA.Name)

Help with function in string

I have a variable, emailBody, which is set to a string stored in a database. The email body is set to a string via a dlookup function.
emailBody = DLookup("emailBody", "listAdditions", "Id = " & itemType)
The string that email body is set to includes an IIf function (which includes a dlookup function). When
?emailBody is entered in the immediate window during runtime, it shows that emailBody is set to the following string:
The new commodity is" & Iif(dlookup("IsVague", "CommodityType", "Description= " & newItem)="1", "vague.", "not vague.")
However, I want the dlookup and IIf functions to be evaluated and their results stored in the string. How do I properly format the emailBody string ("the new commodity...") in my database so that the functions will be evaluated and the results stored in the emailBody variable?
Your question is a bit unclear, but if [Id] (Or [Description]) is a string, then you Dlookup must be like this:
emailBody = DLookup("emailBody", "listAdditions", "Id = '" & itemType & "'")
or
emailBody = DLookup("emailBody", "listAdditions", "Id = """ & itemType & """")
That is, your constant should be surrounded by quotes. You can either use ' (single quote) or "" (doubled double quote).
I am somewhat concerned about the value of newitem, but in general you can use Eval:
s = """The new commodity is"" & " _
& "Iif(dlookup(""IsVague"", ""CommodityType"", ""Description= "" & newItem)=""1"", ""vague."", ""not vague."")"
s2 = Eval(s)
I am not sure that this is the way to go, think about it.
So you have this exact string stored in a table field, and you want Access/VBA to evaluate it, correct?
"The new commodity is " & Iif(dlookup("IsVague", "CommodityType", "Description= " & newItem)="1", "vague.", "not vague.")
If so, try the Eval() command:
emailBody = Eval(DLookup("emailBody", "listAdditions", "Id = " & itemType))

Resources