有没有办法从SQL Server中的table A
,table B
或两个表中进行选择?尽可能多,我不想使用动态SQL。我在类似的question中看到了这一点,但它只在1个表格中选择。
Declare @table = 1
SELECT *
FROM Table1
WHERE <stuff>
AND @Table = 1
UNION ALL
SELECT *
FROM Table2
WHERE <stuff>
AND @Table = 2
答案 0 :(得分:2)
你可以试试这个:
你有两个关于价值@table的解决方案。
您可以考虑@table = NULL关于两个表的选择,或者您可以考虑@table = value(例如3作为1和2的总和), 所以你的查询变为:
如果选择@table = NULL:
Declare @table = NULL
SELECT *
FROM Table1
WHERE <stuff>
AND (@Table = 1 OR @table IS NULL)
UNION ALL
SELECT *
FROM Table2
WHERE <stuff>
AND (@Table = 2 OR @table IS NULL)
如果选择@Table = value(例如3)
Declare @table = 3
SELECT *
FROM Table1
WHERE <stuff>
AND (@Table = 1 OR @table = 3)
UNION ALL
SELECT *
FROM Table2
WHERE <stuff>
AND (@Table = 2 OR @table = 3)
答案 1 :(得分:1)
您可以使用IF ... ELSE语句来实现此目的,如下所示。 我假设您想使用@table来控制脚本应该做什么。
Declare @table = 1
IF @table = 1
BEGIN
SELECT *
FROM Table1
WHERE <stuff>
END
ELSE IF @table = 2
BEGIN
SELECT *
FROM Table2
WHERE <stuff>
END
ELSE IF @table = 3 /* OR @table IN (1,2) --depends on how you want to handle this*/
BEGIN
SELECT *
FROM Table1
WHERE <stuff>
UNION ALL
SELECT *
FROM Table2
WHERE <stuff>
END
只要条件满足,脚本就会停止。 例如,IF @Table = 2,只运行以下脚本部分:
ELSE IF @table = 2
BEGIN
SELECT *
FROM Table2
WHERE <stuff>
END
答案 2 :(得分:-3)
希望这会有所帮助:
SELECT maker, Product.model AS model_1, PC.model AS model_2, price
FROM Product INNER JOIN PC ON PC.model = Product.model
ORDER BY maker, PC.model;