【问题标题】:SQL Server stored procedure to insert in multiple tables a [duplicate]SQL Server存储过程在多个表中插入[重复]
【发布时间】:2017-10-03 08:54:36
【问题描述】:

我有 2 张桌子,custlogincustinfo

客户登录:

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)

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

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

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

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    如果您向custlogin 插入1 行,您可以使用@@IDENTITYScope_identity() 来获取新插入的id。

    如果插入多行,则使用OUTPUT 获取多个新插入的id。

    你可以在这里看到一个例子:http://rextester.com/TWXO81648

    【讨论】:

    【解决方案2】:

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

    create procedure NameOfYourProcedureHere
    as
    begin
    
        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?)
    
    end
    

    【讨论】:

    • 您在提出问题 1 分钟后回答了自己的问题?嗯...闻起来像不对劲
    猜你喜欢
    • 1970-01-01
    • 2022-08-22
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    相关资源
    最近更新 更多