English 中文(简体)
sql服务器条件选择到临时表
原标题:sql server conditional select into temp table

我在SQL Server 2008中工作,并试图根据特定条件选择临时表。。。对于报告,我需要高达18%的记录属于特定的产品类型。

if ((@totalRecords * .18) > @productTypeCount)
    select * into #tmpLP_REIT
    from myTable where productType = @productType
else
    select top 18 percent * into #tmpLP_REIT
    from myTable where productType = @productType

我一直收到错误“数据库中已经有一个名为#tmpLP_REIT的对象”,尽管我知道它不在那里,因为当我试图删除这样的表时,它指出它不存在我在else子句中也得到了这个错误

它似乎忽略了我的if语句,直接创建了第一个表,然后试图再次创建它。有什么建议吗?

最佳回答

这个代码是循环的吗?。。不过,如果第二次出现错误,那就可以解释了。如果没有,语法检查器肯定只是窒息了,因为它看到两个查询创建了同一个表,而没有意识到这是一个条件表。

一种解决方案是先创建表,然后将这两个查询的语法更改为插入查询。

另一个解决方案是使用动态SQL。。。在条件中构建正确的查询,然后执行它。这应该通过您当前正在触发的验证。

问题回答

暂无回答




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

难以执行 REGEXP_SUBSTR

I m 查询Oracle 10g。 我有两张表格(样本数据见下文)。 i m 试图提取一些领域

SQL Query Shortcuts

What are some cool SQL shorthands that you know of? For example, something I learned today is you can specify to group by an index: SELECT col1, col2 FROM table GROUP BY 2 This will group by col2

PHP array callback functions for cleaning output

I have an array of output from a database. I am wondering what the cleanest way to filter the values is example array Array ( [0] => Array ( [title] => title 1 ...

OracleParameter and DBNull.Value

we have a table in an Oracle Database which contains a column with the type Char(3 Byte). Now we use a parameterized sql to select some rows with a DBNull.Value and it doesn t work: OracleCommand ...

Running numbers in SQL

I have a SQL-statement like this: SELECT name FROM users WHERE deleted = 0; How can i create a result set with a running number in the first row? So the result would look like this: 1 Name_1 2 ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...

热门标签