0

我正在使用 SQL Server 2008。

SELECT resultTable.OrderNumber,
                resultTable.ProjectId,
                resultTable.BatchId,
                resultTable.CustomerId,
                resultTable.City,
                resultTable.Street,
                resultTable.PostalCode,
                resultTable.Country,
                resultTable.CreatedDate,
                resultTable.Name,
                COUNT(*) OVER() as OrdersCount,
                Row_Number() OVER 
                  (ORDER BY
                    CASE WHEN @sortBy = 'OrderNumber'
                    THEN resultTable.OrderNumber END,
                    CASE WHEN @sortBy = 'ProjectId'
                    THEN resultTable.ProjectId END,
                    CASE WHEN @sortBy = 'Address'
                    THEN resultTable.Country, resultTable.City, resultTable.Street, resultTable.PostalCode END,
                    CASE WHEN @sortBy = 'CreatedDate'
                    THEN resultTable.CreatedDate END) as RowIndex
FROM resultTable

此查询在“,”附近触发语法错误

THEN resultTable.Country, resultTable.City, resultTable.Street, resultTable.PostalCode END,

如果我删除第一个“,”之后的列,一切正常,但我试图按地址排序,它由 4 列组成。可能我在这里看不到容易的东西。

PS:@sortBy只是一个字符串参数。

4

3 回答 3

3

你可能想要

 CASE WHEN @sortBy = 'Address'
      THEN 
         isnull(resultTable.Country,'') 
         + isnull( resultTable.City,'')
         + isnull( resultTable.Street,'')
         + isnull( resultTable.PostalCode,'') 
      end
于 2013-08-07T14:51:44.503 回答
3

尝试这样的事情:

ORDER BY
   CASE WHEN @sortBy = 'OrderNumber'
     THEN resultTable.OrderNumber END,
   CASE WHEN @sortBy = 'ProjectId'
      THEN resultTable.ProjectId END,
   CASE WHEN @sortBy = 'Address'
     THEN resultTable.Country END,
   CASE WHEN @sortBy = 'Address' 
     THEN resultTable.City END, 
   CASE WHEN @sortBy = 'Address' 
     THEN resultTable.Street END, 
   CASE WHEN @sortBy = 'Address' 
     THEN resultTable.PostalCode END,
   CASE WHEN @sortBy = 'CreatedDate'
     THEN resultTable.CreatedDate END
于 2013-08-07T14:59:57.450 回答
0

假设 @sortBy 只能有这 4 个值

CASE WHEN @sortBy = 'OrderNumber' THEN resultTable.OrderNumber END,
CASE WHEN @sortBy = 'ProjectId'   THEN resultTable.ProjectId END,
CASE WHEN @sortBy = 'CreatedDate' THEN resultTable.CreatedDate END,
CASE WHEN @sortBy = 'Address'     THEN resultTable.Country END,
resultTable.City, resultTable.Street, resultTable.PostalCode
于 2013-08-07T15:07:41.153 回答