動態關聯表

2021-04-14 11:31:27 字數 1013 閱讀 1329

--示例資料

create table [table](a sysname,b varchar(10))

insert [table] select 'table_1','a'

union  all     select 'table_2','b'

create table table_1(a int)

insert table_1 select 1

union  all     select 2

create table table_2(a int)

insert table_2 select 3

union  all     select 4

go/*--問題說明:

table中,a欄位儲存著其他表的名稱

a欄位中,記錄和各個表的a欄位的最大值

即得到如下結果:

table.b   c

--------  -----------

a         1

b         2

--*/

--處理方法

declare @s varchar(8000)

set @s=''

select @s=@s+' when '''+a+''' then(select max(a) from ['+a+'])'

from [table] group by a

exec('select b,c=case a'+@s+' end from [table]')

go--刪除測試

drop table [table],table_1,table_2

/*--測試結果

動態關聯表

最後再說一句。我在老闆那裡看見這句話,忍不住與大家分享 我喜歡在這個地方工作 microsoft 過去有過許多競爭者。還好,我們有很多博物館來收藏它們。microsoft 董事長 bill gates,forbes.com,2004 年 10 月 4 日。shawn msdn online 總編輯 ...

動態關聯表

示例資料 createtable table asysname,bvarchar 10 insert table select table 1 a union all select table 2 b createtabletable 1 aint inserttable 1select1 unio...

動態關聯表

示例資料 create table table a sysname,b varchar 10 insert table select table 1 a union all select table 2 b create table table 1 a int insert table 1 sele...