无法使用 table 值参数插入 table
Trouble inserting into table with table valued parameter
我创建了一个 table 类型:
CREATE TYPE int_array AS TABLE (n INT NOT NULL)
并希望使用它在单个过程中将多行插入以下 table:
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
我做错了什么?
您不能在插入中混合使用标量值和 select 语句。您需要将标量值设为 select 中的一列。像这样。
CREATE PROCEDURE test(
@value INT,
@array int_array readonly
)
AS
BEGIN
INSERT INTO myTable
(
Id_SecondTable
, Id_ThirdTable
)
SELECT @value
, n
FROM @array
END
我创建了一个 table 类型:
CREATE TYPE int_array AS TABLE (n INT NOT NULL)
并希望使用它在单个过程中将多行插入以下 table:
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
我做错了什么?
您不能在插入中混合使用标量值和 select 语句。您需要将标量值设为 select 中的一列。像这样。
CREATE PROCEDURE test(
@value INT,
@array int_array readonly
)
AS
BEGIN
INSERT INTO myTable
(
Id_SecondTable
, Id_ThirdTable
)
SELECT @value
, n
FROM @array
END