Copying a query from SQL server to MS Acess - sql

I've written a query in SQL server that runs okay.
I need to run this query in Access as there is more data I need to pull into the query.
However when I copy the SQL into Access it doesn't work, I get a syntax error, Missing operator in query expression.
SELECT main.Tbl_ServiceOrder.ServiceOrder
, main.Tbl_Serviceorder.BusinessPartnerNumber
, main.Tbl_ServiceOrder.ExternalPointofDeliverynumber
, main.Tbl_ServiceOrder.ServiceProduct
, main.Tbl_ServiceOrder.SOCreatedOn
, main.Tbl_ServiceOrder.MainUserStatus
, main.Tbl_ServiceOrder.MainUserStatusDesc
, main.Tbl_ServiceOrder.ReasonCode
, main.Tbl_ServiceOrder.ReasonCodeDesc
, main.Tbl_ServiceOrder.SOActualFinishDate
, main.Tbl_ServiceOrder.BasicStartDate
,CAST(CASE WHEN reasoncode <> 'CMPL' THEN 'Pre Install'
WHEN reasoncode = 'CMPL' and SOActualFinishDate < (getdate()-182) THEN 'SMART BAU'
ELSE 'Post Install' END as Varchar) as SMRTPot
FROM main.Tbl_ServiceOrder
WHERE main.Tbl_ServiceOrder.ServiceProduct ='SMINSTALL'
OR main.Tbl_ServiceOrder.ServiceProduct ='SMEXCHANGE'
The WHEN on the first line of the CAST is highlighted by access as the error point.
What am i doing wrong?
I've tried changing the cast to the IIF below
, IIF (reasoncode <> 'CMPL','Pre Install',(IIF SOActualFinishDate < (getdate()-182),'SMART BAU','Post Install')) as SMRTPot
Above gives syntax error (comma) in query expression
IIF (reasoncode <> 'CMPL','Pre Install',(IIF SOActualFinishDate < (getdate()-182),'SMART BAU','Post Install')) as SMRTPot
above gives syntax error in query expression.
Okay so this is what I'm using now:
SELECT main.Tbl_ServiceOrder.ServiceOrder
, main.Tbl_Serviceorder.BusinessPartnerNumber
, main.Tbl_ServiceOrder.ExternalPointofDeliverynumber
, main.Tbl_ServiceOrder.ServiceProduct
, main.Tbl_ServiceOrder.SOCreatedOn
, main.Tbl_ServiceOrder.MainUserStatus
, main.Tbl_ServiceOrder.MainUserStatusDesc
, main.Tbl_ServiceOrder.ReasonCode
, main.Tbl_ServiceOrder.ReasonCodeDesc
, main.Tbl_ServiceOrder.SOActualFinishDate
, main.Tbl_ServiceOrder.BasicStartDate
,Switch(reasoncode <> 'CMPL', 'Pre Install',
reasoncode = 'CMPL' AND SOActualFinishDate < ( Getdate() - 182 ), 'SMART BAU',
True, 'Post Install') as SMRTPot
FROM main.Tbl_ServiceOrder
WHERE main.Tbl_ServiceOrder.ServiceProduct ='SMINSTALL' OR main.Tbl_ServiceOrder.ServiceProduct ='SMEXCHANGE'
Error message is now could not find file 'file path\main.mdb

Too many issues and too long for a comment.
You are using SQL Server syntax and not MS Access SQL syntax.
WHEN...CASE is not valid in MS ACcess SQL, you should use IIF or SWITCH instead
CAST is also not valid. You can convert to string using CStr
GetDate is also not valid, you should use DATE().
If you want to substract 182 days then you should do DATEADD('d', DATE() , -182)
But the most handy way to handle this is probably to make passthrough query that will be executed on SQL Server and not MS Access (thus not on linked tables), so you can keep your SQL Server syntax. Search that path.

Related

SQL Syntax Error(missing operator) Microsoft Access in Case Statement [duplicate]

This question already has an answer here:
Access warns that there is an operator error in the case clause in the query
(1 answer)
Closed 5 months ago.
I am working on a SQL query but cannot get started in the following case statement because I keep running into this error. The current query looks like this:
SELECT CoupaData.PO, CoupaData.Line, CoupaData.[Work Order #], CoupaData.Item, CoupaData.LineTotal,
CoupaData.Received, CoupaData.ApprovedInvoiced, CoupaData.[Line Status],
(CASE
WHEN CoupaData.LineTotal = CoupaData.Received THEN 'YES'
ELSE 'NO'
END) AS gg
FROM CoupaData;
Case statements aren't allowed in JET SQL. Try the inline if statement. You can nest these as well if you have multiple conditions.
SELECT
CoupaData.PO
, CoupaData.Line
, CoupaData.[Work Order #]
, CoupaData.Item
, CoupaData.LineTotal
, CoupaData.Received
, CoupaData.ApprovedInvoiced
, CoupaData.[Line Status]
, IIf(CoupaData.LineTotal = CoupaData.Received, 'YES', 'NO') AS gg
FROM CoupaData;

SQL Sub-query parameters from Excel

I have SQL query with a sub-query where I want to assign sub query parameters from a cell in an Excel sheet, as this query cant be represented graphically Excel keep throwing error on this:
[Microsoft][ODBC SQL Server Driver] Invalid paramter number and
[Microsoft][ODBC SQL Server Driver] Invalid Descriptor Index
I have already tried solution as mentioned here to trick excel without success Using Parameters in SQL query with sub-query
;WITH dataset_bl as (
SELECT
--rank() over (partition by date_of_AC, ac_room order by into_theatre) as OrderNumber
--,datetime_of_AC as booking_datetime
date_of_AC
,AC_room
,specialty
,OAMRN
,substring(Subject_NAME,1,CHARINDEX(' ',Subject_NAME,1)) as 'surname'
,substring(Subject_NAME,CHARINDEX(' ',Subject_NAME,1)+2,500) as 'forename'
,convert(date,[dttm_of_birth],103) as DOB
,PRIN_SO as 'surg'
,'"'+ASST_SO_1+' '+ASST_SO_2+'"' as 'assistant_SO'
,substring(CONSULT_NAME,1,abs(CHARINDEX(',',CONSULT_NAME,1)-1)) as 'consult_surname'
,substring(CONSULT_NAME,CHARINDEX(' ',CONSULT_NAME,1)+1,500) as 'consult_first_name'
,'"'+actual_AC+'"' as AC_details
,'"'+PLANNED_PROD+'"' as booked_details
,'Carried Out' as 'TT_outcome'
, 'NULL' as 'unP_return_flag'
,OP_type
--,LOS
,case when CL_PRIORITY ='' then 'Not listed' else 'isted' end as islisted
,CLI_PRIORITY as listed_priority
,case when EM_PRIORITY like '<=%' then 'Submitted' else 'No Greensheet' end as isGreensheet
,em_priority as a, case when EM_PRIORITY like '<=%' and em_priority <> '<=72hrsCannot charge before prod'then LEFT(EM_PRIORITY, abs(charindex('-',EM_PRIORITY)-1))
when em_priority = '<=72hrsCannot diso before prod' then '<=72hrs' else 'NULL' end as em_priority
FROM sample.dbo.tb_Fnl_Sur_th4 WITH (NOLOCK)
**WHERE main_ident = 'A224' and convert(date,into_Start, 103) >= '2019-07-01' and convert(date,into_Start, 103) <= '2019-07-31'** --i am trying to get these parameters from excel cell value
)
SELECT * FROM dataset_bl
WHERE specialty like 'abc%'
or (consult_surname like '%abc%' and consult_first_name like '%def%' )
or surg in ('cde,fghi',
'jkl,'mnop,
'qrs,Tuv')
order by convert(date,date_of_procedure,103), operating_room--, into_theatre
Here's some suggestion.
First is to check the formatting of your date columns.
and build your parameter to be like
Cast(into_Start as smalldatetime) between ? and ?
I've been on that same issue and seem to find the solution for me. In fact the parameter [?] use in MSQUERY in Excel will normally work when you have a direct Query
Ex:
Select [YourTable].[Column]
From [YourTable]
Where [YourTable].[Column]= ?
The Excel parameter will prompt and trigger where the windows that ask you which cell or Data you want that parameter have to be filled with.
In the other hand if you use the a Subquery and you add a Where condition with the Parameter ? will be stuck with the parameter [Microsoft][ODBC SQL Server Driver] Invalid paramter number and [Microsoft][ODBC SQL Server Driver] Invalid Descriptor Index
If you download the ODBC Driver for SQL Server here -->
https://www.microsoft.com/fr-fr/download/details.aspx?id=56567
Install it and make sure that the ODBC use for your MSQUERY in Excel use that connection.
ODBC Data Source to use
After this I was able to use a MSQuery in Excel using Parameter like this one
Select [RenamedTable].*
From (Select [YourTable].[Column1],
[YourTable].[Column2],
[YourTable].[Column3]
From [YourTable]) as RenamedTable
Where [RenamedTable].[Column1] between ? and ?
Hope this will work for you as for me because I had similar problem with between date Parameter

Extracting hour by using coalese in SQL on a timestamp

I am trying to update a query to extract the hour from a timestamp and I keep getting an error. The error I get is due to the FROM clause I was using.
SELECT
analytics_platform_data_type
, activity_date_pt
, activity_timestamp_pt
, analytics_platform_timestamp_utc
, analytics_platform_timestamp_utc_iso
--This is the clause that is causing the problem (Begin)
, extract(hour from coalesce(activity_timestamp_pt)) as latd_hour_pt
--Clause above is the issue; Line above is line 9 (End)
, analytics_platform_ platform
, ad_channel_name
, publisher_name
, ip_address
, analytics_platform_unique_activity_id
, click_id
, latd_custom_fields
FROM table_date_range([AllData_AnalyticsMobileData_], timestamp('2018-09-
25'), timestamp('2018-09-27'))
where 1=1
and analytics_platform_data_type = 'CLICK'
and partner_name = 'ABC123'
If I remove the extract hour piece the query works fine. When I add it I get the error: Encountered " "FROM" "from "" at line 9, column 16. Was expecting: ")" ...
I have seen the clause I am trying to use in the above query used before, but it was a much more complex query that was using sub queries. Really not sure what the issue is. (Using Google Big Query Legacy SQL)
Your query is mixing Legacy Syntax (table_date_range) with Standard Syntax (Extract)
If for some reason you need to stick with Legacy SQL - use HOUR() instead of EXTRACT()
But it is much recommended to migrate stuff to Standard SQL - where you should use wildcard functions instead of table_date_range
Something like
FROM `project.dataset.AllData_AnalyticsMobileData_*`
WHERE _TABLE_SUFFIX BETWEEN '2018-09-25' AND '2018-09-27'
see more at https://cloud.google.com/bigquery/docs/reference/standard-sql/migrating-from-legacy-sql#table_decorators_and_wildcard_functions in Migrating to Standard SQL doc

"Circular reference caused by ..." error in Access SQL (but not in T-SQL)

I have the following SQL statement which returns the desired result in SQL Server 2012:
SELECT
S.ONOMA
, S.DIEY
, S.POLH
, S.TK
, S.IDIOT
, S.KODIKOS
, S.AFM
FROM
SYNERG AS S
INNER JOIN
(SELECT
G.AFM, MIN(KODIKOS) AS KODIKOS
FROM SYNERG AS G
WHERE LEN(ISNULL(AFM, '')) != 0
GROUP BY AFM) AS I ON S.KODIKOS = I.KODIKOS
ORDER BY
S.AFM
but when I run the same SQL statement in MS Access 2007 I get an error:
Circular reference caused by 'KODIKOS' in query definition's SELECT list.
Any help would be appreciated.
As explained in the link by HansUp:
The alias of a calculated field cannot be identical to any of the field names used to calculate the field.
This can be rather annoying (esp. if it is a field that is returned by the query), but there is no way around it.
So you need to change the alias, e.g.:
SELECT
S.ONOMA
, S.DIEY
, S.POLH
, S.TK
, S.IDIOT
, S.KODIKOS
, S.AFM
FROM
SYNERG AS S
INNER JOIN
(SELECT
G.AFM, MIN(KODIKOS) AS MinKODIKOS
FROM SYNERG AS G
WHERE LEN(Nz(AFM, '')) <> 0
GROUP BY AFM) AS I ON S.KODIKOS = I.MinKODIKOS
ORDER BY
S.AFM
Note also that an IsNull() function exists in Access, but has a different meaning (it takes one argument and returns a Boolean). The corresponding function is Nz()
And (thanks #HansUp), the unequal operator is <>, not !=. I always use <> in SQL Server too, no need to make things more complicated than necessary. :)

SQL Developer: invalid identifier error

This is the part of my query that has error:
, case when dsi.distributor_id in
('ALBQA','ASGLA','ASGNY','ASGR1','ASGSF','BIKU9','COAUU','CSWHP','DPIB1','DPID9',
'DPISP','DPISQ','EAS3X','GEP79','GRG8V','NACY7','NOSYK','ORGK7','PETR1','TOP0U',
'UNFIA','UNFIL','UNFIQ','UNFIS','UNMQ9','KOSI8','KEHEN','CSNYC','ALBQA','ALC6Y','BAM7D','BIKU9','CLCE0','COAUU','CSWHT','EAS3X','FOUXU','GEP79',
'GRG8V','HED9Q','LAOJD','MCLFS','NOSYK','ORGK7','UNMQ9','OMAH1'
)
then 'Distributor'
else 'Direct'
end as is_direct
, SUM(dsi.cost) AS tot_cost
, SUM(CASE WHEN is_direct = 'Direct' THEN dsi.cost ELSE 0 END ) AS Direct_cost
It says that is_direct is an invalid column but I already indicated it above. Therefore, I was wondering if you could help me find where I went wrong.
Columns defined in your query cannot be used in other places in your query, whether it is in other columns, or WHERE clauses, etc.
I would suggest either placing these calculations into subqueries, or using WITH AS.