查询视图对应的基表名以及视图字段和对应的基表字段名

本文介绍了一种SQL查询方法,用于查找视图对应的基表名称及视图字段与基表字段之间的映射关系。该方法适用于需要了解视图内部结构及依赖情况的场景,但需要注意的是,视图中必须包含主键字段,否则查询结果可能产生混乱。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转:https://blog.csdn.net/weixin_33845477/article/details/93364024

select v.name ViewName,t.name TableName,vc.name ViewCol,tc.name TableCol
from sysdepends d,
     sysobjects v,
     syscolumns vc,
     sysobjects t,
     syscolumns tc
where objectproperty(d.id,'IsView')=1 
    and d.id=v.id 
    and v.id=vc.id
    and d.depnumber=vc.colid  
    and d.depnumber=tc.colid  
    and d.depid=t.id 
    and t.id=tc.id
    --and v.name='V_AMeals'
order by v.name

以上,查询视图对应的基表名以及视图字段和对应的基表字段名。

注意:视图中必须有主键字段,否则查出的对应关系可能会错乱!!!

--查询视图的创建脚本
sp_helptext  [V_AMeals]

--获取存储过程
SELECT * FROM sysobjects WHERE type = 'P' AND category = 0 ORDER BY name

--获取存储过程对应的脚本
SELECT * 
FROM syscomments
WHERE id = ( SELECT id FROM sysobjects WHERE name = 'UP_GetRecordByPage')
 

--select *,object_name(id) as 表名 ,c.name as 字段名 ,t.name 数据类型 ,c.prec as 长度  
--from syscolumns c inner join systypes t on c.xusertype=t.xusertype 
--where objectproperty(c.id,'IsView')=1 and c.id=object_id('V_AMeals')


--获取视图时段对应的基表

--drop table #t
select * into #t from
(
select v.name ViewName,t.name TableName,vc.name ViewCol,tc.name TableCol
from sysdepends d,
     sysobjects v,
     syscolumns vc,
     sysobjects t,
     syscolumns tc
where objectproperty(d.id,'IsView')=1 
    and d.id=v.id 
    and v.id=vc.id
    and d.depnumber=vc.colid  
    and d.depnumber=tc.colid  
    and d.depid=t.id 
    and t.id=tc.id
    and v.name='V_AMeals'
    --order by v.name
) as dd

select * from #t

--获取视图对应多表的所有字段
select sc.name as TableCol,st.name as TableName from syscolumns as sc,sysobjects as st
where sc.id=st.id
and st.name in (select TableName
from   #t
 )  
--获取视图对应的表名
select distinct TableName from   #t
--select Table_Name from INFORMATION_SCHEMA.VIEW_TABLE_USAGE where View_Name='V_AMeals'

 

--获取视图字段在子表中重复的字段
select TableCol,count(0) from
(
select sc.name as TableCol,st.name as TableName from syscolumns as sc,sysobjects as st
where sc.id=st.id
and st.name in (select TableName
from   #t
 )  
 ) as ss
 group by TableCol
 having count(0)>1

 

 


 
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值