首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql的union使用有关问题

2013-06-19 
sql的union使用问题麻烦大虾看一下代码,,运行union 报错是怎么回事啊insert into caogen(id,no,tittle,aut

sql的union使用问题
麻烦大虾看一下代码,,运行union 报错是怎么回事啊
insert into caogen(id,no,tittle,author,contents)
select top 158 * from _TangSi 
where Author not in( select Author  from huangjia)and Author<>'无名氏' order by NEWID() 
union  
select * from _TangSi where Author='无名氏'
[解决办法]
分成两句... 要不你说说报错是啥吧。
[解决办法]
 order by NEWID()  不能加order by  改下就可以了

insert into caogen(id,no,tittle,author,contents)
select * from  (select top 158 * from _TangSi 
where Author not in( select Author  from huangjia)and Author<>'无名氏' order by NEWID() ) a
union  
select * from _TangSi where Author='无名氏'

[解决办法]
应该是楼上说的那样,使用union时,不能带有order by
insert into caogen(id,no,tittle,author,contents)
select top 158 * from _TangSi 
where Author not in( select Author  from huangjia)and Author<>'无名氏'
union  
select * from _TangSi where Author='无名氏' 

[解决办法]

insert into caogen(id,no,tittle,author,contents)
 select * from (select top 158 * from _TangSi 
 where Author not in( select Author  from huangjia)and Author<>'无名氏' union  
 select * from _TangSi where Author='无名氏')as t order by NEWID() 

[解决办法]
with cte
as
(
select top 158 * from _TangSi 
where Author not in( select Author  from huangjia)and Author<>'无名氏' order by NEWID() 
)

insert into caogen(id,no,tittle,author,contents)
select * from cte
union  
select * from _TangSi where Author='无名氏' 


union 连接查询中不能使用order by 语句,必须是类似上楼的
select * from (select top 158 * from _TangSi 
 where Author not in( select Author  from huangjia)and Author<>'无名氏' union  
 select * from _TangSi where Author='无名氏')as t order by NEWID() 

最后使用order by。
或者使用cte 语句定义也可以,参考我的sql语句
[解决办法]
引用:
with cte
as


(
select top 158 * from _TangSi 
where Author not in( select Author  from huangjia)and Author<>'无名氏' order by NEWID() 
)

insert into caogen(id,no,tittle,author,contents)
select * from cte
union  
select * from _TangSi where Author='无名氏' 



union 连接查询中不能使用order by 语句,必须是类似上楼的
select * from (select top 158 * from _TangSi 
 where Author not in( select Author  from huangjia)and Author<>'无名氏' union  
 select * from _TangSi where Author='无名氏')as t order by NEWID() 

最后使用order by。
或者使用cte 语句定义也可以,参考我的sql语句
在使用 UNION、EXCEPT 或 INTERSECT 运算符的查询中,只允许在语句末尾使用 ORDER BY。  只有在顶级查询而不是子查询中指定了 UNION、EXCEPT 和 INTERSECT 时,此限制才适用。

热点排行