i am using visual stdio 2008 and sql server 2005
dim selectquery = "SELECT Purchase_master.Customer_name, Purchase_details.Item_code, Item_Master.Name,
Purchase_details.Quantity, Purchase_details.Cost, Purchase_master.Date
FROM Item_Master INNER JOIN (Purchase_master INNER JOIN Purchase_details ON
Purchase_master.Bill_id = Purchase_details.Bill_id) ON Item_Master.Item_code = Purchase_details.Item_code
WHERE Purchase_master.Date= " + cboPDate.SelectedValue.ToString()
when this selectquery executed it gives me
error
"ERROR near syntax 12"
my cboPDate is a combobox binded with my database which return's data and time in
"2/18/2011 12:00:00 AM"
please help me out
You need to add quotes around your date.
Try
dim selectquery = "SELECT Purchase_master.Customer_name, Purchase_details.Item_code, Item_Master.Name,
Purchase_details.Quantity, Purchase_details.Cost, Purchase_master.Date
FROM Item_Master INNER JOIN (Purchase_master INNER JOIN Purchase_details ON
Purchase_master.Bill_id = Purchase_details.Bill_id) ON Item_Master.Item_code = Purchase_details.Item_code
WHERE Purchase_master.Date= '" + cboPDate.SelectedValue.ToString() +"'"
Better yet, use SQL parameters.
I suspect it is treating it as a delimiter.It would be better to change it to
WHERE Purchase_master.Date=#Your_date
And then add the date as a parameter, this would prevent SQL injection attacks and also promote plan caching
Try this:
dim selectquery = string.Format("SELECT Purchase_master.Customer_name, Purchase_details.Item_code, Item_Master.Name,
Purchase_details.Quantity, Purchase_details.Cost, Purchase_master.Date
FROM Item_Master INNER JOIN (Purchase_master INNER JOIN Purchase_details ON
Purchase_master.Bill_id = Purchase_details.Bill_id) ON Item_Master.Item_code = Purchase_details.Item_code
WHERE Purchase_master.Date= '{0}'", cboPDate.SelectedValue.ToString());
you have to add quots to the value. :)
Related
I build a query with this syntax:
SELECT e.codigo AS `Código`,
e.razao_social AS `Razão Social`,
e.grupo AS `Grupo`,
e.tributacao AS `Tributação`,
e.sistema AS `Sistema`,
r.nome AS `Responsável`,
date_format(t.competencia, '%m/%Y') AS `Competência`,
s.nome AS `Status`,
c.nome AS `Tipo Conferência`
FROM tarefa AS t
RIGHT JOIN empresa AS e ON t.id_empresa = e.id_empresa
LEFT JOIN responsavel AS r ON t.id_responsavel = r.id_responsavel
LEFT JOIN status AS s ON t.id_status = s.id_status
LEFT JOIN conferencia AS c ON t.id_conferencia = c.id_conferencia
WHERE c.nome = 'Encerramento Contábil'
ORDER BY `Competencia`;
I did a test query in MariaDB, and it worked.
Now, i am use this query in Access with VBA MSExcel, where it has the same structure and relationship between tables, but return error.
message error vba:
Syntax error (missing operator) in expression 't.id_empresa =
e.id_empresa LEFT JOIN responsavel AS r ON t.id_respons'
This is my code vba MSExcel:
Sub testSql()
'Creating objects of Connection and Recordset
Dim conn As New Connection, rec As New Recordset
Dim DBPATH, PRVD, connString, query As String
'Declaring fully qualified name of database. Change it with your database's location and name.
DBPATH = "C:\Users\ctb06\Documents\Database2.accdb"
'This is the connection provider. Remember this for your interview.
PRVD = "Microsoft.ace.OLEDB.12.0;"
'This is the connection string that you will require when opening the the connection.
connString = "Provider=" & PRVD & "Data Source=" & DBPATH
'opening the connection
conn.Open connString
'the query I want to run on the database.
query = "SELECT e.codigo AS `Código`, e.razao_social AS `Razão Social`, e.grupo AS `Grupo`, e.tributacao AS `Tributação`, e.sistema AS `Sistema`, r.nome AS `Responsável`, date_format(t.competencia, '%m/%Y') AS `Competência` FROM tarefa AS t RIGHT JOIN empresa AS e ON t.id_empresa = e.id_empresa LEFT JOIN responsavel AS r ON t.id_responsavel = r.id_responsavel;"
'running the query on the open connection. It will get all the data in the rec object.
rec.Open query, conn
'clearing the content of the cells
Range("a1").Select
Cells.ClearContents
If (rec.RecordCount <> 0) Then
col = 1
For Each resp In rec.Fields
With Cells(1, col)
.Value = resp.Name
End With
col = col + 1
Next resp
Cells(2, 1).CopyFromRecordset rec
End If
rec.Close
conn.Close
End Sub
Where am I missing?
No two SQL dialects are exactly the same for exact transferability. Simply, MariaDB's SQL will not perfectly align to MS Access' SQL similar to running same query from Oracle to Postgres, MySQL to SQL Server, Sybase to DB2... There will need to be some translation.
Specifically:
DATE_FORMAT is not an available function in MS Access. Instead use FORMAT with appropriate format pattern which does not use %.
More than one JOIN require parentheses wrapping in MS Access. However, your mix of RIGHT JOIN and LEFT JOIN may require nested joining.
(Admittedly, this is a frustrating requirement for new Access users to build complex queries with Query Designer and not SQL. I raised this suggested change among others to Access' SQL dialect.)
Fortunately, backticks are supported in MS Access though square brackets, [...], are the more popular form to escape identifiers with special characters or keywords.
Consider following adjustment:
SELECT e.codigo AS `Código`,
e.razao_social AS `Razão Social`,
e.grupo AS `Grupo`,
e.tributacao AS `Tributação`,
e.sistema AS `Sistema`,
r.nome AS `Responsável`,
FORMAT(t.competencia, 'mm/yyyy') AS `Competência`,
s.nome AS `Status`,
c.nome AS `Tipo Conferência`
FROM ((((empresa AS e
RIGHT JOIN tarefa AS t ON t.id_empresa = e.id_empresa)
LEFT JOIN responsavel AS r ON t.id_responsavel = r.id_responsavel)
LEFT JOIN status AS s ON t.id_status = s.id_status)
LEFT JOIN conferencia AS c ON t.id_conferencia = c.id_conferencia)
WHERE c.nome = 'Encerramento Contábil'
ORDER BY `Competencia`;
I'm having problems with my sql code, i'm trying to implement a current date to my comment but i can't figure out how + i'm having syntax errors and i don't know what to do anymore. Can someone help me with the date adding to comment?
UPDATE Osalus_projektis AS op
SET op.töötasu = op.töötasu + 100,
op.comment = CONCAT(NOW()'tõusis palk 100 eurot')
FROM Osalus_projektis
INNER JOIN Osaluse_liik AS ol
ON ol.osaluse_liik = op.osaluse_liik
WHERE ol.nimetus = 'nõustaja';
MS Access uses & for string concatenation. And it doesn't support a FROM clause. This may do what you want:
UPDATE Osalus_projektis AS op INNER JOIN
Osaluse_liik AS ol
ON ol.osaluse_liik = op.osaluse_liik
SET op.töötasu = op.töötasu + 100,
op.comment = NOW() & 'tõusis palk 100 eurot'
WHERE ol.nimetus = 'nõustaja';
If there is a problem with the JOIN -- which happens a lot in MS Access -- then you can use an EXISTS clause as well.
I'm a long time follower of Stack overflow but this is my first post. I'm hoping the community can help.
I have a successful Access Query that returns the required results - Perfect!
HOWEVER, I'm trying to return the same using OLEDB connection to the database within an ASP script. This is all legacy stuff however we are allowing web access to this legacy information.
MS Access (2016) shows Query as this... (works)
SELECT [EventName] & ": " & [RoundCaption] AS RoundTitle, ChunkEntryTable.WinPos
FROM ((EventTable INNER JOIN EventRoundTable ON EventTable.EventId = EventRoundTable.EventId) INNER JOIN ((RoundHeatTable INNER JOIN ChunkTable ON RoundHeatTable.RoundHeatId = ChunkTable.RoundHeatId) INNER JOIN (EventEntryTable INNER JOIN ChunkEntryTable ON EventEntryTable.EventEntryId = ChunkEntryTable.EventEntryId) ON ChunkTable.ChunkId = ChunkEntryTable.ChunkId) ON EventRoundTable.RoundKeyId = RoundHeatTable.RoundKeyId) LEFT JOIN EventEntryMemberTable ON EventEntryTable.EventEntryId = EventEntryMemberTable.EventEntryId
WHERE (((EventEntryTable.Entry1Id)=[EntryId])) OR (((EventEntryTable.Entry2Id)=[EntryId])) OR (((EventEntryTable.Entry3Id)=[EntryId])) OR (((EventEntryMemberTable.MemberId)=[EntryId]))
ORDER BY EventTable.SortIdx, EventRoundTable.RoundId DESC , EventRoundTable.IsRepechage DESC;
Doing this in OLEDB. Connection string as follows...
<%
' FileName="Connection_ado_conn_string.htm"
' Type="ADO"
' DesigntimeType="ADO"
' HTTP="true"
' Catalog=""
' Schema=""
Dim MM_csresultdb_STRING
MM_csresultdb_STRING = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=xyz.mde;Jet OLEDB:Database Password=xxxxxxxxx;"
%>
Connection works perfectly but I can't seem to get the SQL command to work. I get "No value given for one or more required parameters".
NOTE: I have replaced [EntryID] in 4 places with a valid value and it works perfectly in Access just not outside of Access using OLEDB. Here's what the SQL is I'm using...
SELECT EventTable.EventName & ": " & EventRoundTable.RoundCaption AS RoundTitle, ChunkEntryTable.WinPos FROM
((EventTable INNER JOIN EventRoundTable ON EventTable.EventId = EventRoundTable.EventId) INNER JOIN
((RoundHeatTable INNER JOIN ChunkTable ON RoundHeatTable.RoundHeatId = ChunkTable.RoundHeatId) INNER JOIN
(EventEntryTable INNER JOIN ChunkEntryTable ON EventEntryTable.EventEntryId = ChunkEntryTable.EventEntryId) ON ChunkTable.ChunkId = ChunkEntryTable.ChunkId) ON ChunkTable.ChunkId = ChunkEntryTable.ChunkId)
ON EventRoundTable.RoundKeyId = RoundHeatTable.RoundKeyId)
WHERE ((EventEntryTable.Entry1Id)=4741) OR ((EventEntryTable.Entry2Id)=4741) OR ((EventEntryTable.Entry3Id)=4741)
ORDER BY EventTable.SortIdx, EventRoundTable.RoundId DESC , EventRoundTable.IsRepechage DESC;
FOUND PROBLEM ** See answer below
FOUND PROBLEM ** It's to do with this part of the SQL...
[EventName] & ": " & [RoundCaption] AS RoundTitle
Changed to
[EventName], [RoundCaption] AS RoundTitle
and it works but gives me two separate fields rather than the one concatenated field called "RoundTitle". So I'll join the two result fields during the display output rather than at the query stage.
Whew! That many days to figure out. Thanks to the comments that kinda steered me in that direction of the AS part of the statement.
I have a form named FietsAantDagen, a query named QueryFietsAantDagen and a textbox named Txtinput. I am trying to use a pass-through query to SQL Server and use a text form's input as a input in my query.
Query:
SELECT
Fiets_id,
Fiets_Type,
SUM(DATEDIFF(DAY, Huurovereenkomst_Begin_datum, Huurovereenkomst_Eind_datum)) AS AantalDagen
FROM
Fiets
INNER JOIN
HuurovereenkomstFiets
ON HuurovereenkomstFiets_Fiets_id = Fiets_id
INNER JOIN
Huurovereenkomst
ON Huurovereenkomst_id = HuurovereenkomstFiets_Huurovereenkomst_id
WHERE
YEAR(Huurovereenkomst_Begin_datum) = [Forms]![FietsAantDagen]![Txtinput]
AND YEAR(Huurovereenkomst_Eind_datum) = [Forms]![FietsAantDagen]![Txtinput]
GROUP BY
Fiets_id,
Fiets_Type
While running this query as a pass-through query I get the following error:
ODBC: Runtime error [Microsoft][SQL Server Native Client 11.0][SQL
Server]Incorrect syntax near the keyword 'WHERE'/ (#156)
Is the problem that I am using an Access text form value in a pass-through query, if so what can I do to solve it?
I read in another Overflow question you needed to add (), which I did and now I get the error:
JOIN-expression is not supported.
I'm going crazy...
If you don’t have direct use of SQL server, then likely best to create two pass though queries.
Query #1 – this is your raw SQL as you have
Eg:
SELECT
Fiets_id,
Fiets_Type,
SUM(DATEDIFF(DAY, Huurovereenkomst_Begin_datum,
Huurovereenkomst_Eind_datum)) AS AantalDagen
FROM
Fiets
INNER JOIN
HuurovereenkomstFiets
ON HuurovereenkomstFiets_Fiets_id = Fiets_id
INNER JOIN
Huurovereenkomst
ON Huurovereenkomst_id = HuurovereenkomstFiets_Huurovereenkomst_id
WHERE
YEAR(Huurovereenkomst_Begin_datum) = [StartYear]
AND YEAR(Huurovereenkomst_Eind_datum) = [EndYear]
GROUP BY
Fiets_id,
Fiets_Type
Query #2 – this is an application wide query you make that you can re-use over and over for any raw t-SQL (SQL server pass though). You then in code go like this:
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = CurrentDb.QueryDefs("MyQ1").SQL
srtSQL = Replace(strSQL, "[YearStart]", [Forms]![FietsAantDagen]![Txtinput])
strSQL = Replace(strSQL, "[YearEnd]", [Forms]![FietsAantDagen]![Txtinput])
With CurrentDb.QueryDefs("qryPassR")
.SQL = strSQL
.ReturnsRecords = True
Set rst = .OpenRecordset
End With
However, if you have the ability to use SQL server, and create a proc, then I would suggest you create store procedure like this:
CREATE PROCEDURE SelectDates
#StartYear int,
#EndYear int
AS
BEGIN
SET NOCOUNT ON;
SELECT
Fiets_id,
Fiets_Type,
SUM(DATEDIFF(DAY, Huurovereenkomst_Begin_datum, Huurovereenkomst_Eind_datum)) AS AantalDagen
FROM
Fiets
INNER JOIN
HuurovereenkomstFiets
ON HuurovereenkomstFiets_Fiets_id = Fiets_id
INNER JOIN
Huurovereenkomst
ON Huurovereenkomst_id = HuurovereenkomstFiets_Huurovereenkomst_id
WHERE
YEAR(Huurovereenkomst_Begin_datum) = #StartYear
AND YEAR(Huurovereenkomst_Eind_datum) = #EndYear
GROUP BY
Fiets_id,
Fiets_Type
END
Then in access, you use this:
Dim rst As DAO.Recordset
With CurrentDb.QueryDefs("qryPassR")
.SQL = "exec SelectDates " & [Forms]![FietsAantDagen]![Txtinput] & "," & _
[Forms]![FietsAantDagen]![Txtinput]
.ReturnsRecords = True
Set rst = .OpenRecordset
End With
So by passing parameters you reduce most of issues in regards to SQL injection.
Of course if you can’t create store procs, or don’t have permissions, then you have to adopt the first idea above. You can also of course in the first suggestion insert the raw SQL into the code editor, but I find using up an extra query to “just” hold the raw SQL, and then modifying the SQL into the 2nd pass-through query eliminates the need for messy SQL in the VBA code editor.
When you run a Pass-Through query, its SQL text gets sent to the DB server as-is, nothing is evaluated. So including [Forms]![FietsAantDagen]![Txtinput] in a Pass-Through query will never work.
You're on the right track with
SELECT * FROM fnFietsAantDagenPerJaar([Forms]![FietsAantDagen]![Txtinput])
but you need to supply the parameter yourself, because (see above).
So you need to build the Pass-Through SQL, e.g. with this VBA procedure:
Private Sub txtInput_AfterUpdate()
Dim QD As DAO.QueryDef
Dim lYear As Long
' Make sure we pass a number to the SQL Server function
lYear = Val(Me!txtInput)
If lYear > 0 Then
Set QD = CurrentDb.QueryDefs("QueryFietsAantDagen")
QD.SQL = "SELECT * FROM fnFietsAantDagenPerJaar(" & lYear & ")"
Set QD = Nothing
' After changing the query SQL, requery the form
' This assumes that your form is bound to Pass-Through query QueryFietsAantDagen
Me.Requery
End If
End Sub
Pass-through queries run exclusively on the connected, external database engine, here being SQL Server, and does not see anything in MS Access, only everything in that external environment.
Consider adjusting pass-through query to avoid any MS Access evaluations and add year groupings to aggregate query. Then query this resultset in a local Access query filtering for needed year conditions using form values. Below adds table aliases for clarity (adjust if not correct).
Pass-Through (no WHERE clause, but extended SELECT and GROUP BY)
SELECT
f.Fiets_id,
f.Fiets_Type,
YEAR(h.Huurovereenkomst_Begin_datum) As BeginYear,
YEAR(h.Huurovereenkomst_Eind_datum) As EndYear,
SUM(DATEDIFF('d', h.Huurovereenkomst_Begin_datum,
h.Huurovereenkomst_Eind_datum)) AS AantalDagen
FROM
HuurovereenkomstFiets_LinkTable hf
INNER JOIN
Fiets_LinkTable f
ON hf.HuurovereenkomstFiets_Fiets_id = f.Fiets_id
INNER JOIN
Huurovereenkomst_LinkTable h
ON h.Huurovereenkomst_id = hf.HuurovereenkomstFiets_Huurovereenkomst_id
GROUP BY
f.Fiets_id,
f.Fiets_Type,
YEAR(h.Huurovereenkomst_Begin_datum),
YEAR(h.Huurovereenkomst_Eind_datum)
Local Query
SELECT
t.Fiets_id,
t.Fiets_Type,
t.AantalDagen
FROM
myPassThroughQuery t
WHERE t.BeginYear = [Forms]![FietsAantDagen]![Txtinput]
AND t.EndYear = [Forms]![FietsAantDagen]![Txtinput]
Alternatively, consider using linked tables from SQL Server (with same ODBC connection as pass-through) where Access can treat them as local tables. Hence, you can run your query using form date values. Do note you will have to convert syntax to adhere to Access' SQL dialect like DATEDIFF and JOIN parentheses. Performance may differ due to changed engines but test.
Linked Tables Local Query
SELECT
f.Fiets_id,
f.Fiets_Type,
SUM(DATEDIFF('d', h.Huurovereenkomst_Begin_datum,
h.Huurovereenkomst_Eind_datum)) AS AantalDagen
FROM
(HuurovereenkomstFiets_LinkTable hf
INNER JOIN
Fiets_LinkTable f
ON hf.HuurovereenkomstFiets_Fiets_id = f.Fiets_id)
INNER JOIN
Huurovereenkomst_LinkTable h
ON h.Huurovereenkomst_id = hf.HuurovereenkomstFiets_Huurovereenkomst_id
WHERE YEAR(h.Huurovereenkomst_Begin_datum) = [Forms]![FietsAantDagen]![Txtinput]
AND YEAR(h.Huurovereenkomst_Eind_datum) = [Forms]![FietsAantDagen]![Txtinput]
GROUP BY
f.Fiets_id,
f.Fiets_Type
To create linked tables automatically, use DoCmd.TransferDatabase. Otherwise, use the External Data / ODBC Database icon on ribbon and walk through setup wizard.
DoCmd.TransferDatabase acLink, "ODBC Database", _
"ODBC;DRIVER={SQL Server};Server=<ServerAddress>;Database=<DBname>;Trusted_Connection=Yes;", _
acTable, "HuurovereenkomstFiets", "HuurovereenkomstFiets_LinkedTable"
I've got a date variable that looks like this:
Dim LogDate As Date = Date.Today.AddDays(-1)
the format comes out like: #4/5/2010#
then it goes into a SQL select query as a WHERE clause. When I debug, the query has changed this to '05/04/2010'. I want it to be in the format '04/05/2010' like it is when declared. Any ideas on how I do this?
Hee is the query:
Dim sqlCmd As New SqlCommand("SELECT TOP (100) PERCENT tblBackup.BackupName,
tblBackupArchive.BackupDate, tblStatus.Status FROM tblStatus INNER JOIN tblBackupArchive ON
tblStatus.StatusID = tblBackupArchive.StatusID INNER JOIN tblBackup ON tblBackupArchive.BackupID =
tblBackup.BackupID INNER JOIN tblClient ON tblBackup.ClientID = tblClient.ClientID WHERE tblBackupArchive.BackupDate = '" & LogDate & "' AND (tblBackupArchive.StatusID = 3) ORDER BY
tblBackupArchive.BackupDate DESC", connection)
-- Jonesy
The best way would be to use a SQLCommand object with a suitable named parameter in the where clause - this would make the formatting of the textual representation of the date totally beside the point...
Another approach, if you're using MS-SQL, would be to use a date in the following format:
Where date = '20100504'
Be careful when using dates though - remember that behind the scenes they are DateTimes...
Martin.