關於樹形結構的表與另外乙個表的連線查詢

2021-04-09 08:51:44 字數 2939 閱讀 2720

--

建立單位資訊表i_sys_unitinfo

ifexists

(select

name 

from

sysobjects 

where

name='

i_sys_unitinfo')

drop

table

i_sys_unitinfo

gocreate

table

i_sys_unitinfo

(ui_id 

intidentity(1

,1

) not

null

primary

key,

--單位id

ui_shortname 

varchar(20

) not

null,--

單位名稱

p_ui_id 

intnot

null,--

所屬單位id

ui_optmark 

intnot

null

default1,

--操作標記:0刪除,1新增,2修改

ui_optid 

intnot

null

default0,

ui_opttime 

datetime

notnull

default

getdate

(),)

go--

建立員工檔案表i_hr_employeearchives

ifexists

(select

name 

from

sysobjects 

where

name='

i_hr_employeearchives')

drop

table

i_hr_employeearchives

gocreate

table

i_hr_employeearchives

(ea_id 

intidentity(1

,1

) not

null

primary

key,

--檔案id

ea_ui_id 

intnot

null,--

所屬部門

ea_name 

varchar(50

) not

null,--

員工姓名

ea_optmark 

intnot

null

default1,

--操作標記:0刪除,1新增,2修改

ea_optid 

intnot

null

default0,

ea_time 

datetime

notnull

default

getdate

(),)

go--查詢屬於編號為1的單位下的所有的員工

--定義要查詢的單位

declare

@uid

intset

@uid=1

as--

得到所有屬於1的單位

declare

@ttable

(ui_id 

int, 

level

int)

declare

@lint

set@l=0

insert

@tselect

ui_id, 

@lfrom

i_sys_unitinfo

where

ui_id 

=@uid

while

@@rowcount

>

0begin

set@l=@l

+1

insert

@tselect

a.ui_id, 

@lfrom

i_sys_unitinfo a, @tb

where

a.p_ui_id 

=b.ui_id

andb.

level=@l

-1

end--

統計select

distinct

h.ea_id,h.ea_name,a.ui_shortname,h.ea_ui_id

from

(select

aa.ui_id,aa.ui_shortname

from

@ta,i_hr_employeearchives h,i_sys_unitinfo aa

where

a.ui_id

=h.ea_ui_id

anda.ui_id 

=aa.ui_id 

andh.ea_optmark

>

0and

aa.ui_optmark

>0)a

full

join

(select

aa.ui_id,aa.ui_shortname,h.ea_name,h.ea_ui_id,h.ea_id

from

@ta,i_hr_employeearchives h,i_sys_unitinfo aa

where

a.ui_id

=h.ea_ui_id

anda.ui_id 

=aa.ui_id 

andh.ea_optmark

>

0and

aa.ui_optmark

>0)h

ona.ui_id 

=h.ea_ui_id

order

byh.ea_ui_id

用乙個表的記錄更新另外乙個表

用table 1的address,phone number更新table 2的address,phone number,注意 1.set 後面加上要更新的列,有多個要更新的列時,加上多個列,2.where 後面加上table 1和table 2的關聯列,有多個關聯列時,加上多個列 3.rownum用...

根據乙個表的字段,更新另外乙個表的字段

update table a set latesttm u.tm,latestdata u.data from select from table b inner join select max tm newesttm from table b group by stcd v on drp.tm v...

把乙個表中的資料插入到另外乙個表中

1.在oracle中可以用下面兩種 01 create table newtable as select from oldtable 用於複製前未建立新錶newtable不存在的情況 02 insert into newtable select from oldtable 已經建立了新錶newtab...