Jump to content

Need help with INSERT...SELECT...WHERE


shanetastic

Recommended Posts

Here is my query:

 

INSERT INTO Territories 
(RepId, PrincipalID, StateID)
SELECT Reps.RepID
Where Reps.RepName = 'ARepName'
SELECT Principals.PrincipalID
Where Principals.PrincipalName = 'APrincipalName'
SELECT States.StateID
Where States.StateAbbreviation = 'LA'

 

I have four tables:

 

Reps
------
RepID
RepName


Principals
-----------
PrincipalID
PrincipalName


States
--------
StateID
StateAbbreviation

Territories
------------
RepID
PrincipalID
StateID

 

I know the RepName, PrincipalName, and StateAbbreviation.  I am trying to use those to pull the respective IDs from the respective tables and then insert a row into Territories.

 

What am I doing wrong?

Link to comment
Share on other sites

Am I getting warmer?

 

INSERT INTO Territories 
(RepId, PrincipalID, StateID)
JOIN StatesON Territories.StateID = States.StateID
JOIN Reps ON Territories.RepID = Reps.RepID
JOIN Principals ON Territories.PrincipalID = Principals.PrincipalID
SELECT Reps.RepID as RepID
Where Reps.RepName = 'ARepName'
SELECT Principals.PrincipalID as PrincipalID
Where Principals.PrincipalName = 'APrincipalName'
SELECT States.StateID as StateID
Where States.StateAbbreviation LIKE '%LA%'

Link to comment
Share on other sites

You are inserting into a mapping table so chances are you may not have that data in the application as of yet.

 

INSERT INTO Territories ( RepID, PrincipalID, StateID )
     SELECT ( SELECT RepID FROM Reps WHERE RepName = 'ARepName' ) AS RepID
         , ( SELECT PrincipalID FROM Principals WHERE PrincipalName = 'APrincipalName' ) AS PrincipalID
         , ( SELECT StateID FROM States WHERE StateAbbreviation LIKE '%LA%' ) AS StateID

 

Assuming they all return 1 row.  If they don't then you will need a bit more for the query to get it to work.

 

~juddster

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.