使用IF / ELSE来确定SELECT INTO语句 [英] Using IF / ELSE to determine a SELECT INTO statement

查看:1214
本文介绍了使用IF / ELSE来确定SELECT INTO语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些奇怪的问题,使用IF / ELSE来确定要执行哪一个或两个SELECT语句。运行完整语句时得到的错误消息是我的临时表已经存在,但是如果我运行两个单独的IF语句的两个单独的执行,则不会出现。

I'm having some strange issues using IF / ELSE to determine which one or two SELECT statements to execute. The error message I'm getting when running the full statement is that my temporary table already exists, but that does not occur if I run two separate executions of two separate IF statements.

以下是SQL Server中的代码:

Here is the code in SQL Server:

IF (select BusinessDayCount from Calendartbl) <= 1
  BEGIN
    SELECT * into #temp1
    FROM PreviousMonthTbl
  END
ELSE
  BEGIN
    SELECT * into #temp1
    FROM CurrentMonthTbl
  END


推荐答案

这是SQL Server中语法检查的功能。你不能在同一批次中两次创建一个#temporary表。

It's a "feature" of the syntax checking in SQL Server. You simply cannot "create" a #temporary table twice within the same batch.

这是你需要的模式。

SELECT * into #temp1
FROM PreviousMonthTbl
WHERE 1=0;

IF (select BusinessDayCount from Calendartbl) <= 1
  BEGIN
    INSERT into #temp1 SELECT *
    FROM PreviousMonthTbl
  END
ELSE
  BEGIN
    INSERT into #temp1 SELECT *
    FROM CurrentMonthTbl
  END

如果愿意,您还可以将分支(在这种情况下)表示为WHERE子句:

If you prefer, you can also express the branch (in this case) as a WHERE clause:

SELECT * into #temp1
FROM PreviousMonthTbl
WHERE (select BusinessDayCount from Calendartbl) <= 1
UNION ALL
SELECT *
FROM CurrentMonthTbl
WHERE isnull((select BusinessDayCount from Calendartbl),2) > 1

这篇关于使用IF / ELSE来确定SELECT INTO语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆