接http://topic.csdn.net/u/20081031/11/b203f3e6-8c22-4b45-8c1a-2d90742516df.html帖子的疑惑用户表 yonghu
xuhao mingcheng gongsi
1 aa 1
2 bb 1
3 cc 1
4 dd 1
5 admin 2
6 ee 2
7 ff 2
公司表 gongsi
xuhao mingcheng
1 aaaaa
2 bbbbb 用户admin 有最高权限,可以查询所有用户,其它用户按公司分属查询OCTWIND回复的代码
select a.*,b.mingcheng from yonghu a right outer join gongsi b on a.gongsi = b.xuhao where a.gongsi in (case when (select mingcheng from yonghu where xuhao = '用户输入')= 'admin' then
(select distinct xuehao from gongsi) else (select gongsi from yonghu where xuhao = '用户输入')
end)
在用户输入不为admin的时候可以正确查询出结果,可为什么值为admin的时候就报错呢?select mingcheng from yonghu where xuhao = '用户输入' 这句话查询后的确只有一条数据
希望大家能够解惑~~~'用户输入'为 admin 的时候
错误为: 子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
xuhao mingcheng gongsi
1 aa 1
2 bb 1
3 cc 1
4 dd 1
5 admin 2
6 ee 2
7 ff 2
公司表 gongsi
xuhao mingcheng
1 aaaaa
2 bbbbb 用户admin 有最高权限,可以查询所有用户,其它用户按公司分属查询OCTWIND回复的代码
select a.*,b.mingcheng from yonghu a right outer join gongsi b on a.gongsi = b.xuhao where a.gongsi in (case when (select mingcheng from yonghu where xuhao = '用户输入')= 'admin' then
(select distinct xuehao from gongsi) else (select gongsi from yonghu where xuhao = '用户输入')
end)
在用户输入不为admin的时候可以正确查询出结果,可为什么值为admin的时候就报错呢?select mingcheng from yonghu where xuhao = '用户输入' 这句话查询后的确只有一条数据
希望大家能够解惑~~~'用户输入'为 admin 的时候
错误为: 子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
--------------------
出现这种结果肯定是有多条数据存在~
select a.*,b.mingcheng
from yonghu a
right outer join gongsi b on a.gongsi = b.xuhao
where
a.gongsi in ('+
case when (select top 1 mingcheng from yonghu where xuhao = '用户输入')= 'admin' then
'select distinct xuehao from gongsi'
else 'select gongsi from yonghu where xuhao = ''用户输入'''
end +'''') ')
--------------------
出现这种结果肯定是有多条数据存在~
if object_id('yonghu') is not null drop table yonghu
create table yonghu (xuhao int, mingcheng varchar(10) , gongsi int)
insert into yonghu
select 1,'aa',1 union all
select 2,'bb',1 union all
select 3,'cc',1 union all
select 4,'dd',1 union all
select 5,'admin',2 union all
select 6,'ee',2 union all
select 7,'ff',2 if object_id('gongsi') is not null drop table gongsi
create table gongsi (xuhao int,mingcheng varchar(10))
insert into gongsi
select 1,'aaaaa' union all
select 2,'bbbbb'
DECLARE @mc VARCHAR(10)SET @mc='admin'SELECT a.xuhao,a.mingcheng,b.mingcheng
FROM yonghu a
FULL JOIN
yonghu c
ON a.gongsi = CASE WHEN @mc='admin' THEN a.gongsi ELSE c.gongsi END
INNER JOIN gongsi b
ON a.gongsi = b.xuhao WHERE c.mingcheng = @mc
(select distinct xuehao from gongsi) else (select gongsi from yonghu where xuhao = '用户输入')
select distinct xuehao from gongsi
它返回的值不止一个
(select distinct xuehao from gongsi) else (select gongsi from yonghu where xuhao = '用户输入') 当你的用户输入为5时,那么执行select distinct xuehao from gongsi,那么会返回1,2两个值,在then后面需要一个确定的值,所以会有“子查询返回的值多于一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的”这个错误。
而用户输入不为5时,执行select gongsi from yonghu where xuhao = '用户输入',那么值返回一个值,自然就不会出错了。