再谈 UNION ALL 和 ORDER BY NEWID 一起使用
来源:未知 责任编辑:智问网络 发表时间:2013-09-26 23:53 点击:次
当使用UNION ALL或者UNION时,如果按照NewId()随机排序,那么,不能直接写
SQL 代码
SELECT TOP 2 * FROM [Article] Where ArticleId < 100 Order By NewId()
UNION ALL
SELECT TOP 8 * FROM [Article] Where ArticleId > 200 Order By NewId()
如果这样写,运行时会报告错误:在关键字'UNION' 附近有语法错误。
需要写成
SQL 代码
SELECT * FROM (SELECT TOP 2 * FROM [Article] Where ArticleId < 100 Order By NewId()) A
UNION ALL
SELECT * FROM (SELECT TOP 8 * FROM [Article] Where ArticleId > 200 Order By NewId()) B
但是,这些,在SQL Server 2008里面是正确的,但在SQL Server2000里面,仍然会报告错误:如果语句中包含UNION 运算符,那么ORDER BY 子句中的项就必须出现在选择列表中。
在SQL Server 2000里面,需要写成
SQL 代码
SELECT * FROM (SELECT TOP 2 *, NewId() As RandomX FROM [Article] Where ArticleId < 100 Order By RandomX) A
UNION ALL
SELECT * FROM (SELECT TOP 8 *, NewId() As RandomX FROM [Article] Where ArticleId > 200 Order By RandomX) B
才可以正常执行。
SQL 代码
SELECT TOP 2 * FROM [Article] Where ArticleId < 100 Order By NewId()
UNION ALL
SELECT TOP 8 * FROM [Article] Where ArticleId > 200 Order By NewId()
如果这样写,运行时会报告错误:在关键字'UNION' 附近有语法错误。
需要写成
SQL 代码
SELECT * FROM (SELECT TOP 2 * FROM [Article] Where ArticleId < 100 Order By NewId()) A
UNION ALL
SELECT * FROM (SELECT TOP 8 * FROM [Article] Where ArticleId > 200 Order By NewId()) B
但是,这些,在SQL Server 2008里面是正确的,但在SQL Server2000里面,仍然会报告错误:如果语句中包含UNION 运算符,那么ORDER BY 子句中的项就必须出现在选择列表中。
在SQL Server 2000里面,需要写成
SQL 代码
SELECT * FROM (SELECT TOP 2 *, NewId() As RandomX FROM [Article] Where ArticleId < 100 Order By RandomX) A
UNION ALL
SELECT * FROM (SELECT TOP 8 *, NewId() As RandomX FROM [Article] Where ArticleId > 200 Order By RandomX) B
才可以正常执行。
最新推荐更多>>>
- 发表评论
-
- 最新评论 进入详细评论页>>