注册 登录
编程论坛 SQL Server论坛

关于更新表的问题?

olderdream 发布于 2009-07-16 11:06, 663 次点击
想用下面的语句更新test表,可是不成功,红色部分出错,出现错误提示-----必须声明变量 '@mytable'。
请高手帮忙看看。多谢


declare @mytable table ([no] char(10),[score] char(10))
insert into @mytable
select '1','1298' union all
select '2','1298' union all
select '3','1297' union all
select '4','1298'

update test set score =(select score from @mytable )
where test.no=@mytable.no


test表结构
no    score
1    a
2    b
3    c
4    d
5    e
5 回复
#2
olderdream2009-07-16 17:58
请高手指点
#3
球球2009-07-17 13:48
不知道你要做什么
#4
olderdream2009-07-17 14:14
建一个虚表“mytable”,并在其中insert into数据

之后,根据虚表的内容去更新数据库中的表test(把test中字段score更新---根据no字段)
#5
happynight2009-07-17 17:00
declare @mytable table ([no] char(10),[score] char(10))
insert into @mytable
select '1','1298' union all
select '2','1298' union all
select '3','1297' union all
select '4','1298'
--SELECT * FROM @mytable
--DROP TABLE #lS1
Create table #ls1 ([no] varchar(10),score varchar(10))

update #ls1 set score =a.score
from @mytable a
where #ls1.no=a.no
---------------------------------
还真没写过你这样的代码 在后面更新的话 确实必须要给表取别名 否则会出你那样的错误 另外 更新的写法 我比较习惯上面的方式 如果按照你的习惯的话 应该写成下面的样式
update #ls1 set score =(select score from @mytable a where #ls1.no=a.no)
#6
olderdream2009-07-17 17:40
回复 5楼 happynight
谢谢,搞定了。正对我的内容,如下:
declare @mytable table ([no] char(10),[score] char(10))
insert into @mytable
select '1','1298' union all
select '2','1298' union all
select '3','1297' union all
select '4','1298'

update test set score=a.score from  @mytable a where test.no=a.no
1