使用存储过程插入多个记录 [英] Insert multiple records using stored procedure

查看:98
本文介绍了使用存储过程插入多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张桌子



emplyoee(第一张桌子)

id主键自动增量

emp_name varchar



学生(第二张桌子)

id foriegnkey emplyoee.id

st_name varchar



i希望为单个员工ID插入多个学生记录。我的代码附在此处,但这只用于一个学生记录update.how我可以为这个需求编写存储过程。

i是SQL服务器和存储过程的新手,请你帮帮我。 br $>


I have two tables

emplyoee (first table)
id primary key auto increment
emp_name varchar

student(second table)
id foriegnkey emplyoee.id
st_name varchar

i want to insert multiple student records for a single employe id . My code is attached here , but this use to only one student record update.how can i write stored procedure for this need.
i am new with SQL server and stored procedure , could you please help me.

create procedure  empst_Sp
@emp_name varchar(50),
@st_name varchar(50)
as
begin
insert into emplyoee (emp_name) values (@emp_name)
insert into student(id,st_name) values(SCOPE_IDENTITY(),@st_name)
end

推荐答案





我认为你有一个列表的数据表,你只需要一个员工ID。



你可以查看这个链接这是关于如何将数据表发送到存储过程。



您可以使用该文章的帮助,并将员工详细信息作为文章中指定的简单参数和学生详细信息发送(作为XMl文件)。
Hi,

I think you have a data table for the list which you to save along with only one employee id.

You can check this link It is about how you can send datatable to stored procedure.

you can use help from that article and send employee details as simple parameter and student details as specified in the article(as XMl file).


Not确定以下所有语法是否适用于SQL2000。

解决方案是将学生名称列表作为XML传递到存储过程中,并更新INSERT语句以插入多个记录。



Not sure if all the syntax below works with SQL2000.
The solution is to pass a list of Student Names as XML into the Stored Procedure, and update the INSERT statement to insert multiple records.

DECLARE @students TABLE (st_name VARCHAR(50));
DECLARE @students_xml XML;
INSERT @students
    SELECT 'Michael'
    UNION
    SELECT 'Bob'

-- Convert table into an XML
SET @students_xml =
    (
        SELECT *
        FROM @students AS student
        FOR XML AUTO, ROOT('students')
    );

-- Parse the XML to a table
SELECT
    Tbl.Col.value('@st_name', 'varchar(50)') AS st_name
FROM @students_xml.nodes('//students/student') Tbl(Col)





此外,如果您使用的是SQL 2008及更高版本,则可以使用表值参数


这篇关于使用存储过程插入多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆