2

我似乎无法使用存储过程中的变量正确使用 LIKE 语句。我想从表中找到以传递的变量开头的所有行。

我目前正在使用以下查询,其中@id传递给存储过程的值是nvarchar(20). 当 ID 完全匹配但没有正确使用'%'附加的时,这可以正常工作。完成此任务的正确方法是什么?

SELECT * FROM Table WHERE id LIKE @id + '%'
4

4 回答 4

4

这对我有用:

declare @id nvarchar(20)
select @id = '1'
SELECT * FROM tab WHERE id LIKE @id + '%'

Sql Fiddle 演示

于 2013-07-17T20:51:31.310 回答
0

@id如果为空,则查询不起作用。因此,如果为空,您可以将其设置为空字符串@id。请尝试以下方法:

begin 
    declare @id nvarchar(20)
    set @id = isnull(@id, '')
    select * from table where id like @id + '%'
end

因此,在您的过程中,添加以下行应该适用于您的查询:

set @id = isnull(@id, '')
于 2013-07-17T20:57:11.073 回答
0

简单的解决方案:

$search_q = '%' . $this_search_q. '%';

$stmt = $db->prepare("SELECT * FROM tbl_tablename WHERE tablecollumn LIKE :id");
$stmt ->bindParam(":id", $search_q );
$stmt->execute();

或者

$search_q = '%' . $this_search_q. '%';

$stmt = $db->prepare("SELECT * FROM tbl_tablename WHERE tablecollumn LIKE $search_q");
$stmt->execute();
于 2015-09-23T11:28:38.083 回答
0
CREATE PROCEDURE `SP_GENRE_SELECT`(
    IN _Id INTEGER,
      IN _Name VARCHAR(50),
      IN _account VARCHAR (50),
      IN _Password VARCHAR (50),
      IN _LastConnexionDate DATETIME,
      IN _CreatedDate DATETIME,
      IN _UpdatedDate DATETIME,
      IN _CreatedUserId INTEGER,
      IN _UpdatedUserId INTEGER,
      IN _Status TINYINT
    )
BEGIN
      SELECT *
      FROM user
      WHERE Id LIKE _id IS NULL + '%',CAST(_Id AS VARCHAR)
      AND
      WHERE Name LIKE _Name IS NULL + '%' ,'%',CONCAT('%',_Name,'%')
      AND
      WHERE Account  LIKE _Account IS NULL + '%' ,'%',CONCAT('%',_Account,'%')
      AND
      WHERE LastConnexionDate LIKE _LastConnexionDate IS NULL + '%' ,'%',CONCAT('%',CAST(LastConnexionDate AS VARCHAR(50),'%'))
      AND
      WHERE CreatedDate LIKE _CreatedDate IS NULL + '%' ,'%',CONCAT('%',CAST(_CreatedDate AS VARCHAR(50),'%'))
      AND
      WHERE UpdatedDate LIKE _UpdatedDate IS NULL + '%' ,'%',CONCAT('%',CAST(_UpdatedDate AS VARCHAR(50),'%'))
      AND
      WHERE CreatedUserID LIKE _CreatedUserID IS NULL +'%' ,'%',CONCAT('%',CAST(_CreatedUserID AS VARCHAR(50),'%'))
      AND
      WHERE UpdatedUserID LIKE _UpdatedUserID IS NULL +'%' ,'%',CONCAT('%',CAST(_UpdatedUserID AS VARCHAR(50),'%'))
      AND
      WHERE Status LIKE _Status IS NULL + '%' ,'%',CAST(_Status AS VARCHAR(50),'%');

END
于 2017-01-16T07:35:35.740 回答