注册 登录
编程论坛 新人交流区

求sqlserver存贮过程:按条件查询字段。

jonvahe 发布于 2007-10-27 09:20, 761 次点击

表1:id,工号,姓名,性别
表2:id,字段名,显示标志
表2的"字段名"的内容为表1的字段名:id,工号,姓名,性别; "显示标志"为: 0显示,-1不显示。
要求根据表2"字段名"与"显示标志"的相关条件,查询显示表1的记录。
如:
表1
id 工号 姓名 性别
1 a01 a 男
2 a02 b 男
3 a03 c 男
4 a04 d 男
表2
id 字段名 显示标志
1 id -1
2 工号 0
3 姓名 0
4 性别 -1
则查询结果为:
工号 姓名
a01 a
a02 b
a03 c
a04 d

[此贴子已经被作者于2007-10-27 9:21:33编辑过]

11 回复
#2
徐强2007-10-27 10:07

declare @a varchar(100)
set @a=''
select @a=@a+字段名 from table2 where 显示标志='0'

exec ('select '+@a+' from table1')
没有测试不知道正确吧 思路是这样的

#3
徐强2007-10-27 10:18

漏了一句

if @a<>''
begin
set @a=left(@a,len(@a)-1)
end


declare @a varchar(100)
set @a=''
select @a=@a+字段名 from table2 where 显示标志='0'
if @a<>''
begin
set @a=left(@a,len(@a)-1)
end
exec ('select '+@a+' from table1')

#4
徐强2007-10-27 10:24

把我写的例子一起贴出来看看吧

create table ceshi1(id int,name varchar(10),pass varchar(10))
go
create table ceshi2(id int identity(1,1),columns1 varchar(10),B varchar(1))
go

insert into ceshi1 select 1,'a','a' union select 2,'b','b'
insert into ceshi2 select 'id','1' union select 'name','0' union select 'pass','0'

select * from ceshi1
select * from ceshi2

declare @a varchar(100)
set @a=''
select @a=@a+columns1+',' from ceshi2 where b='0'

if @a<>''
begin
set @a=left(@a,len(@a)-1)
end
exec ('select '+@a+' from ceshi1')

#5
jonvahe2007-10-27 13:38
谢谢.
#6
pipifei1992007-10-28 11:51
大家一起分享成果,共同进步!
#7
jonvahe2007-10-29 09:44

将此存贮过程查询出来的字段及内容生成为表3,如表3已存在,先删除.能行不?

#8
jonvahe2007-10-29 13:33
顶一下.
#9
徐强2007-10-30 16:53
以下是引用jonvahe在2007-10-29 9:44:29的发言:

将此存贮过程查询出来的字段及内容生成为表3,如表3已存在,先删除.能行不?

最后一句改成:
exec ('if object_id(''表3'') is not null drop table 表3 select name,pass into 表3 from ceshi1')

#10
jonvahe2007-10-31 13:33

好象没达到要求.

#11
jonvahe2007-11-01 18:33
顶.
#12
jonvahe2007-11-05 13:57
顶一下.
1