Search code examples
sql-serverpyodbcquotation-marks

sql server unclosed quotation mark because insert a string with 's


I am trying to write extended properties to each column of a table from python. Here is my code:

for i in dat.columns:
    sql_query = """\
                EXEC sys.sp_addextendedproperty
                     @name = N'Description',
                     @value = N'{}',
                     @level0type = N'Schema', @level0name = '{}',
                     @level1type = N'Table',  @level1name = '{}',
                     @level2type = N'Column', @level2name = '{}'
                """.format(dat[i][0], db, tb, i)

Here dat[i][0] contains the description for each column. However, one of the description is like balabalabala...student's program...balabalabal, where there is a single ' in the description and it cause an error.

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 's'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Unclosed quotation mark after the character string '\n                    '. (105)")

How to handle this problem?

Thank you!


Solution

  • Whenever inserting a string that contains a single-quote character in SQL Server, use two consecutive single quotes. In your case, the description would be:

    'Balabalabalabala... student''s program, balabalabala.'