0

I am trying to avoid Inserting one record at a time so i need some help;

Here is an example table named Foods:

ID   UniqueID       Name        Type
1     Apple101      Apple       Fruit
2     Ban 11        Banana      Fruit
3     abc 123       Carrot      Vegetable
4     xyz123        Mango       Fruit
5     bnb123        Spinach     Vegetable

Now i have another Table name "Food Data" which has the following fields:

ID  UniqueID   FoodPrice    FoodExpiry

What i am trying to do is create the table above by recovering all the records from the table Foods which are Fruits and inserting into this table the thing is i have some external parameters (FoodPrice,FoodExpiry) . At the end i need the table Food Dataas below:

ID  UniqueID   FoodPrice    FoodExpiry
1   Apple101   100$         2 months
2   Ban 11     100$         2 months
3   xyz123     100$         2 months

The FoodPrice & FoodExpiry will remain the same for a given Query.

In Algorithmic terms i need an equivalent of :

Select UniqueID  from Foods where Type ='Fruit' and loop all the UniqueID   
and Insert into the table food Data , i want to this in one query .

1 Answer 1

2

The following assumes that FoodData.ID is an identity column and would automatically be populated. I also made some assumptions when declaring the types of the parameters:

DECLARE
  @Price decimal(19, 4)
  , @Expiry nvarchar(50)

SET @Price = 100.00
SET @Expiry = '2 months'

INSERT INTO FoodData (UniqueID, FoodPrice, FoodExpiry)
SELECT
  UniqueID
  , @Price 
  , @Expiry
FROM Food
WHERE Type = 'Fruit'
Sign up to request clarification or add additional context in comments.

6 Comments

Hi , Just tested the query ran no error but nothing gets inserted into the table?
Couple of things - I just noticed in your description of the FoodData table, the one column is named "Food.ID" - does the column name really have a dot in it? If so, you would need to change the insert to INSERT INTO FoodData ([Food.ID], FoodPrice, FoodExpiry) and to be real explicit, you could change the 3rd line to FoodID as [Food.ID]
Also, the question about the identity column is important. What are the specifics of the FoodData.ID column? Is it a plain old int or is its identity specification set to true?
Okay - same question - is FoodData.ID an identity column (meaning, that the server will automatically assign the next incremental value for you), or will you need to assign this value yourself?
FoodData.ID is an identity Column.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.