0

Ok i have 3 tables

Person Item Purchase

Person has 2 columns: PersonId, PersonName Item has 2 columns: ItemId, ItemName Purchase has 3 columns: PurchaseId, ItemId, PersonId

Lets Say Person with a PersonName of "Justin" Has a PersonId of 2 and Item with an ItemName of "Book" Has an ItemId of 4

I would like to insert into the purchase table using the values 2 and 4

What i have so far

 Select PersonId  AS a FROM tblPerson
 Where PersonName = 'Justin'

 Select ItemId  AS b From tblItem
 Where ItemName = 'Book'

 INSERT INTO tblPurchase (ItemId,PersonId)
 VALUES (b,a);

So the new entry in Purchase would be

PurchaseId ItemId PersonId 1 4 2

How would i do this in sql? Would i use variables?

Im using SQL Server Management Studio 2012

1 Answer 1

1
DECLARE @PersonId INT
DECLARE @ItemId INT

Select @PersonId = PersonId FROM tblPerson
Where PersonName = 'Justin'

Select @ItemId = ItemId From tblItem
Where ItemName = 'Book'

  INSERT INTO tblPurchase (ItemId,PersonId)
  VALUES (@ItemId  ,@PersonId);

If you are using an Identity or auto generated key on tblPurchase you can get that key after the INSERT using:

DECLARE @NewKey INT
SET @NewKey = SCOPE_IDENTITY()
Sign up to request clarification or add additional context in comments.

1 Comment

I hope there are UNIQUE INDEXes/CONSTRAINTs on dbo.tblPerson.PersonName and on dbo.tblItem.ItemName.

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.