在 INSERTion 期间向表值参数添加额外的列

问题描述

给定以下表格类型:

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

我将此表类型传递给存储过程。在此存储过程中,我想将 TestType 中的数据添加到表 someId 中,并带有附加 ID TestType(对于 dbo.soMetable 中的所有行都相同)。将 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,并添加具有常量值的列:

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