sql server中sql语句中单引号怎么转义?

时间:2021-12-23 00:41:31

sql server有两个转义符: 

' 默认情况下, '是字符串的边界符, 如果在字符串中包含', 则必须使用两个', 第1个'就是转义符 


另一个转义符是" 

当SET QUOTED_IDENTIFIER OFF时, "是字符串边界符, 字符串中的"必须用两个"表示。 

vb: "" <=> "
sql server 2000: ''' <=> '

eg:

declare @SearchType nvarchar(50)
declare @SearchString nvarchar(255)
declare @SearchKey nvarchar(50)
declare @SearchSql nvarchar(2000)

set @SearchType = '2'
set @SearchKey = 'd'

set @SearchString = CASE @SearchType 
                            when '1'  then '1 = 1'
                            when '2'  then  'p.ProjectName like ''' + '%'  +  @searchkey + '%'  + ''''
                            when '3'  then  'p.ProjectCity like ''' + '%'+ @searchkey + '%' +''''
                            when '4'  then  'c.CateName like '''  + '%' + @searchkey + '%' + ''''
                            when '4'  then  'p.ProjectManager like ''' + '%' + @searchkey + '%' +'''' 
                            END

set @SearchSql = N'

SELECT p.*,datename(year,ProjectPostTime)+ '   +  '''-''' + ' + datename(month,ProjectPostTime)+ '+ '''-''' + ' + datename(day,ProjectPostTime)' + ' as PostTime, m.EmpName,c.CateName FROM proProject As p ,mrBaseInf As m ,proCate c WHERE p.EmpID = m.EmpID and p.CateID = c.CateID  and '
 
 + @SearchString


print(@SearchSql)

exec(@SearchSql)