Conditional insert

  • Hi,

    Can i pass an insert query based on a condition??

  • You can see this in the Books Online:

    INSERT INTO schema.table (columnlist)

    SELECT ...

    FROM ...

    WHERE ....

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

  • Hi Grant,

    Thanks for the reply...

    I would like to know if we can include a case statement in an insert operation.

  • vaidyanathan_kalyanasundaram (4/3/2008)


    Hi Grant,

    Thanks for the reply...

    I would like to know if we can include a case statement in an insert operation.

    [font="Verdana"]Obviously.

    Insert Into {Table} {Col1, Col2}

    Select Col1, {Case When Col2 = {Condition} Then {expr1} Else {expr2} End} From {Table} Where {Where Criteria}

    For more information use BOL

    Thanks,

    Mahesh[/font]

    MH-09-AM-8694

  • Thanks mahesh for your reply.

  • Mahesh beat me to it.

    Once you realize that the INSERT...SELECT mechanism is just a SELECT statement, pretty much anything possible within the SELECT statement can be used with the INSERT statement. I'm sure there are exceptions to that, but none are coming to mind immediately.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

  • [font="Verdana"]

    Grant Fritchey (4/4/2008)


    Mahesh beat me to it.

    Once you realize that the INSERT...SELECT mechanism is just a SELECT statement, pretty much anything possible within the SELECT statement can be used with the INSERT statement. I'm sure there are exceptions to that, but none are coming to mind immediately.

    Then kindly do let us know, as we might unaware with them.

    Thanks in advance,

    Mahesh[/font]

    MH-09-AM-8694

  • Sorry, I stated that badly. I'm not aware of any exceptions.

    The one thing that might be an exception would be that the SELECT statement can only return the same number of columns, in the same order, that the INSERT statement expects them in.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

Viewing 8 posts - 1 through 7 (of 7 total)

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