23

我有一个存储过程,它使用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)

我将其他参数设为空并仅按位置搜索,但即使我使用位置的全名,它也始终不返回任何结果

4

7 回答 7

43

您的数据类型@location nchar(20)应该是@location nvarchar(20),因为 nChar 具有固定长度(用空格填充)。
如果 Location 也是 nchar 你将不得不转换它:

 ... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...   

要使用和AND条件启用可空参数,只需使用 IsNull 或 Coalesce 进行比较,在使用OR.

例如,如果您想比较位置和日期和时间。

@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))
于 2013-05-05T05:40:34.207 回答
6

我也在做同样的事情。检查以下声明。为我工作!!


SELECT * FROM [Schema].[Table] WHERE [Column] LIKE '%' + @Parameter + '%'
于 2018-02-17T06:22:09.577 回答
1

对于 mysql- SELECT * FROM tablename WHERE columnanme LIKE '%'+ @location+'%';

对于 oracle - SELECT * FROM tablename WHERE columnanme LIKE '%'|| @位置 ||'%';

于 2021-10-13T05:21:46.310 回答
-1
...
WHERE ...
      AND (@Location is null OR (Location like '%' + @Location + '%'))
      AND (@Date is null OR (Date = @Date))

这样更明显的是参数在 null 时不使用。

于 2021-02-04T12:00:03.930 回答
-1
CREATE PROCEDURE [dbo].[Sp_schemeallotment] (
    @SchemeName NVARCHAR (255) = ' ',
    @Ind INT = 0
)
AS
  BEGIN
      IF ( @Ind = 1 )
        BEGIN
            SELECT *
            FROM   schemeallotment
        END

      IF ( @Ind = 2 )
        BEGIN
            SELECT *
            FROM   schemeallotment
            WHERE  schemename LIKE '%' + @SchemeName + '%'
        END
  END

--exec sp_SchemeAllotment @Ind=2, @SchemeName='shree'
go 

像这样分配这些变量很重要:

(
    @SchemeName nvarchar (255) = ' ',
    @Ind int = 0
)
于 2021-10-05T10:55:02.733 回答
-1
   CREATE procedure [dbo].[sp_SchemeAllotment]
    (
    @SchemeName nvarchar (255)='',
    @Ind int=0
    )
    As 
    Begin
    if (@Ind = 1)
    begin
    SELECT * FROM SchemeAllotment
    End
    if (@Ind = 2)
    begin
    SELECT * FROM SchemeAllotment where SchemeName like '%'+ @SchemeName +'%'
    end
    End
    --exec sp_SchemeAllotment @Ind=2, @SchemeName='shree'
    GO
于 2021-10-05T09:51:35.423 回答
-5

EG : 与村名比较

ALTER PROCEDURE POSMAST
(@COLUMN_NAME VARCHAR(50))
AS
SELECT * FROM TABLE_NAME
WHERE 
village_name LIKE + @VILLAGE_NAME + '%';
于 2013-08-05T16:25:16.060 回答