gpt4 book ai didi

sql - Insert 语句中的多个 Select 语句出错

转载 作者:行者123 更新时间:2023-12-04 21:54:46 24 4
gpt4 key购买 nike

我正在编写一个在插入语句中有多个选择语句的查询

    INSERT INTO dbo.Products 
(ProductName,
SupplierID,
CategoryID,
UnitsInStock,
UnitsOnOrder,
ReorderLevel,
Discontinued)
VALUES
('Twinkies' ,
(SELECT SupplierID FROM dbo.Suppliers WHERE CompanyName = 'Lyngbysild'),
(SELECT CategoryID FROM dbo.Categories WHERE CategoryName = 'Confections'),
0,
0,
10,
0)

实际上它给出了错误

Msg 1046, Level 15, State 1, Line 4
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ','.

这两个 select 语句只返回一个值。

最佳答案

只需将 VALUES 更改为 SELECT 并删除外括号。

INSERT INTO dbo.Products 
(ProductName,
SupplierID,
CategoryID,
UnitsInStock,
UnitsOnOrder,
ReorderLevel,
Discontinued)
SELECT
'Twinkies' ,
(SELECT SupplierID FROM dbo.Suppliers WHERE CompanyName = 'Lyngbysild'),
(SELECT CategoryID FROM dbo.Categories WHERE CategoryName = 'Confections'),
0,
0,
10,
0

您可能还需要在子表达式上使用 TOP 1,但这会给出不同的错误消息:子查询返回了多个值。

关于sql - Insert 语句中的多个 Select 语句出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4875513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com