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

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

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

  1. create procedure [dbo].[genrate_Exame]
  2. @course_id int
  3. as
  4. if @course_id = 600
  5. begin
  6. select top(7)
  7. C.C#_Mcq_Id,
  8. C.C#_MCQ_Question,
  9. C.C#_Choices,
  10. null as [no_question]
  11. from C#_MCQ C
  12. union all
  13. select top(3)
  14. T.C#_T_F_Id,
  15. T.C#_T_F_Q,
  16. null as [no_question]
  17. from C#_T_F T
  18. order by NEWID()
  19. end
  20. else if (@course_id = 500)
  21. begin
  22. select top(7)
  23. Q.SQl_Mcq_id,
  24. Q.SQl_MCQ_Question,
  25. Q.SQl_Choices,
  26. null as [no_question]
  27. from SQl_MCQ Q
  28. union all
  29. select top(3)
  30. QT.SQl_T_F_Id,
  31. QT.SQl_T_F_Q,
  32. null as [no_question]
  33. from
  34. SQl_T_F QT
  35. order by
  36. NEWID()
  37. end
p8h8hvxi

p8h8hvxi1#

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

  1. -- 4 columns here
  2. select top(7)
  3. C.C#_Mcq_Id,
  4. C.C#_MCQ_Question,
  5. C.C#_Choices,
  6. null as [no_question]
  7. from C#_MCQ C
  8. union all
  9. -- 3 columns here
  10. select top(3)
  11. T.C#_T_F_Id,
  12. T.C#_T_F_Q,
  13. null as [no_question]
  14. from C#_T_F T

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

  1. SELECT * FROM
  2. (
  3. select top(7)
  4. C.C#_Mcq_Id,
  5. C.C#_MCQ_Question,
  6. C.C#_Choices,
  7. null as [no_question]
  8. from C#_MCQ C
  9. ORDER BY NEWID()
  10. ) as t1
  11. union all
  12. SELECT * FROM
  13. (
  14. select top(3)
  15. T.C#_T_F_Id,
  16. T.C#_T_F_Q,
  17. null as [C#_Choices]
  18. null as [no_question]
  19. from C#_T_F T
  20. ORDER BY NEWID()
  21. ) as t2
展开查看全部

相关问题