从两个查询的UNION返回前1个值并将其分配给变量

时间:2018-01-29 10:04:24

标签: sql sql-server sql-server-2008

是否可以通过从两个查询的UNION获得前1个结果来直接分配变量?

declare @a varchar(3)

select top 1 @a = (select sifval
                from VALUTI
                where OZNVAL = 'EUR'
                union 
                select sifval
                from KURSNA
                where OZNVAL = 'EUR')

执行此查询会返回错误'子查询返回的值超过1'。还有其他方法可以做到这一点,而无需创建临时表吗?

5 个答案:

答案 0 :(得分:4)

如果您关心表现,可以考虑:

declare @a varchar(3);

select @a = (select top 1 sifval from VALUTI where OZNVAL = 'EUR');

if @a is null begin
      select @a = (select top 1 sifval from KURSNA where OZNVAL = 'EUR');
end;

使用不top的{​​{1}}非常可疑。

答案 1 :(得分:3)

试试这个..

DECLARE @A VARCHAR(3)
SELECT TOP 1 @A = SIFVAL FROM (SELECT SIFVAL
                FROM VALUTI
                WHERE OZNVAL = 'EUR'
                UNION 
                SELECT SIFVAL
                FROM KURSNA
                WHERE OZNVAL = 'EUR') T
SELECT @A

答案 2 :(得分:1)

试试这个:

declare @a varchar(3);

SET @a = (SELECT top 1 sifval FROM(select sifval
                from VALUTI
                where OZNVAL = 'EUR'
                union 
                select sifval
                from KURSNA
                where OZNVAL = 'EUR') as T);

答案 3 :(得分:1)

你实际上不需要前1名,因为变量牌一次只存储1个值,所以即使你没有指定,它也会默认为前1名。

您还可以尝试以下方法

SELECT *
FROM your_table
WHERE FIND_IN_SET(10, custom_categories) 
      OR FIND_IN_SET(11, custom_categories) 
      OR FIND_IN_SET(12, custom_categories);

或者这个

DECLARE @a VARCHAR(3);
SELECT @a = sifval
FROM 
(
    SELECT sifval
    FROM VALUTI
    WHERE OZNVAL = 'EUR'
    UNION
    SELECT sifval
    FROM KURSNA
    WHERE OZNVAL = 'EUR'
)q;

答案 4 :(得分:0)

Try This 
DECLARE @A VARCHAR(3)


SELECT @A= sifval 
FROM 
    (Select top 1 sifval 
     FROM VALUTI  where OZNVAL = 'EUR'
     UNION 
     Select  top 1  sifval
     FROM KURSNA
     WHERE OZNVAL = 'EUR')a


SELECT @A
ROLLBACK TRAN