【问题标题】:how to write more than one insert statements in stored procedure with two table parameters如何在具有两个表参数的存储过程中编写多个插入语句
【发布时间】:2013-01-23 11:44:59
【问题描述】:

我有两张桌子

Employee---->Id(identity),FN,LN,Address

EmpContact--->Id(identity),Empid(Above table identity value),ContactType,ContactNumber

如何在单个存储过程中编写两个表插入语句。第二个表“EmpContact”需要插入第一个表“Employee”中产生的身份 ID

【问题讨论】:

  • 这很好。你试过了吗? - 你有什么问题?另外,您使用的是什么数据库系统?

标签: sql stored-procedures asp-classic


【解决方案1】:

你需要的是 SCOPE_IDENTITY() 函数,它返回一个范围内的最后一个 ID

insert into Employee(FN,LN, Adress)
values(@var1, @var2, @var3)

declare @EmpID int 
set @EmpID = SCOPE_IDENTITY()

insert into EmpContact(Empid, ContactType, contactNumber)
values(@EmpID, @var4, @var5)

【讨论】:

    【解决方案2】:

    ummm...答案很简单,只要写一个带有错误处理等的程序就可以了。

    create procedure dbo.myProc
    @param
    
    insert into dbo.Employee(FN,LN,Address)
    select @value1, @value2, @value3
    
    insert into dbo.EmpContact(Empid,ContactType,ContactNumber)
    select ID,@value4, @value5
    from dbo.Employee
    
    go
    

    【讨论】:

    • 每当有人调用此过程时,它都会将整个 Employee 表插入到 EmpContact 中
    • 是的,除了“插入 2 个表的过程”之外,问题没有指定任何内容——这就是它的作用。
    【解决方案3】:

    假设您的未知字段作为参数传入:

    在您的存储过程中...

    DECLARE @EmployeeID BIGINT --Or whatever datatype you are using
    
    INSERT INTO Employee
        (FN, LN, Address)
    VALUES
        (@FN, @LN, @Address)
    
    SET @EmployeeID = SCOPE_IDENTITY()  --This is probably the line you are looking for
    
    INSERT INTO EmpContact
        (Empid, ContractType, ContractNumber)
    VALUES
        (@EmployeeID, @ContractType, @ContractNumber)
    

    【讨论】:

      【解决方案4】:
      create proc yourproc
      (
         -- parameter definitions here
      )
      as
      begin
              insert into Employee
              (FN,LN,Address) 
              values 
              (@FN,@LN,@Address)
      
      declare @EmployeeID int 
      set @EmployeeID = SCOPE_IDENTITY()
      
              insert into EmpContact
              (Empid, ContactType, ContactNumber) 
              values 
              (@EmployeeID, @ContactType, @ContactNumber) 
      end
      

      SCOPE_IDENTITY 和 @@IDENTITY 返回最后一个身份值 在当前会话的任何表中生成。但是,SCOPE_IDENTITY 返回仅在当前范围内插入的值; @@IDENTITY 是 不限于特定范围。

      SCOPE_IDENTITY (Transact-SQL) - MSDN

      【讨论】:

        【解决方案5】:

        您可以使用原始插入的东西,但是您可以使用SCOPE_IDENTITY()在第一个表中插入的标识ID,它返回为当前会话和当前范围内的任何表生成的最后一个标识值。

        【讨论】:

          猜你喜欢
          • 2012-05-14
          • 2023-04-09
          • 1970-01-01
          • 1970-01-01
          • 2021-07-06
          • 1970-01-01
          • 2011-12-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多