在SQL Server中传递“大于”或“小于”运算符作为参数

时间:2015-03-19 11:19:58

标签: sql-server

我想知道我可以将<>运算符作为SQL Server中的参数传递吗?我试图使用CASE语句,但收到错误。

我的查询如下:

Select TOP (@messagesNumber)
    * 
from 
    Messages 
Where  
    Case 
       When @action = 'received' Then Addressee 
       When @action = 'sended' Then Sender 
    END = @userId 
    And (CreateDatetime > @fromDate And CreateDateTime < @toDate) 
    And MessageId Case 
                     When @direction = '-1' Then < 
                     When @direction = '--1' Then > 
                  END @startingMessageId 
Order by 
    MessageId * @direction

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT TOP (@messagesNumber) * 
FROM Messages 
WHERE  
     CASE WHEN @action = 'received' THEN Addressee 
          WHEN @action = 'sended' THEN Sender END = @userId 
          AND (CreateDatetime > @fromDate AND CreateDateTime < @toDate) 
          AND ((MessageId < @startingMessageId AND @direction = '-1') OR (MessageId > @startingMessageId AND @direction = '--1')) 
ORDER BY MessageId * @direction

答案 1 :(得分:0)

您可以使用动态查询,例如:

DECLARE @direction = VARCHAR(1)
DECLARE @sql AS VARCHAR(8000)

SET @direction = '<'
SET @sql = 'SELECT * FROM Products WHERE Price ' + @direction + ' 100'

EXEC(@sql)

我的查询只是一个使用示例。