Inserting with Select

Discussion in 'Databases' started by qazwsxed, Apr 5, 2011.

  1. #1
    Say I have a query that inserts using a select as such:

    Code:

    INSERT INTO courses name, location, gid SELECT (name, location, gid) FROM courses WHERE cid = $cid

    Is it possible to only select "name,location" for the insert, and set gid to something else in the query?

    Thanks in advance
     
    qazwsxed, Apr 5, 2011 IP
  2. randheer

    randheer Greenhorn

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #2
    You can do it in different ways as specified below…

    You can declare a variable and provide @var in place of GID in select statement

    Declare @var varchar (100)
    Iset @var = ‘value’

    INSERT INTO courses name, location, gid SELECT (name, location, @var) FROM courses WHERE cid = $cid

    You can send any static value in place of GID in select statement like below example…

    INSERT INTO courses name, location, gid SELECT (name, location, ‘Value’) FROM courses WHERE cid = $cid

    You can write a select statement in select statement for getting GID value

    INSERT INTO courses name, location, gid SELECT (name, location, (select x from y )) FROM courses WHERE cid = $cid


    You want to do it separately than it will be a update statement after insert statement

    these all queries are in TSQL
     
    randheer, Apr 5, 2011 IP
  3. sd3189541

    sd3189541 Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This is really good example.
     
    sd3189541, Apr 5, 2011 IP
  4. aman_gcs

    aman_gcs Member

    Messages:
    178
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    26
    #4
    Thanks for sharing the information.
     
    aman_gcs, Apr 22, 2011 IP
  5. omeslawanya

    omeslawanya Peon

    Messages:
    69
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    yes this is possible..
     
    omeslawanya, Jun 22, 2011 IP