update问题

filebat 2005-06-19 02:45:14
现有数据库中有三张表table1, table2, table3
模式:
table1( id, col11, col12) (其中id为主键, 所有列都为int型)
table2( id, col21, col22, col23)(其中id为主键, 所有列都为int型)
ta( table_name, colname, keyword, value)
table_name存放着数据库中的表名(只可能为table1或table2)。 colname存放着table_name表的列名(除主键id外)。 keyword为该表中的主键值。 value为表名table_name的值的表中,主键值为keyword的记录的colname列的值

数据:
table1:
id col11 col12
1 2 3
table2:
id col21 col22 col23
2 4 1 5
ta
table_name colname keyword value
table1 col11 1 null
table1 col12 2 null
table2 col21 2 null
table2 col22 2 null
table2 col23 2 null

要求:按要求更新value的值。
说明:table1表的列和table2表的列是预先不知道的(即table1表可能还有col13, col14等, table2表亦然)。
...全文
85 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
filebat 2005-06-19
  • 打赏
  • 举报
回复
我只是陈述一个事实了.
不带感情色彩.

btw, 游标很费资源的
vivianfdlpw 2005-06-19
  • 打赏
  • 举报
回复
不会用其他的:(
多多指教哦~~~~~~~~~
Well 2005-06-19
  • 打赏
  • 举报
回复
TO: filebat(Mark)
每個人有每個的風格嗎。

就拿我來說吧。游标還不會用呢

我一直都是用存儲過程呢
filebat 2005-06-19
  • 打赏
  • 举报
回复
to vivianfdlpw():发现你好喜欢用游标哦,
以前看过一张贴子,你也是用游标的.
vivianfdlpw 2005-06-19
  • 打赏
  • 举报
回复
if exists(select * from sysobjects where id=object_id('table1'))
drop table table1
go

if exists(select * from sysobjects where id=object_id('table2'))
drop table table2
go

if exists(select * from sysobjects where id=object_id('ta'))
drop table ta
go

set nocount on
go
create table table1(id int primary key,col11 int,col12 int)
create table table2(id int primary key,col21 int,col22 int,col23 int)
create table ta
(
id int identity,
table_name varchar(20),
colname varchar(20),
keyword int,
value int
)

insert table1 select 1,2,3
insert table2 select 2,4,1,5
insert ta(table_name,colname,keyword,value)
select 'table1','col11',1,null union all
select 'table1','col12',1,null union all
select 'table2','col21',2,null union all
select 'table2','col22',2,null union all
select 'table2','col23',2,null

--select * from ta

declare @ID int,@table_name varchar(20),@colname varchar(20),@keyword int
declare @sql nvarchar(200)
declare cur cursor for
select id,table_name,colname,keyword from ta
open cur
fetch next from cur into @ID,@table_name,@colname,@keyword
while @@fetch_status=0
begin
set @sql=N' update ta set value=(select '+@colname+
N' from '+@table_name+
N' where id='+cast(@keyword as nvarchar)+
N' )'+
N' where ID='+cast(@ID as nvarchar)
--print(@sql)
exec(@sql)
fetch next from cur into @ID,@table_name,@colname,@keyword
end
close cur
deallocate cur

select * from ta

drop table table1
drop table table2
drop table ta

结果:

id table_name colname keyword value
----------- -------------------- -------------------- ----------- -----------
1 table1 col11 1 2
2 table1 col12 1 3
3 table2 col21 2 4
4 table2 col22 2 1
5 table2 col23 2 5
filebat 2005-06-19
  • 打赏
  • 举报
回复
hello, is there anybody here?
filebat 2005-06-19
  • 打赏
  • 举报
回复
怎么排版乱了!
欢迎指点

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧