sql存储过程从一张表中查询到的值作为另一张表的新的字段

2025-03-03 20:59:11
推荐回答(2个)
回答1:

如果两表字段相同,则可以直接这样用。
insert into table_a select * from table_b
如果两表字段不同,a表需要b中的某几个字段即可,则可以如下使用:
insert into table_a(field_a1,field_a2,field_a3) select field_b1,field_b2,field_b3 from table_b
还可以加上where条件

回答2:

create procedure Proc_OldTable
as
begin
declare @subject varchar(max)
declare @sql varchar(max)

set @sql = '

if exists (select 1
            from  sysobjects
           where  id = object_id(''OldTable'')
            and   type = ''U'')
   drop table OldTable
   go
   create table OldTable ( 序号 smallint identity(1,1) Primary key ,考号 varchar(12) null ,
 班级 smallint not null ,学号 smallint not null,姓名 varchar(10) not null '

set @subject = ''
select @subject = @subject + ',' + 科目 + ' int '
from ( select distinct 科目 from Subject表 ) a

set @sql = @sql + @subject
exec (@sql)
end