在Like语句中使用Stored Procedure变量

时间:2013-07-17 20:39:56

标签: sql sql-server-2008 variables stored-procedures sql-like

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

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

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

4 个答案:

答案 0 :(得分:4)

这对我有用:

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

Sql Fiddle DEMO

答案 1 :(得分:0)

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

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

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

set @id = isnull(@id, '')

答案 2 :(得分: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();

答案 3 :(得分: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