为什么这个Where条件返回0行?

时间:2013-05-22 05:50:42

标签: sql sql-server sql-server-2008 tsql

SELECT
  *
FROM tblName
WHERE mode = '1' AND (category = @Category OR @Category = 'all' OR NewsId = @Category)

我通过了@ Category ='all'。这将返回0行。如果OR NewsId=@Category未添加此条件,则查询将返回所有结果

1 个答案:

答案 0 :(得分:1)

试试这个 -

   mode = '1' 
AND 
(
      @Category = 'all' 
    OR 
      @Category IN (category, CAST(NewsId AS VARCHAR(10)))
)

不要使用太大的数据类型长度(我的意思是MAX):

CREATE TABLE dbo.TBL_ContentsPage
(
      NewsId INT IDENTITY(1001,1) NOT NULL PRIMARY KEY
    , Header NVARCHAR(1024) NULL
    , SmallImage IMAGE NULL
    , TextContent NVARCHAR(2048) NULL
    , PostedDate DATETIME NOT NULL DEFAULT(GETDATE())
    , mode VARCHAR(50) NULL
    , [status] VARCHAR(50) NULL
    , category VARCHAR(200) NULL
    , author NVARCHAR(1024) NULL
    , imgRefID VARCHAR(50) NULL
)

ALTER PROCEDURE [dbo].[SPGetArticlePaging]
(
      @startposition INT
    , @stopposition INT
    , @Category VARCHAR(200)
)
AS BEGIN

    SELECT 
          NewsId
        , Header
        , TextContent
        , author
        , PostedDate
        , category
        , imgRefID 
    FROM (
        SELECT 
              NewsId
            , Header
            , TextContent
            , author
            , PostedDate
            , category
            , DateRank = ROW_NUMBER() OVER(ORDER BY PostedDate DESC) 
            , imgRefID 
        FROM dbo.TBL_ContentsPage 
        WHERE mode = '1' 
            AND 
            (
                  @Category = 'all' 
                OR 
                  @Category IN (category, CAST(NewsId AS VARCHAR(10)))
            )
    ) t
    WHERE DateRank BETWEEN @startposition AND @stopposition 

    RETURN 0

END