can I have subquery in INSERT statement

  • Howdy folks,

    The following statement runs when hard-coded with a number:

    INSERT INTO tblProduct

    (productId, productCatId)

    VALUES

    (@productId, 2)

    however, I'd like the second value to be the result of a subquery, as follows:

    INSERT INTO tblProduct

    (productId, productCatId)

    VALUES

    (@productId, SELECT prodCatId FROM tblProductCategory WHERE columNameValue= @columNameValue)

    ..I get error "Incorrect syntax near the keyword 'SELECT'"

    I have correctly initialised all the parameters that I passed.

    Can anyone point me in the right direction?

    Many thanks,

    yogi

  • 
    
    INSERT INTO tblProduct (productId, productCatId)
    SELECT @productId, prodCatId
    FROM tblProductCategory
    WHERE columNameValue = @columNameValue

    --Jonathan



    --Jonathan

  • Cheers Jonathan,

    It seems that it's better to write insert queries the way you've done it.Was the way I was doing it an older style?

    Ta,

    yogi

  • No Yogiberr.

    It is not an older stíle, it is just and another syntax.

    If you check the BOL you can see that EITHER you assign values OR you assign select results to a table.

    Bye

    Gabor



    Bye
    Gabor

  • Hi Gabor,

    thanks bud, i think i'll stick to the "SELECT subquery" version.

    cheers,

    yogiberr

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply