今天在用SQL Server查询以prm_开头的表名时发现问题,查看一下是下划线没被转义,特此总结一下T-SQL字符转义
创建临时表,插入示例数据
1 CREATE TABLE #characters(ch VARCHAR(200)) 2 INSERT #characters VALUES('[入职时间]:2012-9-12') 3 INSERT #characters VALUES('prm_batch') 4 INSERT #characters VALUES('select PromiseTime as ''ptime''') 5 INSERT #characters VALUES('4 % 2= 0') 6 INSERT #characters VALUES('4 / 2= 2')
转义查询
1 -- 对于[],用/和ESCAPE转义 2 SELECT * FROM #characters WHERE ch LIKE '/[入职时间/]%' ESCAPE '/' 3 -- 对于_和%, 用[]括起来转义 4 SELECT * FROM #characters WHERE ch LIKE 'prm[_]%' 5 SELECT * FROM #characters WHERE ch LIKE '4 [%]%' 6 -- 对于单引号, 前加单引号转义 7 SELECT * FROM #characters WHERE ch LIKE 'select PromiseTime as ''%' 8 -- 对于/,不需要转义 9 SELECT * FROM #characters WHERE ch LIKE '4 /%'