日期:2014-05-17  浏览次数:20434 次

???请问,如何屏蔽重复选出的字段呢???
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  姓名 年龄 ......

------最佳解决方案--------------------

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)

------其他解决方案--------------------

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))
go

insert 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))
go

insert 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) 

------其他解决方案--------------------
建议,你把你要搜索的字段一个一个写出来,这样不会重复,而且速度要快过*方式
------其他解决方案--------------------
select b.单号,a.*,b.姓名,b.年龄,... from a,b where a.id=b.id
--B的 除单号列 都指定出来
------其他解决方案--------------------
不要用a.*,b.*   麻烦点,一个一个的写出用的着的
------其他解决方案--------------------
我也知道楼上两位说的方法,可我这里的b.* 是动态生成的,字段不确定很多,但一定有 单号 字段,楼上的方法在此处行不通哦!
------其他解决方案--------------------
引用:
我也知道楼上两位说的方法,可我这里的b.* 是动态生成的,字段不确定很多,但一定有 单号 字段,楼上的方法在此处行不通哦!

那就动态获取b表列名,然后拼接字符串
declare @sql nvarchar(1000)
select @sql=isnull(@sql+',','')+name from syscolumns where id=object_id('b表')
------其他解决方案--------------------
你试试在动态里面指定,或者再在外围筛选