Home Forums SQL Server 2008 T-SQL (SS2K8) Insert Into multiple values from Select plus adding incremental non-Identity RE: Insert Into multiple values from Select plus adding incremental non-Identity

  • Luv SQL (8/24/2016)


    This seems fairly simple, yet I've never been able to do this without multiple steps. I'm creating a sp to check to see if a field exists in Table A for any value in Table B. If there is a field in Table B that is not in Table A then I want to take that field and insert it, along with some constants, an incremental value (based on Max in Table A) for a specific record in Table A.

    Basically the purpose of this is for any new user created in Table B, I want this job to run the sp to insert this new User's ID into this other Table, with a sequence field in Table A (non-identity) and the value of another field in Table A is based on a specific user (mine).

    I can achieve what I want if I manually type in the UserName but then I have to do this for 50 other users, then it's manual for all new users. Here is the code for the manual insert:

    insert into TableA

    (UserName,Sequence,Title,Signature,IsDefault)

    select '<insertUserID>',(select Max(Sequence+1) from TableA),Title,Signature,'Y'

    from TableA

    where UserName='me'

    I've created a sp and have temp table that grabs all the new UserNames that I need to do this for (#TempNewUsers).

    1. How do I add all of these UserNames from #TempNewUsers into this select statement?

    2. Will the Sequence+1 put the same value for all items or will it +1 per each UserName ie do I have to declare a variable first then add 1 for each UserName?

    Why not just make your column an identity and stop killing yourself? You seem to putting a lot of importance of the value of what is just a number. The number itself really doesn't mean anything.

    _______________________________________________________________

    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/