首页 > 解决方案 > 使用表值参数插入表时遇到问题

问题描述

我创建了一个表类型:

CREATE TYPE int_array AS TABLE (n INT NOT NULL)

并希望使用它将单个过程中的多行插入下表:

CREATE TABLE myTable
(
    Id_SecondTable INT NOT NULL,
    Id_ThirdTable  INT NOT NULL,

    CONSTRAINT PK_myTable 
        PRIMARY KEY (Id_SecondTable, Id_ThirdTable),
    CONSTRAINT FK_Id_SecondTable 
        FOREIGN KEY (Id_SecondTable) REFERENCES SecondTable (Id),
    CONSTRAINT FK_Id_ThirdTable 
        FOREIGN KEY (Id_ThirdTable) REFERENCES ThirdTable (Id)
)

我的程序如下:

CREATE PROCEDURE test 
     (@value INT, 
      @array int_array READONLY)
AS 
BEGIN
    INSERT INTO myTable 
    VALUES (Id_SecondTable, Id_ThirdTable) (@value, SELECT n FROM @array)   
END 

我究竟做错了什么?

标签: sql-servertable-valued-parameters

解决方案


您不能在插入中混合使用标量值和选择语句。您需要将标量值改为选择中的列。像这样。

CREATE PROCEDURE test(
@value INT, 
@array int_array readonly 
)
AS 
BEGIN

INSERT INTO myTable 
(
    Id_SecondTable
    , Id_ThirdTable
) 
SELECT @value
    , n 
FROM @array
END 

推荐阅读