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

现要建立一存储过程(Proc_OldTable)。要求如下:建立一个sql表(SQL_Server2005)表名为OldTable.内含有字段:序号smallintide... 现要建立一存储过程(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的字段为(序号,科目,满分,优秀,良好,及格,是否计入总分)。请各路高手帮忙,先谢谢你们!
展开
 我来答
zyilooog
2021-12-20 · 超过50用户采纳过TA的回答
知道小有建树答主
回答量:338
采纳率:100%
帮助的人:9.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条件

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
射手幽灵伊
推荐于2016-10-10 · TA获得超过2714个赞
知道大有可为答主
回答量:4955
采纳率:81%
帮助的人:1906万
展开全部
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
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式