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

字段替换的三种实现

棉花糖ONE 发布于 2007-04-02 11:38, 603 次点击

要求把表b的数字改成表a对应id的name
if object_id('a') is not null
drop table a
go
create table a( id int,name varchar(10))
insert into a select 1,'a'
insert into a select 2,'b'
insert into a select 3,'c'
insert into a select 4,'d'
go
if object_id('b') is not null
drop table b
go
create table b(id1 int,id2 int)
insert into b select 1,2
insert into b select 3,4
go

select * from a
select * from b

create function dbo.fn(@id int)
returns nvarchar(10)
as
begin
declare @name nvarchar(10)
select @name=name from a where id=@id
return @name
end
go

select dbo.fn(id1) as name1,dbo.fn(id2) as name2 from b
Result
name1 name2
---------- ----------
a b
c d

(所影响的行数为 2 行)

select (select name from a where id=id1) as name1,(select name from a where id=id2) as name2 from b
Result
name1 name2
---------- ----------
a b
c d

(所影响的行数为 2 行)
select a1.name as name1,a2.name as name2 from a a1,a a2,b where a1.id=b.id1 and a2.id=b.id2
Result
name1 name2
---------- ----------
a b
c d


(所影响的行数为 2 行)


drop table a
go
drop tabl b

[此贴子已经被作者于2007-4-2 13:52:12编辑过]

7 回复
#2
棉花糖ONE2007-04-02 12:34

没人顶

#3
bygg2007-04-02 12:48
#4
songyuyu2007-04-02 13:38
心情不好
不想顶
#5
星梦缘2007-04-02 14:15

辛苦拉..斑竹

#6
xiyou4192007-04-02 21:04
受教了,棉花~~~~~~~~~
#7
帅哥一条虫2007-04-02 23:20
#8
Silent欢欢2007-05-09 09:38
不懂
1