Single quote in request

How can I insert 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 to put a single quote. How can i do this?

+4
source share
5 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 
+8
source

Use double single quotes. ''

If one quotation 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 quotation marks (not with the double quote character, but with two characters of the same quote).

+2
source
 declare @var varchar(100) select @var = 'txt' select char(39) +@var +char(39) -- with single quote 
+1
source
 select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES (''' + CAST(Endereco_Id as varchar) + ''',' + .... 
0
source

You should use ' in a line two times:

 declare @var varchar(100) select @var = 'txt' select ' ' +@var +' ' -- without single quote select '''' +@var +'''' -- with single quote 
0
source

Source: https://habr.com/ru/post/1434619/


All Articles