I have this script below. I left out the connection details for security purposes but the code executes with out error in python and in MS SQL 2019
JavaScript
x
26
26
1
import pandas as pd
2
import pyodbc
3
4
5
sqlInsertScript = """
6
SELECT 'INSERT INTO dbo.table(' +
7
STUFF ((
8
SELECT ', [' + name + ']'
9
FROM syscolumns
10
WHERE id = OBJECT_ID('dbo.table') AND
11
name <> 'me'
12
FOR XML PATH('')), 1, 1, '') +
13
')
14
Select ' +
15
STUFF ((
16
SELECT ', [' + name + ']'
17
FROM syscolumns
18
WHERE id = OBJECT_ID('dbo.table') AND
19
name <> 'me'
20
FOR XML PATH('')), 1, 1, '') + '
21
From dbo.QueryPerformance
22
where EntryID > Number'
23
"""
24
25
insertquery = pd.read_sql_query(sqlInsertScript,cnxn1)
26
My issue is that this query returns 0 None in python. I need it to return the string I am creating because I intend to use that query going forward. I know the query works it returns correct text when run from MSSQL SSMS.
Advertisement
Answer
I used pyodbc instead of pandas and your code worked for me.
JavaScript
1
48
48
1
import pyodbc
2
import pandas as pd
3
def connectToDatabase():
4
'''
5
Connect to the SQL Server. Note the insecurity here
6
'''
7
try:
8
conn = pyodbc.connect('Driver={SQL Server};'
9
r'your server;'
10
'Database=your db;'
11
'uid=your uid;'
12
'pwd=your pw;')
13
except Exception as e:
14
print(e)
15
conn = None
16
return conn
17
def getQuery():
18
'''
19
The query we use to extract data from our SQL Server
20
'''
21
# This can't go wrong so we don't need error handling
22
query = """
23
SELECT 'INSERT INTO dbo.table(' +
24
STUFF ((
25
SELECT ', [' + name + ']'
26
FROM syscolumns
27
WHERE id = OBJECT_ID('dbo.table') AND
28
name <> 'me'
29
FOR XML PATH('')), 1, 1, '') +
30
')
31
Select ' +
32
STUFF ((
33
SELECT ', [' + name + ']'
34
FROM syscolumns
35
WHERE id = OBJECT_ID('dbo.table') AND
36
name <> 'me'
37
FOR XML PATH('')), 1, 1, '') + '
38
From dbo.QueryPerformance
39
where EntryID > Number'
40
"""
41
return query
42
conn = connectToDatabase()
43
cursor = conn.cursor()
44
# Submit a query to the SQL Server instance and store the results in the cursor object
45
cursor.execute(getQuery())
46
for row in cursor:
47
print(row)
48
The output:
JavaScript
1
2
1
('INSERT INTO dbo.table( [A], [B], [C]) nSelect [A], [B], [C] nFrom dbo.QueryPerformancenwhere EntryID > Number', )
2
Here is the table I cobbled for this test case:
JavaScript
1
13
13
1
SET ANSI_NULLS ON
2
GO
3
4
SET QUOTED_IDENTIFIER ON
5
GO
6
7
CREATE TABLE [dbo].[Table](
8
[A] [nchar](10) NULL,
9
[B] [real] NULL,
10
[C] [text] NULL
11
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
12
GO
13