日期:2014-05-18  浏览次数:20755 次

查询视图中所有字段名、字段所在表,字段描述。
从网上查了很久,没有查了很多信息都不对,sp_depends也试过了,但是查询出来的内容比实际的视图多两条,这两条都是join中on的字段出现了两遍,我想查出跟实际的视图列一样的内容,现在卡在视图的列位于哪个表中这个地方,没有找出他们之间的关联,恳请高手帮忙指点。最好能写出完整的Sql语句。谢谢。

------解决方案--------------------
sp_helptext ?
------解决方案--------------------
SQL code
USE MASTER
GO
CREATE proc sp_MSforeachObject
 @objectType int=1,
 @command1 nvarchar(2000), 
 @replacechar nchar(1) = N'?', 
 @command2 nvarchar(2000) = null,
    @command3 nvarchar(2000) = null, 
 @whereand nvarchar(2000) = null,
 @precommand nvarchar(2000) = null, 
 @postcommand nvarchar(2000) = null
as
 /* This proc returns one or more rows for each table (optionally, matching @where), with each table defaulting to its 
own result set */
 /* @precommand and @postcommand may be used to force a single result set via a temp table. */
 /* Preprocessor won't replace within quotes so have to use str(). */
 declare @mscat nvarchar(12)
 select @mscat = ltrim(str(convert(int, 0x0002)))
 if (@precommand is not null)
  exec(@precommand)
 /* Defined  @isobject for save object type */
 Declare @isobject varchar(256)
 select @isobject= case @objectType when 1 then 'IsUserTable'
         when 2 then 'IsView'
         when 3 then 'IsTrigger'
         when 4 then 'IsProcedure' 
         when 5 then 'IsDefault'   
         when 6 then 'IsForeignKey'
         when 7 then 'IsScalarFunction'
         when 8 then 'IsInlineFunction'
         when 9 then 'IsPrimaryKey'
         when 10 then 'IsExtendedProc'    
         when 11 then 'IsReplProc'
         when 12 then 'IsRule'
                  end
 /* Create the select */
 /* Use @isobject variable isstead of IsUserTable string */
EXEC(N'declare hCForEach cursor global for select ''['' + REPLACE(user_name(uid), N'']'', N'']]'') + '']'' + ''.'' + ''['' + 
REPLACE(object_name(id), N'']'', N'']]'') + '']'' from dbo.sysobjects o '
        + N' where OBJECTPROPERTY(o.id, N'''+@isobject+''') = 1 '+N' and o.category & ' + @mscat + N' = 0 '
       + @whereand)
 declare @retval int
 select @retval = @@error
 if (@retval = 0)
  exec @retval = sp_MSforeach_worker @command1, @replacechar, @command2, @command3
 if (@retval = 0 and @postcommand is not null)
  exec(@postcommand)
 return @retval
GO

这样我们来测试一下:
   --获得所有的存储过程的脚本:
         EXEc sp_MSforeachObject @command1="sp_helptext '?' ",@objectType=4
   --获得所有的视图的脚本:
         EXEc sp_MSforeachObject @command1="sp_helptext '?' ",@objectType=2
   --比如在开发过程中,没一个用户都是自己的OBJECT OWNER,所以在真实的数据库时都要改为DBO:
         EXEc sp_MSforeachObject @command1="sp_changeobjectowner '?', 'dbo'",@objectType=1
         EXEc sp_MSforeachObject @command1="sp_changeobjectowner '?', 'dbo'",@objectType=2
         EXEc sp_MSforeachObject @command1="sp_changeobjectowner '?', 'dbo'",@objectType=3
         EXEc sp_MSforeachObject @command1="sp_changeobjectowner '?', 'dbo'",@objectType=4

------解决方案--------------------
探讨
难道这个真的没法用系统表解决???

------解决方案--------------------
这个是没有办法用系统表解决的。原因是你可以重命名视视图中的列名,有些列是复合的或计算的,这个系统怎么能对应到具体的表呢?