SQL Server 2008需要使用SQL语句创建用户表类型create语句

SQL Server 2008需要使用SQL语句创建用户表类型create语句,sql,sql-server,sql-server-2008,types,user-defined-types,Sql,Sql Server,Sql Server 2008,Types,User Defined Types,我需要创建一个用户表类型。我的首选是使用单个SQL语句。忽略可归因于此类create语句的提示,我首先导出了逻辑,以便使用该语句为单列表生成create语句: select 'create type ' + tt.name + ' as TABLE (' + c.name + ' ' + t.name + case when t.name in ('varchar','char','nvarchar','nchar','binary','varbinary') then '(' +

我需要创建一个用户表类型。我的首选是使用单个SQL语句。忽略可归因于此类create语句的提示,我首先导出了逻辑,以便使用该语句为单列表生成create语句:

select 'create type ' + tt.name + ' as TABLE (' + c.name + ' ' + t.name +
case
when t.name in ('varchar','char','nvarchar','nchar','binary','varbinary') then
     '(' +
      case
         when c.max_length = -1 then 'MAX'
         else convert(varchar, c.max_length)
      end + ')'
    when t.name in ('numeric','decimal') then
      '(' + convert(varchar, c.precision) + ',' + convert(varchar, c.scale) + ')'
    else ''
 end + ')'
from sys.table_types tt
join sys.columns c
on tt.type_table_object_id = c.object_id
join sys.types t
on c.system_type_id = t.system_type_id and
c.user_type_id = t.user_type_id

这在数据类型等方面的范围有限,但现在已经足够了。我想弄明白的是,如何扩展它,使得创建表列定义的语句位于某种内部循环中,以处理1到n列。似乎这应该是可能的,但我还没有弄清楚逻辑。

您可以使用
for xml path
字符串串联技巧

select 'create type ' + tt.name + ' as TABLE (' + 
    stuff((select ', '+c.name + ' ' + t.name +
                  case when t.name in ('varchar','char','nvarchar','nchar','binary','varbinary') 
                       then '(' + case when c.max_length = -1 
                                       then 'MAX'
                                       else convert(varchar, c.max_length)
                                  end + ')'
                       when t.name in ('numeric','decimal') 
                       then '(' + convert(varchar, c.precision) + ',' + convert(varchar, c.scale) + ')'
                       else ''
                  end 
           from sys.columns c
             inner join sys.types t
               on c.system_type_id = t.system_type_id and
                  c.user_type_id = t.user_type_id        
           where c.object_id = tt.type_table_object_id
           for xml path(''), type      
          ).value('.', 'varchar(max)'), 1, 2, '')+ ')'
from sys.table_types tt

为了增加获得帮助的机会,你可能想回去接受之前8个问题中的一些问题的答案。哇,0%,嗯?让我想对答案撒谎不喜欢
scholar
badge?+1我仍然很惊讶,你似乎很容易把
xml
sql
混在一起。我自己试一试仍然会让我的亵渎程度一落千丈。。。