现有表 a
no  方式     金额
1   800    100.00
2   801    20.00
1   900    50.00
 
表 b
code   name
800    现金
801    支票
900    金卡表a中的方式对应表b中的code, 这个项目不是固定的有可能还有 901,902,903,
怎样建立一个表结构形成
no   现金    支票   金卡 
1  100.00    0    50.00
2    0      20.00   0
不是说用行转列查询,是建一个实表  相当于用存储过程建表但是字段是变量  这该如何实现 SQL动态建表  实表

解决方案 »

  1.   

    declare @sql varchar(max)
    set @sql='組合动态建表指令'
    exec(@sql)
      

  2.   

    +1
    用select  into  from 不是可以创建表吗?
      

  3.   

    IF OBJECT_ID('tempdb..#tb') IS NOT NULL 
    DROP TABLE #tb;with a (no,code,amount) as
    (
    select 1,800,100.00 union all
    select 2,801,20.00 union all
    select 1,900,50.00
    )
    ,b (code,name) as
    (
    select 800,'现金' union all
    select 801,'支票' union all
    select 900,'金卡'
    )
    select a.*,b.name
    into #tb
    from a
    inner join b on a.code=b.codedeclare @sql varchar(max),@sql2 varchar(max)
    select @sql = isnull(@sql + '],[' , '') + name from (select distinct code,name from #tb) a
    set @sql = '[' + @sql + ']'
    select @sql2 = isnull(@sql2 + ',' , ',') + 'isnull('+name+',0) '+name from (select distinct code,name from #tb) a
    set @sql='select no'+@sql2+' from (select no,name,amount from #tb) a pivot (max(amount) for name in (' + @sql + ')) b'
    exec (@sql)
      

  4.   

    倒數第二行改為:
    set @sql='select no'+@sql2+' into 新表 from (select no,name,amount from #tb) a pivot (max(amount) for name in (' + @sql + ')) b'
      

  5.   

    http://blog.csdn.net/chjjo/article/details/4649643这个是我想要的, 楼上你的这个感觉不是我要的  还是我看不懂
      

  6.   


    declare @t nvarchar(10)
    declare @sql nvarchar(1000)
    set @t='tmp' --要创建表的名
    set @sql='create table '+ @t +'(id int,name nvarchar(20))'
    exec(@sql)
      

  7.   


    DECLARE @sql VARCHAR(8000)
    SELECT * INTO #aaa FROM t1 AS a INNER JOIN t2 AS b ON a.fangshi=b.code
    --SELECT * FROM aaa
    SET @sql='select id'
    SELECT @sql=@sql+',max(case when name='''+name+''' then jine else 0.00 end) as ['+name+']'
    FROM (SELECT DISTINCT name FROM t2) AS abc
    SET @sql=@sql+' into t3 from #aaa group by id'
    PRINT @sql
    EXEC (@sql)
    DROP TABLE #aaaselect * from t3 --t3就是新创建的表