从Case语句条件返回多个数据

时间:2017-08-16 19:15:32

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

我有以下SQl。现在我只得到<td class="HeaderData"> Year 1 </td>的回报,因为在下面的sql中满足所有条件我怎样才能得到所有..这是小提琴Sql Fiddle

Declare @ContractTerm int
Set @ContractTerm = 5

Select Case When @ContractTerm  >= 1 Then '<td class="HeaderData"> Year 1 </td>'
   When @ContractTerm >=  2 Then '<td class="HeaderData"> Year 2 </td>' 
   When @ContractTerm >= 3 Then '<td class="HeaderData"> Year 3 </td>'
   When @ContractTerm  >= 4 Then '<td class="HeaderData"> Year 4 </td>' 
   When @ContractTerm  >= 5 Then '<td class="HeaderData"> Year 5 </td>' End 

由于

2 个答案:

答案 0 :(得分:2)

也许你想把这些条件连在一起?

Select ( (Case When @ContractTerm >= 1 Then '<td class="HeaderData"> Year 1 </td>' else '' end) +
         (case When @ContractTerm >= 2 Then '<td class="HeaderData"> Year 2 </td>' else '' end) +
         (case When @ContractTerm >= 3 Then '<td class="HeaderData"> Year 3 </td>' else '' end) +
         (case When @ContractTerm >= 4 Then '<td class="HeaderData"> Year 4 </td>' else '' end) +
         (case When @ContractTerm >= 5 Then '<td class="HeaderData"> Year 5 </td>' else '' end)
        ) as all_conditions

答案 1 :(得分:0)

这将导致在@ContractTerm

上声明的数量
DECLARE @ContractTerm INT
DECLARE @Counter INT
SET @ContractTerm = 5
SET @Counter = 1

WHILE @Counter <= @ContractTerm
BEGIN
   SELECT '<td class="HeaderData"> Year ' + CAST(@Counter AS VARCHAR) + ' </td>'

   SET @Counter += 1
END