I am trying to convert an Access query to one that works in SQL server. The original query in Access works perfectly well (just terribly slow).
I only changed things slightly to make it compatible with SQL server instead of Access, like changing "NOW()" to "GETDATE()" and we can no longer divide aliases.
Running this query in SQL Server:
SELECT batches.[price-group],
[development].verifier,
Count([development].company) AS SENT,
Sum([order] *- 1) AS ORDS,
Count([development].company) / Sum([order] *- 1) AS PCT
FROM [development]
INNER JOIN batches
ON [development].batch = batches.batch
WHERE (( ( [development].[mail-date] ) < Getdate() - 50 ))
GROUP BY batches.[price-group],
[development].verifier
HAVING (( ( batches.[price-group] ) = 'pgb' ))
ORDER BY batches.[price-group],
[development].verifier,
Count([development].company) DESC;
Returns this error:
Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
Only real change, was like I said, in Access we could do this
[ords] / [sent] AS PCT
Any help will be appreciated, I'm not sure exactly why it isn't working! Removing the converted line above, does work in SQL server without any errors.
Thank you!
Use NULLIF():
Count([development].company) / NULLIF(Sum([order] * -1), 0) AS PCT
Related
I'm calling a SQL query with a BigQuery API with Airflow. This query works perfectly fine in the BigQuery workspace but says I'm writing FROM FROM even though I'm not...
The logs say line 4, character 20 is where the error occurs which corresponds to:
, EXTRACT(DATE FROM event_time) AS session_date.
My overall query structure looks something like:
SELECT * FROM
((SELECT
fields_here
FROM table_name
LEFT JOIN UNNEST(sub_table) AS s
WHERE 1=1
UNION ALL
(SELECT
fields_here
FROM table_name
LEFT JOIN UNNEST(sub_table) AS s
WHERE 1=1
ORDER BY 1, 2))
ORDER BY 1, 2
I'm also using the LEAD() window function and COALESCE() but not sure if that matters. Really confused why this error is occurring...
Issue was not adding use_legacy_sql=False argument in Airflow
Currently, I am trying to extract metadata from an OLAP cube in SQL Server (via a linked server) using this simple query:
select *
into [dbo].[columns_metadata]
from openquery([LINKED_SERVER], '
select *
from $System.TMSCHEMA_COLUMNS
')
But in the result set, there is a column named RefreshedTime with values 31.12.1699 00:00:00.
Because of this value, the query gives this error message:
Msg 8114, Level 16, State 9, Line 1 Error converting data type (null)
to datetime.
The problem is that I need to run the query without specifying the columns in the SELECT statement.
Do you know a trick to avoid this error?
I know you wanted not to have to mention the columns explicitly, but in case nobody can suggest a way to have it handle the 1699-12-31 dates, then you can fallback to this:
select *
into [dbo].[columns_metadata]
from openquery([LINKED_SERVER], '
SELECT [ID]
,[TableID]
,[ExplicitName]
,[InferredName]
,[ExplicitDataType]
,[InferredDataType]
,[DataCategory]
,[Description]
,[IsHidden]
,[State]
,[IsUnique]
,[IsKey]
,[IsNullable]
,[Alignment]
,[TableDetailPosition]
,[IsDefaultLabel]
,[IsDefaultImage]
,[SummarizeBy]
,[ColumnStorageID]
,[Type]
,[SourceColumn]
,[ColumnOriginID]
,[Expression]
,[FormatString]
,[IsAvailableInMDX]
,[SortByColumnID]
,[AttributeHierarchyID]
,[ModifiedTime]
,[StructureModifiedTime]
,CStr([RefreshedTime]) as [RefreshedTime]
,[SystemFlags]
,[KeepUniqueRows]
,[DisplayOrdinal]
,[ErrorMessage]
,[SourceProviderType]
,[DisplayFolder]
from $System.TMSCHEMA_COLUMNS
')
I am running a SQL query in stored procedure which is like following
SELECT
t1.id,t2.Name
FROM
table1 t1 , table2 t2 ,table2 t3,table4 t4
WHERE
t1.id=t3.t4.id
this query gets executed on SQL server 2008 when its compatible with SQL server 2000 but if we turn OFF the compatibility with SQL server 2000 then this Query gives syntax error which is expected.
Can some one help me to understand why this is happeneing ? thanks in advance
Original query:
SELECT
ConfigID , LocationDesc + '-' + LOBTeamDesc LocLOBTeamSource
FROM Config CONFIG , Location_LOBTeam LOCLOB , Location LOC , LOBTeam LOB, System SRC
WHERE CONFIG.LocationLOBTeamID = LOC.LOB.LocationLOBTeamID
AND CONFIG.SourceSystemID = SRC.SystemID
AND LOCLOB.LocationID = LOC.LocationID
AND LOCLOB.LOBTeamID = LOB.LOBTeamID
AND (GETDATE() BETWEEN CONFIG.effectiveDate AND CONFIG.EndDate
OR CONFIG.EndDate IS NULL)
ORDER BY
LOC.LocationCode
I think that original query, with current standard join syntax applied would be this:
SELECT
ConfigID
, LocationDesc + '-' + LOBTeamDesc LocLOBTeamSource
FROM Config CONFIG
INNER JOIN Location_LOBTeam LOCLOB
ON CONFIG.LocationLOBTeamID = LOCLOB.LocationLOBTeamID
INNER JOIN Location LOC
ON LOCLOB.LocationID = LOC.LocationID
INNER JOIN LOBTeam LOB
ON LOCLOB.LOBTeamID = LOB.LOBTeamID
INNER JOIN [System] SRC
ON CONFIG.SourceSystemID = SRC.SystemID
WHERE (GETDATE() BETWEEN CONFIG.effectiveDate AND CONFIG.EndDate
OR CONFIG.EndDate IS NULL)
ORDER BY
LOC.LocationCode
Perhaps this will help.
+EDIT
"System" as a table name, could that be a problem? Suggest you try it as [System]
+EDIT2
The original is given with this: LOC.LOB.LocationLOBTeamID but that appears to be an error as there is an alias LOCLOB
I think below post from msdn answers this issue Compatibility Levels and Stored Procedures
in the above post the point number 3 under section "Differences Between Compatibility Level 80 and Level 90" states "WHEN binding the column references in the ORDER BY list to the columns defined in the SELECT list, column ambiguities are ignored and column prefixes are sometimes ignored. This can cause the result set to return in an unexpected order."
on my database I am using compatibility level 80 i.e 2000 thats why it runs smoothly with the given syntax but when I remove this compatibility and make it to 100 i.e. 2008/R2 script gives syntax error which is expected
Today I wrote this bit of sql:
SELECT COUNT(T0021_werk_naam)
FROM (SELECT Distinct T0021_werk_naam,T0021_jaar,T0021_kwartiel
FROM T0021_offertes
WHERE T0021_status_code = 'G' AND T0021_jaar = 2013 AND (T0021_kwartiel = 3))
This sql runs great when I run it locally in access, however, when I run it through the code that has been used for ages for this and most certainly definetly is not the problem, and send it to SQL Express it gives an error that says there's a problem near ')'
After stripping away all the brackets possible it becomes clear that it detects there's a problem with the last ')' but I don't see the problem.
Any Ideas?
You need to give an alias for the select in the parenthesis:
SELECT COUNT(T0021_werk_naam)
FROM (
SELECT Distinct T0021_werk_naam,
T0021_jaar,
T0021_kwartiel
FROM T0021_offertes
WHERE T0021_status_code = 'G'
AND T0021_jaar = 2013
AND (T0021_kwartiel = 3)
) T
notice the T in the end after the last parenthesis.
I'm getting an annoying error in visual studio for SQL that executes fine.
SELECT InvoiceLines.LineID,
InvoiceLines.InvoiceID,
InvoiceLines.Text,
InvoiceLines.Rate,
InvoiceLines.Count,
InvoiceLines.Rate * InvoiceLines.Count AS LineTotal,
((InvoiceLines.Rate * InvoiceLines.Count) * (1 + Invoices.VatRate / 100)) * (1 - CAST(Invoices.Discount AS money) * InvoiceLines.ApplyDiscount / 100) AS LineTotalIncVat, InvoiceLines.ApplyDiscount
FROM InvoiceLines
LEFT JOIN Invoices ON Invoices.InvoiceID = InvoiceLines.InvoiceID
What LineTotalIncVat is trying to do is compute the total for the invoice item while adding the vat and subtracting the discount, and yes, probably better to do this in code (would if I could)
The error visual studio gives is:
There was an error parsing the query [token line number =1, token line offset =14, token in error = InvoiceLines]
Even though it will validate and execute without a problem in the query builder...
Try bracketing the table and column names, it may be having trouble parsing InvoiceLines.Count because Count is a reserved word. Try [InvoiceLines].[Count].
Solved
Deleted the table from the dataset and added it again with exactly the same SQL.
How strange... although not the first time I've had to do this.