将一个表的字段值追加为另一个表的字段

hnsongbiao 2008-07-23 05:50:15
有2表,表TA,表TB,

TB表只有一个字段TZ,数据如下
TZ
0001
0002
0003
0004
....
....


现将TB表的这些字段值追加到TA中,成为TA的字段

用动态查询语句怎么实现?
...全文
87 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
wzy_love_sly 2008-07-23
  • 打赏
  • 举报
回复
7楼就是不知道有多少行,你加几列测试下就知道了
hnsongbiao 2008-07-23
  • 打赏
  • 举报
回复
如果不知道
TB表
TZ
001
002
003
004
....

到底有多少值,怎么用动态语句实现?
rhq12345 2008-07-23
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 wzy_love_sly 的回复:]
SQL codeif object_id('ta') is not null
drop table ta
go
create table ta(id CHAR(10))
insert into ta select '001'
insert into ta select '002'
insert into ta select '003'
insert into ta select '004'

if object_id('tb') is not null
drop table tb
go
create table tb(col int)
insert into tb select 1
insert into tb select 2
insert into tb select 3

declare @sql varchar(8000)
select @s…
[/Quote]
wzy_love_sly 2008-07-23
  • 打赏
  • 举报
回复
if object_id('ta') is not null
drop table ta
go
create table ta(id CHAR(10))
insert into ta select '001'
insert into ta select '002'
insert into ta select '003'
insert into ta select '004'

if object_id('tb') is not null
drop table tb
go
create table tb(col int)
insert into tb select 1
insert into tb select 2
insert into tb select 3

declare @sql varchar(8000)
select @sql=isnull(@sql+';','')+'alter table tb add ['+id+'] varchar(10)'
from ta group by id
exec(@sql)
set @sql=''
select @sql=@sql+'update tb set ['+id+']=''0'''
from ta group by id
exec(@sql)

select * from tb


col 001 002 003 004
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
wzy_love_sly 2008-07-23
  • 打赏
  • 举报
回复
早说啊
hnsongbiao 2008-07-23
  • 打赏
  • 举报
回复
您可能理解错了我的意思,
比如TA表为

ID NAME
1 zhang
2 wang

TB表为
TZ
001
002
003
004
....

现在要将001,002,003 加入到TA中,成为TA的字段,字段值值为0 如

ID NAME 001 002 003 .........
1 zhang 0 0 0 0 0 0
2 wang 0 0 0 0 0 0


wzy_love_sly 2008-07-23
  • 打赏
  • 举报
回复
create table tb(id CHAR(10) default dbo.getid(),name varchar(20))

create function getid()
returns varchar(10)
as
begin
declare @id varchar(10)
select @id=right('000'+ltrim(isnull(max(id),0)+1),4) from tb with(tablockx)
return @id
end

insert into tb(name) select 'a'
insert into tb(name) select 'b'
insert into tb(name) select 'c'

select * from tb


id name
0001 a
0002 b
0003 c

写个函数,以后就会取最大加1了
wzy_love_sly 2008-07-23
  • 打赏
  • 举报
回复
这就行了,有多少值都会自动加上去的、、
改成4就是0001,0002,你可以自己控制长度


update tb set col2=right('00'+ltrim(col3),4)
hnsongbiao 2008-07-23
  • 打赏
  • 举报
回复
因为不知道TZ具体有多少个值,请用动态SQL实现
wzy_love_sly 2008-07-23
  • 打赏
  • 举报
回复
create table tb(col1 CHAR(1))
insert into tb select 'A'
insert into tb select 'A'
insert into tb select 'A'

alter table tb add col2 varchar(20)

alter table tb add col3 int identity(1,1)

update tb set col2=right('00'+ltrim(col3),3)

alter table tb drop column col3

select * from tb


col1 col2
A 001
A 002
A 003

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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