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

现要建立一存储过程(Proc_OldTable)。要求如下:建立一个sql表(SQL_Server 2005)表名为OldTable.
内含有字段:序号 smallint identity(1,1) Primary key ,考号 varchar(12) null ,班级 smallint not null ,学号 smallint not null,姓名 varchar(10) not null。另外从 Subject表中获取科目(如语文、数学等)作为新建的 OldTable表的字段。(位于姓名之后。全部为 smallint null 科目顺序为按序号升序)Subject表中科目不是固定的。Subject的字段为(序号,科目,满分,优秀,良好,及格,是否计入总分)。请各路高手帮忙,先谢谢你们!

第1个回答  2021-12-20

如果两表字段相同,则可以直接这样用。
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个回答  推荐于2016-10-10
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

追问

exec proc_OldTable
消息 102,级别 15,状态 1,第 8 行
'go' 附近有语法错误。
消息 102,级别 15,状态 1,第 10 行
'int' 附近有语法错误。

追答
drop procedure Proc_OldTable
go

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
   ;
   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

追问

语句没问题,exec 执行也可以通过。但与要求有一点距离。(科目顺序为按序号升序)。你这句 select distinct 科目 from Subject 没有按要求升序。我自己加上Order by 序号 提示错误:除非另外还指定了 TOP 或 FOR XML,否则,ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效

追答set @subject = ''
    select @subject = @subject + ',' + 科目 + ' int '
    from ( select distinct 序号,科目 from Subject表 ) a order by 序号
    
    这部分这样改一下,应该就可以了。

本回答被提问者和网友采纳
相似回答