create table DDL to import + Databricks notebook

Vinodh247 40,031 Reputation points MVP Volunteer Moderator
2022-08-16T11:44:48.407+00:00

Why doesnt the following code work in my databricks notebook? I am getting error.

<console>:7: error: '(' expected but identifier found.
for db in dbs:
^
<console>:10: error: '(' expected but identifier found.
for t in tables:
^
<console>:12: error: identifier expected but integer literal found.
f.write(DDL.first()[0])
^
****Code is below****

dbs = spark.catalog.listDatabases()
for db in dbs:
f = open("testfile{}.ddl".format(db.name), "w")
tables = spark.catalog.listTables(db.name)
for t in tables:
DDL = spark.sql("SHOW CREATE TABLE {}.{}".format(db.name, t.name))
f.write(DDL.first()[0])
f.write("\n")
f.close()

https://learn.microsoft.com/en-us/azure/databricks/kb/metastore/create-table-ddl-for-metastore

Azure Databricks
Azure Databricks
An Apache Spark-based analytics platform optimized for Azure.
0 comments No comments
{count} votes

Answer accepted by question author
  1. ShaikMaheer-MSFT 38,556 Reputation points Microsoft Employee Moderator
    2022-08-17T13:55:16.767+00:00

    Hi @Vinodh247 ,

    Thank you for posting query in Microsoft Q&A Platform.

    I tried same code, its working perfectly fine for me. Please check below screenshot.

    I suspect you might have missed to have proper indentation, that means spaces before lines to differentiate code which is inside for loops. Kindly check below screenshot and use similar code and see if that helps.

    232023-image.png

    Code used:

    dbs = spark.catalog.listDatabases()  
    for db in dbs:  
      f = open("{}.ddl".format(db.name), "w")  
      tables = spark.catalog.listTables(db.name)  
      for t in tables:  
        DDL = spark.sql("SHOW CREATE TABLE {}.{}".format(db.name, t.name))  
        f.write(DDL.first()[0])  
        f.write("\n")  
    f.close()  
    

    Please check below video to understand about indentation in Python.
    Indentation in Python

    Hope this helps. Please let us know if any further queries.

    ------------

    Please consider hitting Accept Answer button. Accepted answers help community as well.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.