我有一个SQL函数,它返回一个团队列表。
我想使用union将其他列表加入到该列表中,但前提是第一次选择返回多行。
类似的东西:
CREATE FUNCTION Teams()
RETURNS TABLE
AS
RETURN
(
SELECT * FROM TABLE1
if @@rowcount>1
UNION
SELECT * FROM TABLE2
end if
)
答案 0 :(得分:2)
不漂亮,但这应该有效:
CREATE FUNCTION Teams()
RETURNS TABLE
AS
RETURN
(
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2 WHERE EXISTS (SELECT * FROM TABLE1)
)
如果第一个表中的选择很复杂,您可以将它放入CTE:
CREATE FUNCTION Teams()
RETURNS TABLE
AS
RETURN
(
WITH Result AS
(
SELECT * FROM TABLE1 WHERE ComplicatedConditions = 1
)
SELECT * FROM Result
UNION
SELECT * FROM TABLE2 WHERE EXISTS (SELECT * FROM Result)
)
答案 1 :(得分:1)
如果我理解正确
CREATE FUNCTION Teams()
RETURNS TABLE
AS
RETURN
(
if (select COUNT(*) from TABLE2)>1
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
else
SELECT * FROM TABLE1
)
答案 2 :(得分:0)
一种方法是:
IF EXISTS(SELECT 1 FROM TABLE1)
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
ELSE
SELECT * FROM TABLE1