Home Forums SQL Server 2005 T-SQL (SS2K5) Manually increment smallint column during an INSERT command. RE: Manually increment smallint column during an INSERT command.

  • Generically you can use ROW_NUMBER for this.

    INSERT INTO SPEDDTL (spdd_f1, spdd_f2, spdd_f3, spdd_f4, spdd_f5, spdd_f6, spdd_f7)

    ( SELECT spd_f1, spd_f2, spd_f3, spd_f4, ROW_NUMBER() over (order by (select null)), spd_f6, spd_f7

    FROM SPED WHERE NOT EXISTS

    (SELECT * FROM SPEDDTL WHERE spdd_f1 = spd_f1 and spdd_f2 = spd_f2 and spdd_f3 = spd_f3 and spdd_f4 = spd_f4))

    There are a couple of issues here.

    1) We don't know if you can have duplicates in spdd_f5 or not. If so, you can determine a modifier for ROW_NUMBER prior to this query.

    2) There is no way to know what row will get what value because there is no indication of what the order of rows inserted will be.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/