在 INSERTion 期间向 table 个值参数添加一个附加列

Add an additional column to table valued parameters during INSERTion

给出以下 table 类型:

/* Create a table type. */
CREATE TYPE TestType
   AS TABLE
      (someNumber      int,
       someOtherNumber int);
GO

我将此 table 类型传递给存储过程。在此存储过程中,我想将来自 TestType 的数据添加到 table dbo.someTable 中,并带有附加 ID someIdTestType 中的所有行都相同)。将 someId 添加到 TestType 中所有行的最佳方法是什么?

CREATE PROCEDURE dbo.Test @TVP TestType READONLY
AS
    BEGIN
    SET NOCOUNT ON

    DECLARE @someId int;
    SET @someId = 10;

    INSERT INTO dbo.someTable
        (someId,
         someNumber,
         someOtherNumber)
        VALUES
         -- here I want to add all rows from @TVP.
         -- However, @TVP only has the columns someNumber and someOtherNumber.
         -- The column someId is missing. What is the most efficient way
         -- to add the @someId to all rows during insert?
         -- Note that @someId shall be the same value for all rows in @TVP.
    END;
GO

只需 SELECT 来自 table 参数,并添加一个具有常量值的列:

INSERT INTO dbo.someTable (someId, someNumber, someOtherNumber)
SELECT @someId, someNumber, someOtherNumber 
FROM @TVP

这是最有效的方法。

CREATE PROCEDURE dbo.Test 
@TVP TestType READONLY
AS
    BEGIN
    SET NOCOUNT ON

    DECLARE @someId int;
    SET @someId = 10;

    INSERT INTO dbo.someTable
        (someId,
         someNumber,
         someOtherNumber)
        VALUES
          @SomeId
         ,SomeNumber
         ,SomeOtherNumber
    END;
GO