Need help with script

  • I did some searching in the forums before posting this question, but I could not find what I want. I'm sure the solution is probably simple but my old brain cells aren't giving me much help.

    I am trying to write a script that will select values from one column in Table A that change for every row, and insert that value in Table B, incrementing the row value used from Table A until I come to the end of the values in Table A.

    Table B has five columns that I have to account for in my insert statement. Fortunately, four of the five columns have identical values for each insert (they don't change), however, the values from Table A change for each row. I need a loop to go through the values selected from Table A and insert them into the corresponding column in Table B, along with the static values for each row.

    I am assuming I will use a temporary table to select the column values from Table A and then a WHILE loop to iterate through the values and insert them into Table B.

    SELECT desiredColumn INTO #TableA

    FROM sourceTable

    WHILE(????????)

    BEGIN

    INSERT INTO TableB

    (column1, column2, column3, column4, column5)

    VALUES

    (staticValue1, staticValue2, TableAValue, staticValue4, staticValue5)

    CONTINUE

    END

    I guess where I am stuck is in selecting the next column value from Table A in each iteration. Hope I'm close on the code I've already written. Appreciate any help.

    Thanks.

  • I highly doubt you need a loop or cursor for this. This sounds like a simple insert from select type of scenario. If you want some help with coding you need provide some ddl, sample data and desired output. Take a look at the first link in my signature for best practices when posting questions.

    _______________________________________________________________

    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/

Viewing 2 posts - 1 through 1 (of 1 total)

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