视图难题,请高手解决!
视图由多个(可能是7,8个,并且很多表中都有相同的字段)表关联而成,视图的字段取所有关联表的所有字段,表可能增加字段,但增加字段之前的字段名称是未知的,要达到的目标是:使视图的字段跟着表的字段的变化而改变,就是表增加字段了,视图也增加了相应的字段 问题点数:50、回复次数:8Top
1 楼funsuzhou(☆【处变不惊】☆)回复于 2005-11-22 13:42:59 得分 20
--类似这样,不过有重复列。如果要没有重复列,比较麻烦
select a.*,b.*,c.*,d.*,e.*,f.*,g.*
from table1 a
left join table2 b on a.字段1=b.字段1
left join table3 c on b.字段1=c.字段1
left join table4 d on c.字段1=d.字段1
left join table5 e on d.字段1=e.字段1
left join table6 f on e.字段1=f.字段1
left join table7 g on f.字段1=g.字段1Top
2 楼funsuzhou(☆【处变不惊】☆)回复于 2005-11-22 13:58:09 得分 0
--用动态SQL语句。下面的“关系字段1”、“关系字段2”等是table1、table2等里面不希望重复出现的列名。
--类似:
declare @sql varchar(8000)
set @sql='select '
select @sql=@sql+t.col+',' from (
select col=col_name(object_id('table1'),ordinal_position)from information_schema.columns where table_name='table1'
)t where col not in('关系字段1','关系字段2')
select @sql=@sql+t.col+',' from (
select col=col_name(object_id('table2'),ordinal_position)from information_schema.columns where table_name='table2'
)t where col not in('关系字段1','关系字段2')
select @sql=@sql+t.col+',' from (
select col=col_name(object_id('table3'),ordinal_position)from information_schema.columns where table_name='table3'
)t where col not in('关系字段1','关系字段2')
select @sql=@sql+t.col+',' from (
select col=col_name(object_id('table4'),ordinal_position)from information_schema.columns where table_name='table4'
)t where col not in('关系字段1','关系字段2')
select @sql=@sql+t.col+',' from (
select col=col_name(object_id('table5'),ordinal_position)from information_schema.columns where table_name='table5'
)t where col not in('关系字段1','关系字段2')
select @sql=@sql+t.col+',' from (
select col=col_name(object_id('table6'),ordinal_position)from information_schema.columns where table_name='table6'
)t where col not in('关系字段1','关系字段2')
select @sql=@sql+t.col+',' from (
select col=col_name(object_id('table7'),ordinal_position)from information_schema.columns where table_name='table7'
)t where col not in('关系字段1','关系字段2')
set @sql=left(@sql,len(@sql)-1)
set @sql=@sql+' '+'from table1 a left join table2 b on a.字段1=b.字段1 left join table3 c on b.字段1=c.字段1 left join table4 d on c.字段1=d.字段1 left join table5 e on d.字段1=e.字段1 left join table6 f on e.字段1=f.字段1 left join table7 g on f.字段1=g.字段1'
select @sqlTop
3 楼funsuzhou(☆【处变不惊】☆)回复于 2005-11-22 13:59:09 得分 0
--最后加上:
exec (@sql)Top
4 楼morou_007(默柔)回复于 2005-11-22 14:09:57 得分 0
有的表之间有重复列,有的表没有,所以更麻烦啊!帮帮忙了,给个思路Top
5 楼churchatp1(别看资料,看聊效!)回复于 2005-11-22 14:24:19 得分 5
更新表的时候更新视图Top
6 楼weixiao51(4fen)回复于 2005-11-22 14:26:40 得分 5
最好不要用视图,改用存储过程,试图的列很难动态更新,并且查询速度没有存储过程快Top
7 楼morou_007(默柔)回复于 2005-11-22 14:40:48 得分 0
存储过程我还没有写过呢,表的列更新视图的列就能更新吗?请问用哪条语句啊?Top
8 楼try_hard(IT菜鸟)回复于 2005-11-29 17:03:51 得分 20
可以写程序动态修改表的时候就修改是图,先将视图的SQL语句分成两部分,一部分为str=select...,一部分为str1=from...,保存每个视图的这两个语句,要是修改表就可以修改视图alter view viewname as str+添加的表.字段+str1就可以了,主要就是动态改变字符串str和str1,并且获得准确的添加字符串
这只是个思路,具体事宜还要你自己解决Top




