首页 > 解决方案 > 如何以字符串格式编写 SQL 命令

问题描述

如何转换此代码:

SELECT * FROM DB
WHERE field LIKE N'%'+RTRIM(LTRIM('98'))+N'%'

至:

SET @stringWhere= ' SELECT * FROM DB AND field LIKE '+N'%' +RTRIM(LTRIM(@field))+ N'%';

标签: sqlsql-server

解决方案


这里有点猜测。请输入下面的代码。并确保您查看代码中的注释,因为有几件事可以改进。

declare @field nvarchar(10) = N'98'

select * --don't use *, select ONLY the columns you need
from DB
where Name like '%' + @field+ '%' --be careful here, this is a nonSARGable predicate with the leading wildcard. As such all indexes will be rendered useless.

推荐阅读