select a.*,b.* from a,b where a.id=b.id选出结果为(其中b表有很多字段)
id 单号 姓名 年龄 ......我想选出这样的结果,让单号放在选出的最前面,我这样写的语句
select b.单号,a.*,b.* from a,b where a.id=b.id结果:
单号 id 单号 姓名 年龄 ......请问如何不让b.*中不在选出 单号 字段?想要的排列:
单号 id  姓名 年龄 ......

解决方案 »

  1.   

    select b.单号,a.*,b.姓名,b.年龄,... from a,b where a.id=b.id
    --B的 除单号列 都指定出来
      

  2.   

    那就动态获取b表列名,然后拼接字符串
    declare @sql nvarchar(1000)
    select @sql=isnull(@sql+',','')+name from syscolumns where id=object_id('b表')
      

  3.   


    declare @sql nvarchar(max)
    set @sql = N'select a.*'+
    ltrim(isnull((select ','+name from sys.columns b
    where object_id = object_id('dbo.tableB', 'u')
    and not exists
    (
    select 1
    from sys.columns a
    where object_id = object_id('dbo.tableA', 'u')
    and b.name = a.name
    )   
    for xml path('')),''))
    +' from a,b where a.id=b.id'--select @sql
    exec(@sql)
      

  4.   


    use Test
    if OBJECT_ID('A') is not null 
    drop table A
    create table A(id int identity(1,1),col_1 nvarchar(20),col_2 nvarchar(20))
    goinsert into A(col_1,col_2)
    select 'AAA','AAA1' union all
    select 'BBB','BBB1' union all
    select 'CCC','CCC1' if OBJECT_ID('B') is not null 
    drop table B
    create table B(id int identity(1,1),单号 nvarchar(20),col2 nvarchar(20),col3 nvarchar(20),col4 nvarchar(20))
    goinsert into B(单号,col2,col3,col4)
    select 'A001','A1','A2','A3' union all
    select 'B001','B1','B2','B3' union all
    select 'C001','C1','C2','C3' declare @sql nvarchar(2000)
    select @sql=isnull(@sql+',','')+'b.'+name from syscolumns where id=object_id('B') and name<>'单号'
    set @sql='select a.*,b.单号,'+@sql+' from a,b where a.id=b.id'
    exec(@sql)