5

如何在查询中插入单引号?

例子

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

在每个CAST我需要放单引号之前。我怎样才能做到这一点 ?

4

5 回答 5

9

使用两个单引号:''

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 
于 2012-09-17T13:54:37.233 回答
2

使用双单引号''

如果要插入的实际数据中包含单引号,则命令通常会损坏。要解决此问题,只需将任何单引号替换为两个引号(不是双引号字符而是两个单引号字符)。

于 2012-09-17T13:56:45.800 回答
1
declare @var varchar(100)
select @var = 'txt'        
select char(39)+@var+char(39) -- with single quote
于 2016-01-15T09:37:23.980 回答
0
select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES 
        (''' + CAST(Endereco_Id as varchar) + ''','
    + ....
于 2012-09-17T13:55:26.767 回答
0

您必须'在字符串中使用两次:

declare @var varchar(100)
select @var = 'txt'        
select ' '+@var+' ' -- without single quote
select ''''+@var+'''' -- with single quote
于 2012-09-17T13:57:18.650 回答