连接多个变量表并将所有列名和数据类型输出到变量中

时间:2014-10-29 15:32:28

标签: sql sql-server sql-server-2008

我有很多变量表,每个表中都有这么多列。我想知道每个变量表的所有列名和数据类型,而不通过每个变量表来确定它们是手动的。我曾尝试使用sys.columns,但当然它不起作用,因为变量表信息没有存储在系统数据库中。

所有列名称的结果应该类似于@AllColumnsAndDataTypes的结果。请参阅代码中的推荐。谢谢

            ALTER proc [dbo].[usp_BigCodes]
            as
            begin

             --Multiple table variables
             declare @Table_01 table( TB01_MasterID int, Column_01 nvarchar(100), Column_02 nvarchar(100))
             declare @Table_02 table( TB02_MasterID int, Column_03 nvarchar(100), Column_04 nvarchar(100))
             declare @Table_03 table( TB03_MasterID int, Column_04 nvarchar(100), Column_05 nvarchar(100))

              ---I need to convert all of the code above programatically into 1 table
             --The result should be out put into the @AllColumnsAndDataTypes 
             declare @AllColumnsAndDataTypes nvarchar(max)
             --Result should be similar to below.
             set @AllColumnsAndDataTypes='
                                         TB01_MasterID int, Column_01 nvarchar(100), Column_02 nvarchar(100)
                                         TB02_MasterID int, Column_03 nvarchar(100), Column_04 nvarchar(100)
                                         TB03_MasterID int, Column_04 nvarchar(100), Column_05 nvarchar(100)
                                        '
            ---Need code to do output the result into the variable like on line 15 to 17  
                --Join all table variables and output all columns names and datatype into @AllColumnsAndDataTypes 
                select  @AllColumnsAndDataTypes = ???????? from 
                @Table_01 as T1 
                INNER JOIN @Table_02 as T2 ON T1.TB01_MasterID=T2.TB02_MasterID
                INNER JOIN @Table_03 as T3  ON T1.TB01_MasterID=T3.TB03_MasterID 

             --Display the result
             select @AllColumnsAndDataTypes as AllColumnsInfo
            end

2 个答案:

答案 0 :(得分:1)

可以使用sys.columns,但您必须在TempDB

的上下文中执行此操作

Source

示例:

declare  @foo table ( bar int, blah varchar(30) )
declare  @object_name sysname, @object_id int

select   @object_name = OBJECT_NAME([object_id], DB_ID('TempDB'))
        ,@object_id = [object_id]
from     tempdb.sys.columns 
where    name = 'bar'

select   @object_name [object_name], @object_id [object_id]

select   [object_id], name
from     tempdb.sys.columns 
where    [object_id] = @object_id

答案 1 :(得分:0)

尝试以下方法......

declare @Table_01 table( TB01_MasterID int, Column_01 nvarchar(100), Column_02 nvarchar(100))

select TN.N.value('local-name(.)', 'sysname') as ColumnName
from 
  (
  select TV.*
  from (select 1) as D(N)
    outer apply (
                select top(0) *
                from @Table_01
                ) as TV
  for xml path(''), elements xsinil, type
  ) as TX(X)
cross apply TX.X.nodes('*') as TN(N)