Thursday, April 28, 2011

How to copy & insert records in table by strored procedure?

I have a table with one field: lngStatusID with value 2 for all the records.

Now I need to insert all the records again in the same table but with lngStatusID=1

So for that I think stored procedure will help me somehow.

AS per my logic it should be something like:

1) I need to read each record with loop

2) copy all fields in temporary variables

3) And than execute insert query to insert the record with lngStatusID=1

I am new to stored procedure. So can any one guide me how to do that?

Or is there any easy way to do so?

From stackoverflow
  • You don't need a stored procedure for this, a simple INSERT statement will do:

    insert into mytable
    (field1, field2, lngStatusID)
    select field1, field2, 1
    from mytable
    
  • Why do you need to insert them again? Maybe simple UPDATE will be enough?

    UPDATE table SET IngStatusID = 1
    

    Please provide more details, because for me it is pointless to copy all the records to temporary table to insert them again.

  • UPDATE <tablename>
    SET IngStatusID = 1
    

    That being said, any table with only one field probably shouldn't be a table unless its some kind of lookup.

    JohnFx : Even if it was a lookup table, what would be the point of having a single column with the same value on multiple rows?
    Scott Lance : Agreed, there is no point to having the same value in multiple rows.
    RedFilter : @JohnFx: multiple fields ("all fields") are mentioned in 2) in the original question.
  • INSERT INTO <TABLENAME> (Col1,Col2,Col3)
    SELECT Col1, Col2, 2
    FROM <TABLENAME>
    

    No need for sp or cursors

0 comments:

Post a Comment