2011-02-02 101 views
3

我寫它有多個SELECT語句在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語句只返回一個值。

回答

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,但會給出不同的錯誤信息:子查詢返回多個值。

+0

+1偉大的...謝謝 – Azhar 2011-02-02 14:53:38

0

錯誤信息是正確的,因爲

SELECT SupplierID FROM dbo.Suppliers WHERE CompanyName = 'Lyngbysild' 

能(技術上)返回多行,它應該在列中顯示哪一行?

如果你知道這個子查詢只返回一行,那麼告訴數據庫採取第一個。

SELECT TOP 1 SupplierID FROM dbo.Suppliers WHERE CompanyName = 'Lyngbysild' 
+0

仍然給出錯誤頂1 – Azhar 2011-02-02 14:32:42