like '%字符串%' 在存储过程中需要使用 like"%'+@条件+'%"' 实现。即套双引号
CREATE PROCEDURE getCostServices
@companyid int,
@fld_name varchar(100),
@fld_PointPerUnit varchar(100),
@fld_Cycle varchar(100)
AS
declare @str nvarchar(1000)
declare @strCondition nvarchar(500)
begin
if @companyid=NULL
set @companyid=0
end
begin
if @fld_name=NULL
set @fld_name=''
end
begin
if @fld_PointPerUnit=NULL
set @fld_PointPerUnit=''
end
begin
if @fld_Cycle=NULL
set @fld_Cycle=''
end
set @strCondition=' where a. fld_Name like ''%'+@fld_name+'%'' and fld_PointPerUnit='+@fld_PointPerUnit+' and fld_Cycle='+@fld_Cycle
set @str='select existid=(case when a.fld_name=b.fld_srvname then 1 else 0 end), a.fld_name,a.fld_PointPerUnit,a.fld_Cycle,a.fld_Unit,a.fld_Remark,b.fld_cpyId from User_Crunode.T_ServiceInfo a left join User_Crunode.T_subsServ b on (a.fld_name=b.fld_srvName and b.fld_CpyId='+ltrim(str(@companyId))+') '+@strCondition
exec sp_executesql @str
GO
-------------
-当 SET QUOTED_IDENTIFIER 为 ON 时,标识符可以由双引号分隔,而文字必须由单引号分隔 --当 SET QUOTED_IDENTIFIER 为 OFF(默认值)时,表达式中的文字字符串可以由单引号或双引号分隔 SET QUOTED_IDENTIFIER ON --SELECT "1" --"为标识定界符,1理解为标识符,等价于 --SELECT [1] --即1为列名之类的数据库对象 /* 消息 207,级别 16,状态 1,第 2 行 列名 '1' 无效。 */ SELECT '1' --'为字串定界符,这里1为字串值 /* 1 */ SELECT "id" FROM xx --"为标识定界符 /* id 1 2 3 */ --等价于 SELECT [id] FROM xx /* id 1 2 3 */ SET QUOTED_IDENTIFIER OFF SELECT "1" --"用作字串定界符,这里1为字串值,等价于 /* 1 */ SELECT '1' /* 1 */ SELECT "id" FROM xx --因为在OFF状态下,"成为了字串定界符,因此这里不会选出id列,而会是常量字串,"id"是字串值 /* id id id 表xx里有三条记录*/
-----------
存储过程中 like '%%' 中单引号的问题
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)