I have an SQL query that generates the DDL to create tables based on the existing schema. I am running this to copy the schema to another database for backup purposes. I do not have permission to do it the normal way in SQL Server, so I'm using this other way.
Here is the DDL text that my query should return (and I have verified that the query returns in SSMS); it is only one row (and column) with the header name "DDL":
SET NOCOUNT OFF;
IF OBJECT_ID('[<schema_name>].[<table_name>]','SN') IS NOT NULL DROP SYNONYM [<schema_name>].[<table_name>];
IF OBJECT_ID('[<schema_name>].[<table_name>]','U') IS NOT NULL DROP TABLE [<schema_name>].[<table_name>];
RAISERROR('CREATE TABLE %s',10,1, '[<schema_name>].[<table_name>]') WITH NOWAIT;
CREATE TABLE [<schema_name>].[<table_name>] (
... column definitions ...
)
RAISERROR('CREATING INDEXES OF %s',10,1, '[<schema_name>].[<table_name>]') WITH NOWAIT;
However, sqlachemy only returns the last line:
RAISERROR('CREATING INDEXES OF %s',10,1, '[<schema_name>].[<table_name>]') WITH NOWAIT;
And here's the python code around where this is pulled:
def get_create_ddls(table_name_list: list, conn) -> list:
fd = open('CreateCreateDDL.sql', 'r')
original_query = fd.read()
fd.close()
return_list = []
for name in table_name_list:
# prefixed the views as "V_"
isView = name[:2] == "V_"
if isView:
tbl_insert_str = "('" + name[2:] + "')"
else:
tbl_insert_str = "('" + name + "')"
query = original_query.replace("<INSERT_TABLE_NAME_HERE>", tbl_insert_str, 1)
result = conn.execute(sqlalchemy.text(query))
# TODO: Only reading last line of the row
value_str = ""
for row in result:
temp_value = row.DDL
value_str += temp_value
print(value_str)
if isView:
# put the "V_" back into the CREATE statement
view_name = name[2:(name.find("].[") + 3)] + "V_" + name[(name.find("].[") + 3):]
value_str = value_str.replace(name[2:], view_name)
return_list.append(value_str)
return return_list
How can I fix this without going in and manually removing every carriage return from the source query? There are a lot of them.
1条答案
按热度按时间mm5n2pyu1#
I'm going to leave the question up because I think a general answer would be more suitable (i.e. a solution for queries that return cells with text that have carriage returns in them), but in the script that was generating this DDL, the script defines the carriage return like below:
and then uses
@CR
for carriage returns the rest of the script. So, the solution was just to use a different delimiter:Kudos to ildanny and devart for the script that generates the DDL mentioned above.