如何在多个案例中选择表格

时间:2013-12-22 14:21:20

标签: sql sql-server

我想创建一个存储过程来从表中选择行,其顺序取决于输入变量。我试过这段代码:

ALTER proc [dbo].[advance_search] (
    @keyword nvarchar(50),
    @casi nvarchar(50),
    @loai nvarchar(5),
    @order nchar(10)
)
as
   select *
   from Nhac n 
   inner join CaSi cs on n.MaCS = cs.MaCS 
   where TenBH like '%'+@keyword+'%' AND TenCS like '%'+@casi+'%'
   ORDER BY 
      CASE 
          WHEN @loai = 'Ngayramat' AND @order = 'DESC' THEN n.Ngayramat 
          ELSE NULL 
      END DESC,
      CASE 
          WHEN @loai = 'Ngayramat' AND @order = 'ASC' THEN n.Ngayramat 
          ELSE NULL 
      END ASC,
      CASE 
          WHEN @loai = 'TenBH' AND @order = 'DESC' THEN n.TenBH 
          ELSE NULL 
      END DESC,
      CASE 
          WHEN @loai = 'TenBH' AND @order = 'ASC' THEN n.TenBH 
          ELSE NULL 
      END ASC,
      CASE 
          WHEN @loai = 'Luotnghe' AND @order = 'DESC' THEN n.Luotnghe 
          ELSE NULL 
      END DESC,
      CASE 
          WHEN @loai = 'Luotnghe' AND @order = 'ASC' THEN n.Luotnghe 
          ELSE NULL 
      END ASC

我想从2个表CasiNhac中选择所有表,其顺序取决于输入变量。

例如:如果输入变量:

@loai = 'luotnghe', @order = 'DESC'

命令将是:

select *
from Nhac n inner join CaSi cs on n.MaCS = cs.MaCS 
where TenBH like '%'+@keyword+'%' AND TenCS like '%'+@casi+'%'
ORDER BY n.luotnghe DESC

任何帮助都会很棒

1 个答案:

答案 0 :(得分:0)

问题很简单。你的变量声明太短了:

ALTER proc [dbo].[advance_search] (
    @keyword nvarchar(50),
    @casi nvarchar(50),
    @loai nvarchar(5),
-------------------^
    @order nchar(10)
)

然后,您将@loai与8个字符的值进行比较,因此它们永远不会相等。

将其更改为更大的值:

ALTER proc [dbo].[advance_search] (
    @keyword nvarchar(255),
    @casi nvarchar(255),
    @loai nvarchar(255),
-------------------^
    @order nchar(10)
)

由于某些不合理的原因,我经常使用255作为字符串长度的“更大”值。