4

I want the tables in SQL Server DB as a nice comma separated list. I have some code as below.

import pyodbc 
cnxn = pyodbc.connect('Trusted_Connection=yes', 
                     driver = '{ODBC Driver 13 for SQL Server}',
                     server = 'XXXXXX\SQLSERVER', 
                     database = 'AdventureWorks2016CTP3')
sql = "SELECT Distinct TABLE_NAME FROM information_schema.TABLES"

cursor = cnxn.cursor()
cursor.execute(sql)
print(cursor.fetchall())

I want the list to be like

['Address', 'AddressType',.....]

instead of

[('Address', ), ('AddressType', ), .....]

How to get this done.

Keerikkattu Chellappan

2 Answers2

1

Looks like the list is returned as a list of single element tuples. You could join them using join() and using the index for the first element for one long string or you could use list comprehension to return them as a single list.

val = [('Table1',),('Table2',),('Table3',)]
table_list = [x[0] for x in val]
table_string = ', '.join([x[0] for x in val])
dfundako
  • 8,022
  • 3
  • 18
  • 34
0

If join() isn't your thing, this is a good time for list comprehension:

table_list = [x[0] for x in val]

Which will return a list like you specified.

pythomatic
  • 647
  • 4
  • 13