9

我正在尝试编写一个存储过程,并根据某个列值,我希望能够更改我从中选择的表。我将尝试举一个例子:

SELECT ItemNumber,
       ItemType, 
       Description
FROM

CASE ItemType
WHEN 'A' THEN TableA
ELSE TableB
END

WHERE 

CASE ItemType
WHEN 'A' THEN ItemNumber = @itemNumber
ELSE PartNumber = @itemNumber
END

如您所见,我不仅动态更改了我从中选择的表,而且由于这两个表是由两个不同的人在两个不同的时间制作的,所以列名也不同。

所以,我的问题是:什么是完成此任务的最佳方法,因为 SQL Server 似乎不喜欢我构建的查询。

如果有人看到我正在尝试做的事情可以提出更好的方法来做到这一点,我会全神贯注:-)

4

6 回答 6

6

您不能在 FROM 子句中使用 CASE 语句,但可以使用以下语句:

SELECT itemnumber, itemtype, description
  FROM tablea
 WHERE itemnumber = @itemnumber AND itemtype = 'A'
UNION ALL
SELECT itemnumber, itemtype, description
  FROM tableb
 WHERE partnumber = @itemnumber AND itemtype <> 'A'
于 2009-01-29T18:02:44.517 回答
4

您可以尝试将动态 SQL 语句构建为字符串,然后调用 sp_executesql 存储过程来执行该字符串。

有关更多信息和示例,请参见此处

于 2009-01-29T17:35:18.300 回答
4

我不确定你为什么要在一个 SQL 语句中做事.. 我不是 SQL Server 人员,但在 Oracle 存储过程中你可以写这样的东西

If itemtype = 'A' 
Then 
 <statement for table A>
Else
 <statement for Table B>
End if

像这样的东西也应该在 SQL Server 中工作......也许有人可以对此进行扩展?

于 2009-01-29T18:42:36.307 回答
1

你真的没有解释ItemType来自哪里。如果您只是组合两个表,则建议UNION可能适用。

这是另一种可能与您的问题有关的可能性:

SELECT ItemNumber,
       ItemType, 
       COALESCE(TableA.Description, TableB.Description) AS Description
FROM Items
LEFT JOIN TableA
    ON Items.ItemType = 'A'
    AND TableA.ItemNumber = Items.ItemNumber
LEFT JOIN TableB
    ON Items.ItemType <> 'A'
    AND TableB.ItemNumber = Items.ItemNumber
于 2009-01-29T17:40:36.197 回答
0

您最好先使用 UNION 查询来连接表,然后再使用 SELECT。

此外,您可以考虑为其中一个表创建一个视图,以便在重命名它们时只提取您需要的列,然后是 UNION,然后从 UNION 中选择。

或者使用临时表来存储每个查询的结果。将临时表的创建放在 CASE 中(伪代码,未测试):

CASE @itemType
   WHEN 'A'
      SELECT ACol1 AS Col1, ACol2 AS Col2
      FROM TABLE_A
      INTO #tempTable
      WHERE ItemNumber = @itemNumber
   ELSE
      SELECT BCol1 AS Col1, BCol2 AS Col2
      FROM TABLE_B
      INTO #tempTable
      WHERE PartNumber = @itemNumber
END

SELECT * FROM #tempTable
于 2009-01-29T17:35:10.950 回答
0

它可以是动态查询,或者您可以继续使用以下方法:

SELECT 
  CASE ItemType
    WHEN 'A' THEN (Select ItemNumber from TableA Where ItemNumber = @itemNumber)
    When 'B' THEN (Select ItemNumber from TableB Where ItemNumber = @itemNumber)
  End as ItemNumber,
  CASE ItemType
    WHEN 'A' THEN (Select ItemType from TableA Where ItemNumber = @itemNumber)
    When 'B' THEN (Select ItemType from TableB Where ItemNumber = @itemNumber)
  End as ItemType,
  CASE ItemType
    WHEN 'A' THEN (Select Description from TableA Where ItemNumber = @itemNumber)
    When 'B' THEN (Select Description from TableB Where ItemNumber = @itemNumber)
  End as Description 
于 2020-08-11T05:59:27.207 回答