在存储过程中使用CTE和IF语句

时间:2013-11-07 22:12:42

标签: sql-server if-statement common-table-expression

我正在为SSRS报告创建存储过程。实际上,SP从用户获取值,然后将其提供给CTE表。这是我的SP的样子:

@parameter1 varchar(12),
@parameter2 varchar(13),
@parameter3 varchar(13),
@parameter4 varchar(13)

;with cte1
     as (select column1, column2 from table1 
                 where column1 = @parameter1 and column2 = parameter2),
      cte2
     as (select column1, column2 from table3
                where column2 in (select column2 from cte1)
                AND column1 = @paramter3),
      cte3
     as (select column1, column2 from table4
               where column2 in (select column2 from cte2)
               AND column1 = @parameter4)

如果我使用SELECT语句,我可以在查询中加入这些CTE。但是,需求发生了变化,现在我需要添加IF逻辑来说“IF学校名称= @ parameter1然后执行此选择语句,否则执行其他选择语句等等。”

这就是我为满足这一要求所做的工作:

declare @1temp varchar(50)  --declaring this all the way at the top with other parameters

set @1temp = @parameter1

   If @1temp = 'Peabody'
      BEGIN 
           (Select from table1 where column1 = '1234')
      END

使用此逻辑时出现以下错误:
        关键字“SET”附近的语法不正确。

我甚至尝试过遵循逻辑而仍然没有成功:

    select @ltemp = column1 FROM cte3  --i made sure that only one value is being generated by that select statement
      IF @temp = 'Peabody'
         BEGIN

    (Select from table1 where column1 = '1234')
         END

我的对象名称'cte2'无效。

最后,我尝试了以下逻辑:

     set @1temp = (select column1 from cte3)   --i made sure that only one value is being generated by the select statement
          IF @1temp = 'Peabody'
               BEGIN

              (Select from table1 where column1 = '1234')
               END

有人可以告诉我,我做错了什么?!

0 个答案:

没有答案
相关问题