msg 205,级别16,状态1,使用union、intersect或except运算符组合的所有查询的表达式数必须相等

cwxwcias  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(321)

我想使用 order by newid() 把结果合并在一起,但是我犯了一个错误我做错了什么?

create procedure [dbo].[genrate_Exame] 
    @course_id int
as 
    if @course_id = 600
    begin
        select top(7) 
            C.C#_Mcq_Id,
            C.C#_MCQ_Question,
            C.C#_Choices, 
            null as [no_question]
        from C#_MCQ C

        union all

        select top(3) 
            T.C#_T_F_Id,
            T.C#_T_F_Q,
            null as [no_question]
        from C#_T_F T
        order by NEWID()
     end
     else if (@course_id = 500)
     begin 
         select top(7)
             Q.SQl_Mcq_id,
             Q.SQl_MCQ_Question,
             Q.SQl_Choices,
             null as [no_question]
         from SQl_MCQ Q

         union all

         select top(3)
             QT.SQl_T_F_Id,
             QT.SQl_T_F_Q, 
             null as [no_question]
         from 
             SQl_T_F QT
         order by 
             NEWID()
    end
p8h8hvxi

p8h8hvxi1#

为了 UNION 以及 UNION ALL ,必须满足以下条件。请阅读msdn上的union
以下是使用union组合两个查询的结果集的基本规则:
在所有查询中,列的数目和顺序必须相同。
数据类型必须兼容。
在您的情况下,表达式的数量不相等:

-- 4 columns here
 select top(7) 
            C.C#_Mcq_Id,
            C.C#_MCQ_Question,
            C.C#_Choices, 
            null as [no_question]
        from C#_MCQ C

        union all
-- 3 columns here
        select top(3) 
            T.C#_T_F_Id,
            T.C#_T_F_Q,
            null as [no_question]
        from C#_T_F T

另外,如果您想随机获取值,则必须应用 ORDER BY NEWID() 在select查询的两个部分,而不仅仅是外部。

SELECT * FROM
(
 select top(7) 
            C.C#_Mcq_Id,
            C.C#_MCQ_Question,
            C.C#_Choices, 
            null as [no_question]
        from C#_MCQ C
ORDER BY NEWID()
) as t1
union all
SELECT * FROM 
(
 select top(3) 
            T.C#_T_F_Id,
            T.C#_T_F_Q,
            null as [C#_Choices]
            null as [no_question]
        from C#_T_F T
ORDER BY NEWID()
) as t2

相关问题