I have this query in Sqlserver that works fine:
select YEARWEEK_DATE as PERIODO ,banner as BANNER,ubicacion as UBICACION,branchid as BRANCHID ,marca as MARCA,
clase as CLASE,sum(unidades_vendidas) as UNIDADES_VENDIDAS,
sum(unidades_vendidas * PRECIO_COSTO_CON_DESCUENTO) as VENTA_COSTO_VALORIZADA,
sum(Venta_Neta) as VENTA_NETA ,sum(Stock) as STOCK,ROUND(sum(Stock_Valorizado),2) as VALORIZADO_STOCK,
ROUND(sum(Stock)/sum(NULLIF (unidades_vendidas,0)),1) as ROTACION_UNIDADES ,
ROUND(sum(Venta_Neta)/ sum(NULLIF (unidades_vendidas,0) * PRECIO_COSTO_CON_DESCUENTO)/1.21,5) as MARKUP
from dabra.dbo.bi_tablero_stock_articulo_reporte tablero
where YEARMONTH_DATE
like (select concat(CAST(year(GETDATE()) AS Varchar), right('0' + convert(varchar,datepart(mm,getdate())),2)))
and branchid <>401
and marca IS NOT NULL
group by marca,clase,branchid, banner, ubicacion, YEARWEEK_DATE
ORDER BY marca
when I try to get the same result via python I get this error message:
---------------------------------------------------------------------------
MSSQLDatabaseException Traceback (most recent call last)
src\pymssql\_pymssql.pyx in pymssql._pymssql.Cursor.fetchall()
src\pymssql\_pymssql.pyx in pymssql._pymssql.Cursor.getrow()
src\pymssql\_mssql.pyx in pymssql._mssql.MSSQLRowIterator.__next__()
src\pymssql\_mssql.pyx in pymssql._mssql.MSSQLConnection.fetch_next_row()
src\pymssql\_mssql.pyx in pymssql._mssql.check_cancel_and_raise()
src\pymssql\_mssql.pyx in pymssql._mssql.maybe_raise_MSSQLDatabaseException()
src\pymssql\_mssql.pyx in pymssql._mssql.raise_MSSQLDatabaseException()
MSSQLDatabaseException: (8134, b'Divide by zero error encountered.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')
During handling of the above exception, another exception occurred:
OperationalError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\sqlalchemy\engine\cursor.py in fetchall(self, result, dbapi_cursor)
976 try:
--> 977 rows = dbapi_cursor.fetchall()
978 result._soft_close()
src\pymssql\_pymssql.pyx in pymssql._pymssql.Cursor.fetchall()
OperationalError: (8134, b'Divide by zero error encountered.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')
The above exception was the direct cause of the following exception:
OperationalError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12868/3629759782.py in <module>
----> 1 DF = pd.read_sql_query(sqlFile,engine)
~\Anaconda3\lib\site-packages\pandas\io\sql.py in read_sql_query(sql, con, index_col, coerce_float, params, parse_dates, chunksize, dtype)
434 """
435 pandas_sql = pandasSQL_builder(con)
--> 436 return pandas_sql.read_query(
437 sql,
438 index_col=index_col,
~\Anaconda3\lib\site-packages\pandas\io\sql.py in read_query(self, sql, index_col, coerce_float, parse_dates, params, chunksize, dtype)
1591 )
1592 else:
-> 1593 data = result.fetchall()
1594 frame = _wrap_result(
1595 data,
~\Anaconda3\lib\site-packages\sqlalchemy\engine\result.py in fetchall(self)
990 """A synonym for the :meth:`_engine.Result.all` method."""
991
--> 992 return self._allrows()
993
994 def fetchone(self):
~\Anaconda3\lib\site-packages\sqlalchemy\engine\result.py in _allrows(self)
398 make_row = self._row_getter
399
--> 400 rows = self._fetchall_impl()
401 if make_row:
402 made_rows = [make_row(row) for row in rows]
~\Anaconda3\lib\site-packages\sqlalchemy\engine\cursor.py in _fetchall_impl(self)
1795
1796 def _fetchall_impl(self):
-> 1797 return self.cursor_strategy.fetchall(self, self.cursor)
1798
1799 def _fetchmany_impl(self, size=None):
~\Anaconda3\lib\site-packages\sqlalchemy\engine\cursor.py in fetchall(self, result, dbapi_cursor)
979 return rows
980 except BaseException as e:
--> 981 self.handle_exception(result, dbapi_cursor, e)
982
983
~\Anaconda3\lib\site-packages\sqlalchemy\engine\cursor.py in handle_exception(self, result, dbapi_cursor, err)
939
940 def handle_exception(self, result, dbapi_cursor, err):
--> 941 result.connection._handle_dbapi_exception(
942 err, None, None, dbapi_cursor, result.context
943 )
~\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py in _handle_dbapi_exception(self, e, statement, parameters, cursor, context)
1993 util.raise_(newraise, with_traceback=exc_info[2], from_=e)
1994 elif should_wrap:
-> 1995 util.raise_(
1996 sqlalchemy_exception, with_traceback=exc_info[2], from_=e
1997 )
~\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py in raise_(***failed resolving arguments***)
205
206 try:
--> 207 raise exception
208 finally:
209 # credit to
~\Anaconda3\lib\site-packages\sqlalchemy\engine\cursor.py in fetchall(self, result, dbapi_cursor)
975 def fetchall(self, result, dbapi_cursor):
976 try:
--> 977 rows = dbapi_cursor.fetchall()
978 result._soft_close()
979 return rows
src\pymssql\_pymssql.pyx in pymssql._pymssql.Cursor.fetchall()
OperationalError: (pymssql._pymssql.OperationalError) (8134, b'Divide by zero error encountered.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')
(Background on this error at: https://sqlalche.me/e/14/e3q8)
My script is as follows:
params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 11.0};"
"SERVER=xxx;"
"DATABASE=xxx;"
"UID=xxx;"
"PWD=xxx")
engine = create_engine('mssql+pymssql://xxx:xxx/xxx')
fd = open('RSCV_AÑO_MES (OK).sql', 'r')
sqlFile = fd.read()
fd.close()
DF = pd.read_sql_query(sqlFile,engine)
sql file has the same query that works fine in sqlserver...What am I doing wrong? the divided zero problem is alreay solved via NULLIF. I don´t understand...Thanks!