在多个表中插入 SQL Server 存储过程

SQL Server stored procedure to insert in multiple tables(在多个表中插入 SQL Server 存储过程)
本文介绍了在多个表中插入 SQL Server 存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个表,custlogincustinfo:

I have 2 tables, custlogin and custinfo:

客户登录:

custid int primary key auto notnull
custusename varchar(25)
custpassword varchar(50)

客户信息:

custid foriegnkey custlogin.custid ondelete set NULL
custfirstname varchar(25)
custlastname  varchar(25)
custaddress   varchar(100)

我想写一个存储过程来插入两个表

I want to write a stored procedure which will insert into both tables

更准确地说,使用 custusername custpassword 插入 custlogin,这将返回 custid 以用作 custinfo.

More precisely, insert into custlogin with custusername custpassword, which would return custid for use as foreign key for custinfo.

我搜索了很多,但没有找到任何解决方案.

I have searched much but I didn't find any solution.

推荐答案

如下所示.在这种情况下,您可以使用 SCOPE_IDENTITY() 来获取最后一个自动生成的 ID,其范围是这个存储过程:

It will be something like below. You can use SCOPE_IDENTITY() to get the last autogenerated ID withing the scope which is this stored proc in this case:

create procedure NameOfYourProcedureHere
as
begin
SET NOCOUNT ON;
SET XACT_ABORT ON;

    insert into custlogin(custusename, custpassword) 
        values ('','') -- put values here (from parameters?)

    insert into custinfo(custid, custfirstname, custlastname, custaddress)
        values (SCOPE_IDENTITY(), '', '', '')  -- put other values here (from parameters?)

SET NOCOUNT OFF;
SET XACT_ABORT OFF;
end

这篇关于在多个表中插入 SQL Server 存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)