在T-Sql

时间:2017-10-25 20:58:19

标签: sql sql-server tsql if-statement

我创建了一个CTE,我正在尝试使用以下内容删除表。请注意,CTE表达式工作正常,但IF ELSE语句不能。

IF 
with FinalSales (time, terminal_id, count) as
(
    select time, terminal_id, count(*)
    from Final_Sales
    group by time, terminal_id
    having count(*) = 1             -- condition here
)

delete Sales
from FinalSales
inner join Sales
    on Sales.[time] = FinalSales.[time] 
    and Sales.terminal_id = FinalSales.terminal_id

ELSE IF 

  with FinalSales (time, terminal_id, count) as
  (
    select time, terminal_id, count(*)
    from Final_Sales
    group by time, terminal_id
    having count(*) > 1              -- Condition here
  )
  delete Sales
  from FinalSales
  inner join Sales
      on Sales.[time] = FinalSales.[time] 
      and Sales.terminal_id = FinalSales.terminal_id

   delete #temp1
   from FinalSales
   inner join #temp1
        on #temp1.[time] = FinalSales.[time] 
        and #temp1.terminal_id = FinalSales.terminal_id

在第一个IF语句中,当count(*) = 1然后我删除一个表中的行,然后在ELSEIF语句中count > 1我要删除两个表中的行。但是,我的方法不起作用。

如何将其包装成IF ELSE语句?或者还有其他方法吗?

简单结构的整个查询,

if count(*) == 1:
   delete Sales
else if count(*) > 1:
   delete Sales, #temp1
像这样的事情。我怎么能在t-sql中做到这一点?

任何想法都将不胜感激。

2 个答案:

答案 0 :(得分:1)

我认为这可行:

declare @count_of_duplicates int

set @count_of_duplicates = 

(select max(duplicate_count)
from
(       select time, terminal_id, count(*) as duplicate_count
        from Final_Sales
        group by time, terminal_id)  t1)

我们首先将参数设置为count(*)的最大值。如果有重复,则它将是大于1的值,否则如果没有重复,则为1。

然后我们可以开始我们的条件:

if @count_of_duplicates = 1

begin
with FinalSales (time, terminal_id, count) as
(
    select time, terminal_id, count(*)
    from Final_Sales
    group by time, terminal_id
)

delete Sales
from FinalSales
inner join Sales
    on Sales.[time] = FinalSales.[time] 
    and Sales.terminal_id = FinalSales.terminal_id
end

else if @count_of_duplicates > 1
begin
  with FinalSales (time, terminal_id, count) as
  (
    select time, terminal_id, count(*)
    from Final_Sales
    group by time, terminal_id
  )
  delete Sales
  from FinalSales
  inner join Sales
      on Sales.[time] = FinalSales.[time] 
      and Sales.terminal_id = FinalSales.terminal_id

   delete #temp1
   from FinalSales
   inner join #temp1
        on #temp1.[time] = FinalSales.[time] 
        and #temp1.terminal_id = FinalSales.terminal_id
end

我还没有机会解析它......让我知道它是否有效。

答案 1 :(得分:0)

为什么不使用if exists(查询)?

IF exists (
    select time, terminal_id 
    from Final_Sales 
    group by time, terminal_id 
    having count(*) = 1
) begin
    --query
end else begin
    --query
end