Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single quote in a query

Tags:

sql

tsql

How can I insert an single quotes in a query ?

Example

select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES 
(' + CAST(Endereco_Id as varchar) + ','
+ CAST(Logradouro_Id as varchar) + ','
+ CAST(Bairro_Id as varchar) + ','
+ CAST (CEP as varchar) + ','
+ CAST(Logradouro as varchar) + ','
+ CAST(Livre as varchar) + ')'  as teste
FROM San_Endereco

Before each CAST I need put the single quote. How can I do that ?

like image 399
Lucas_Santos Avatar asked Sep 17 '12 13:09

Lucas_Santos


People also ask

How do I use single quotes in SQL query?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

How do I include a single quote in a SOQL query?

To handle single quotes or other reserved character in a SOQL query, we need to put a backslash in front of the character ( \ ).

When should single quotes be used when writing a query?

You do have to use single quotes when the column alias includes a space character, e.g., product id , but it's not recommended practice for a column alias to be more than one word. Double quotes are usually used to object names (e.g. column name "First name").


2 Answers

Use two single quotes: ''

select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES  
(''' + CAST(Endereco_Id as varchar) + ''',''' 
+ CAST(Logradouro_Id as varchar) + ''',''' 
+ CAST(Bairro_Id as varchar) + ''',''' 
+ CAST (CEP as varchar) + ''',''' 
+ CAST(Logradouro as varchar) + ''',''' 
+ CAST(Livre as varchar) + ''')'''  as teste 
FROM San_Endereco 
like image 145
Daniel Hilgarth Avatar answered Oct 27 '22 18:10

Daniel Hilgarth


Use double single quotes ''

If a single quote is contained in the actual data to be inserted, the command often becomes corrupted. To solve the problem, simply replace any single quote with two quotes (not the double quote character but two single-quote characters).

like image 22
Yacine Zine Avatar answered Oct 27 '22 20:10

Yacine Zine