When inserting text data that contains single quotes ('), it is important to escape them to prevent syntax errors. In SQL Server, this process is simple.
The solution to escaping single quotes is to double-write them. For example, to insert the text "hi, my name's tim" you would use the following SQL:
<code class="language-sql">INSERT INTO my_table VALUES ('hi, my name''s tim.');</code>
By doubling the single quote, SQL Server recognizes that the apostrophe is part of the data and not a string delimiter.
The following code demonstrates how to escape single quotes in a table with VARCHAR columns:
<code class="language-sql">DECLARE @my_table TABLE ( [value] VARCHAR(200) ) INSERT INTO @my_table VALUES ('hi, my name''s tim.') SELECT * FROM @my_table</code>
<code>value ================== hi, my name's tim.</code>
This confirms that the single quotes have been successfully escaped, allowing the text to be inserted correctly into the database.
The above is the detailed content of How to Escape Single Quotes in SQL Server INSERT Statements?. For more information, please follow other related articles on the PHP Chinese website!