2011-09-23 74 views
5

我们有两个表具有相同的结构和基于一个变量我想选择哪个表选择不必在我的程序中写2个查询。我可以写一个查询有一个条件表选择

这可能吗?

我试图

declare @table int 
set @table = 1 

Select orderID, Quantity 
from case when @table = 1 then tblOrders else tblSubscriptionOrders end 
where filled = 0 

但没有奏效

回答

6

您将需要使用动态SQL这个(假设你想将它扩展到不止2表),这会工作,但是不理想的,因为SQL不会为其生成统计信息,并且在优化查询时有更难的时间。

declare @table sysname 
declare @SQL varchar(1000) 

set @table = 'MyTable' 
SET @SQL='SELECT orderID, Quantity FROM ' + QUOTENAME(@table) + ' WHERE filled=0' 

exec sp_executesql @SQL 

,或者在一个存储过程:

CREATE PROCEDURE p_ConditionalSelect @table sysname 
as 

declare @SQL varchar(1000) 

set @table = 'MyTable' 
SET @SQL='SELECT orderID, Quantity FROM ' + QUOTENAME(@table) + ' WHERE filled=0' 

exec sp_executesql @SQL 
+0

+1。这很可能会超过我工会的“解决方案”。 –

+0

我试图避免为一次执行写一个sp,尽管这似乎是我不得不做的解决方案,因为最终结果比我提出的简单示例更复杂。 – Chad

3

一种选择是使用动态SQL,但如果性能是不是立竿见影的问题,更简单的是刚刚UNION表,并添加一个虚拟[table]列可供选择。

SELECT orderID, Quantity 
FROM (
    SELECT [table] = 1, orderID, Quantity 
    FROM tblOrders 
    UNION ALL 
    SELECT [table] = 2, orderID, Quantity 
    FROM tblSubscriptionOrders 
) t 
WHERE t.Table = @table 
4

如果它只是两个表,你可以这样做:

Declare @table = 1 

SELECT * 
FROM Table1 
WHERE <stuff> 
AND @Table = 1 

UNION ALL 

SELECT * 
FROM Table2 
WHERE <stuff> 
AND @Table = 2 

@table的过滤器将导致仅两个半显示的数据之一。

+0

+1未经测试,但我认为这将是最快的解决方案。 –

2

你可以试试这个

declare @table int 
set @table = 1 

Select orderID, Quantity 
From tblOrders 
Where @table = 1 
And filled = 0 

UNION ALL 

Select orderID, Quantity 
From tblSubscriptionOrders 
Where @table = 2 
And filled = 0 

或本:

declare @table int 
set @table = 1 

if @table = 1 
    Select orderID, Quantity 
    From tblOrders 
    Where filled = 0 
else if @table = 2 
    Select orderID, Quantity 
    From tblSubscriptionOrders 
    Where filled = 0 
相关问题