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

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.