我正在编写一个在insert语句中有多个select语句的查询
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语句只返回一个值。
答案 0 :(得分:7)
只需将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
,但这会产生不同的错误消息:子查询返回了多个值。
答案 1 :(得分:0)
错误信息正确,因为
SELECT SupplierID FROM dbo.Suppliers WHERE CompanyName = 'Lyngbysild'
可以(技术上)返回多行,它应该在列中显示哪一行?
如果您知道此子查询只返回一行,那么告诉数据库采取第一行。
SELECT TOP 1 SupplierID FROM dbo.Suppliers WHERE CompanyName = 'Lyngbysild'