I have a SQL Server procedure which runs in SQL Server Management Studio (SSMS) without any problem and every time it generates the same table.
I want to run the same procedure using python and pyodbc
. In order to do that I wrote a python function run_procedure(my_procedure)
which runs the procedure.
The problem is, every time I run the python function, I get a different result!
The procedure:
DROP PROCEDURE IF EXISTS procedure_create_tbl_date_range;
GO
CREATE PROCEDURE procedure_create_tbl_date_range
AS
DROP TABLE IF EXISTS tbl_date_range;
DECLARE @dateFrom date;
DECLARE @dateTo date;
SET @dateFrom = '2021-12-12';
SET @dateTo = '2022-12-12';
create table tbl_date_range (dates_ date);
WHILE(@dateFrom < @dateTo)
BEGIN
SELECT @dateFrom = DATEADD(day, 1,@dateFrom)
INSERT INTO tbl_date_range
SELECT @dateFrom
END;
GO
The python function:
import pyodbc
import pandas as pd
def run_procedure(my_procedure):
conn = pyodbc.connect('Driver={SQL Server};'
'Server=.\SQLEXPRESS;'
'Database=my_db;'
'Trusted_Connection=yes'
)
cur = conn.cursor()
try:
res = cur.execute(my_procedure)
conn.commit()
except Exception as e:
print(e)
finally:
cur.close()
del cur
conn.close()
Now almost each time I run the function below, the query SELECT max(dates_) as max_date_ FROM tbl_date_range
returns a different result!
run_procedure("EXEC procedure_create_tbl_date_range")
First try:
Second try:
Does anyone know, why the result is different?!