2011-06-20 34 views
0

我試圖使用這樣的sql命令,但它不工作的一些顯而易見的原因。你能告訴我這種類型的命令的出路是什麼?Sql insert command ambiguity

INSERT INTO ContentToGroup(ContentId,ClassSectionId) 
    VALUES (16, Select ClassSectionId from ClassSectionMaster where ClassId=1) 

回答

4
INSERT INTO ContentToGroup (ContentId,ClassSectionId) 
Select 16, ClassSectionId 
from ClassSectionMaster 
where classid = 1 
+0

+1。我進來第二次:) –

+0

謝謝先生!!!!!!! – Naresh

2

不能混淆的INSERT .... VALUES....與 「內聯」 SELECT語句。使用VALUES關鍵字,您必須提供所有值作爲文字或SQL變量。

要麼你需要首先選擇的值,並將其賦值給一個變量:

DECLARE @ClassSectionID INT 

SELECT @ClassSectionID = ClassSectionID 
FROM dbo.ClassSectionMaster WHERE ClassId = 1 

INSERT INTO ContentToGroup(ContentId,ClassSectionId) 
VALUES (16, @ClassSectionID) 

或再使用SELECT聲明其他人已經表明,以提供所有的值(然後你省略VALUES關鍵字)

2
INSERT INTO ContentToGroup(ContentId,ClassSectionId) Select 16, ClassSectionId from ClassSectionMaster where ClassId=1 
1

首先,您需要在使用嵌套查詢時刪除VALUES。也請嘗試在字段名稱前面指定表名,以防造成歧義。

INSERT INTO ContentToGroup(ContentId,ClassSectionId) 
    SELECT 16, ClassSectionMaster.ClassSectionId 
    FROM ClassSectionMaster 
    WHERE ClassSectionMaster.ClassId=1 
+0

我認爲SO應該有一個「x人正在回答」在某處顯示。因爲我們都發布了幾乎相同的答案 – Ben