Sqlserver 模糊查询中文及在mybatis xml【非中文不匹配查询】N@P2问题

问题

sqlserver模糊查询或相等,两者都无法查询。

百度方案解释

Like 后的N是表示unicode字符。获取SQL Server数据库中Unicode类型的数据时,字符串常量必须以大写字母 N 开头,否则字符串将转换为数据库的默认代码页(字符集编码),这可能导致字符串内容发生变化,无法识别。
在SQL界面中

select * from table where column like N'%文档%'

但是在mybatis这样就不好写了。

注意点

一定不要使用mybatis的where标签,否则mybatis会识别为N@P2
N后面必须用 ‘’ + #{queryColumn} 这种格式

模糊查询

select * from table where 
<if test="queryColumn != null and queryColumn != ''">
	column like N'%'+#{queryColumn}+'%'
</if>

相等查询

结合上面,我们发现N后面不能直接拼接#{queryColumn}参数,否则就会报错!

select * from table where 
<if test="queryColumn != null and queryColumn != ''">
	column = N''+#{queryColumn}
</if>