日期:2014-05-17 浏览次数:20590 次
CREATE TABLE table_yuwen
(
table_id int,
table_chengji int,
table_type varchar(10)
)
INSERT INTO table_yuwen
select 1,70,'语文' union
select 2,80,'语文'
create table table_shuxue
(
table_id int,
table_chengji int,
table_type varchar(10)
)
insert into table_shuxue
select 1,70,'数学' union
select 2,90,'数学'
create table lock_table
(
lock_id int,
lock_table varchar(20), --表名
table_id int --表名id
)
insert into lock_table
select 1,'table_yuwen',1 union
select 2,'table_shuxue',1
/*
要求结果:
lock_id lock_table table_id table_type table_chengji
----------- -------------------- ----------- ---------- -------------
1 table_yuwen 1 语文 70
2 table_shuxue 1 数学 70
(2 行受影响)
*/
drop table table_yuwen
drop table table_shuxue
drop table lock_table
CREATE TABLE table_yuwen
(
table_id int,
table_chengji int,
table_type nvarchar(10)
)
INSERT INTO table_yuwen
select 1,70,N'语文' union
select 2,80,N'语文'
create table table_shuxue
(
table_id int,
table_chengji int,
table_type nvarchar(10)
)
insert into table_shuxue
select 1,70,N'数学' union
select 2,90,N'数学'
create table lock_table
(
lock_id int,
lock_table varchar(20), --表名
table_id int --表名id
)
insert into lock_table
select 1,'table_yuwen',1 union
select 2,'table_shuxue',1
declare @sql nvarchar(max)
select @sql=isnull(@sql,'')+stuff((select ' union all '+('select *,'''+lock_table+''' lock_table from '+lock_table+' where table_id='+ltrim(table_id)) from lock_table
for xml path('')),1,10,'')
select @sql='select lock_id,tt.* from lock_table t,('+@sql+')tt where t.table_id=tt.table_id and tt.lock_table=t.lock_table '
exec(@sql)
/*
lock_id table_id table_chengji table_type lock_table
----------- ----------- ------------- ---------- ------------
1 1 &n