我有一个存储过程,使用LIKE
运算符在其他一些参数中搜索卡车位置
@location nchar(20),
@time time,
@date date
AS
select
DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from
Vechile, DonationsTruck
where
Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+@location+'%') or (Location like '%'+@location) or (Location like @location+'%') ) or [Date]=@date or [Time] = @time)
我将其他参数归零并仅按位置搜索,但即使我使用了该位置的全名,它也始终没有返回结果
答案 0 :(得分:31)
@location nchar(20)
的数据类型应为@location nvarchar(20)
,因为nChar具有固定长度(填充空格)。
如果Location也是nchar,你将不得不转换它:
... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...
要使用和AND
条件启用可空参数,只需使用IsNull或Coalesce进行比较,这在使用OR
的示例中不需要。
e.g。如果您想比较位置和日期和时间。
@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))
答案 1 :(得分:2)
我正在努力。请查看以下声明。为我工作!!
SELECT * FROM [Schema].[Table] WHERE [Column] LIKE '%' + @Parameter + '%'
答案 2 :(得分:0)
...
WHERE ...
AND (@Location is null OR (Location like '%' + @Location + '%'))
AND (@Date is null OR (Date = @Date))
这样就更明显了,null 时不使用参数。
答案 3 :(得分:0)
不要将参数连接为字符串。这可以被用来执行 SQL 注入攻击。请参阅:https://docs.microsoft.com/en-us/archive/blogs/brian_swan/do-stored-procedures-protect-against-sql-injection
答案 4 :(得分:-4)
EG:比较村庄名称
ALTER PROCEDURE POSMAST
(@COLUMN_NAME VARCHAR(50))
AS
SELECT * FROM TABLE_NAME
WHERE
village_name LIKE + @VILLAGE_NAME + '%';