0

I'm trying to use a sql command like this but it's not working for some obvious reasons.Can you tell me what's the way out for this type of commands ?

   INSERT INTO ContentToGroup(ContentId,ClassSectionId)  
   VALUES (16, Select ClassSectionId from ClassSectionMaster where ClassId=1)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Naresh
  • 657
  • 3
  • 16
  • 35

4 Answers4

4
INSERT INTO ContentToGroup (ContentId,ClassSectionId)
Select 16, ClassSectionId
from ClassSectionMaster
where classid = 1
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
amit_g
  • 30,880
  • 8
  • 61
  • 118
2

You cannot mix the INSERT .... VALUES.... with "inline" select statements. Using the VALUES keyword, you must provide all values as literals or SQL variables.

Either you need to select the value first and assign it to a variable:

DECLARE @ClassSectionID INT

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

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

or then use the SELECT statement others have shown to provide all values (and then you omit the VALUES keyword)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
2
INSERT INTO ContentToGroup(ContentId,ClassSectionId) Select 16, ClassSectionId from ClassSectionMaster where ClassId=1
Pankaj Agarwal
  • 11,191
  • 12
  • 43
  • 59
1

First you need to remove the VALUES when you are using an nested query. Also try specifying the table names in front of the field name in case that is causing your ambiguity.

INSERT INTO ContentToGroup(ContentId,ClassSectionId) 
    SELECT 16, ClassSectionMaster.ClassSectionId 
    FROM ClassSectionMaster 
    WHERE ClassSectionMaster.ClassId=1
Ben
  • 1,525
  • 11
  • 19
  • I think SO should have an "x people currently answering" displayed somewhere. Since we all posted nearly the same answer – Ben Jun 20 '11 at 06:07