Question

I have Table 1:

ID    UserString   Date     
-------------------------
 1    KRBS         4/25/2014    
 2    WEFG         4/24/2014

And Table 2:

ID  UserString + Other user info 
----------------------------------
 1  KRBS    +  . . .. . 

I'm preforming insert into Table 1 but I would like to make a condition to only insert if the user is already available in Table 2 (only only insert row in table 1 if user already exist in table2)

I'm currently doing two separate SQL checks (one if user exist then insert) but I'm sure there is a better way

Was it helpful?

Solution

Best way to achieve this is to define a FOREIGN KEY on the table. This is the simplest and most implicit way to do it, some reference on that can be found on MSDN. That means you will not ever be able to a) insert an entry to this table if no corresponding FK exists, and b) delete from the base table if entries with foreign key are here (in your case, delete the user if it already has the settings ). It will look like:

ALTER TABLE NameOfTheTable
ADD CONSTRAINT FK_SomeNameForTheKey FOREIGN KEY (nameOfColFromThisTable)
    REFERENCES NameOfTheOtherTable (NameOfTheCOlumnYouAreReferencing);

OTHER TIPS

try this on mysql:

if {{ userId }} in (select UserString from Table2 where UserString = {{ userId }}) then
    insert into Table1 (ID, UserString, Date) values ({{ id }}, {{ userId }}, '{{ date }}')
end if

or this on sql server

if {{ userId }} in (select UserString from Table2 where UserString = {{ userId }})
    insert into Table1 (ID, UserString, Date) values ({{ id }}, {{ userId }}, '{{ date }}')

change {{ var }} to your actual values

You may want to use insert ... select ... to achieve this, assuming your ID column is auto increment:

insert into
    table1 (
        UserString,
        Date
    )
select
    table2.UserString,
    @yourDateVariableHere
from
    table2
where
    table2.UserString = @yourUserStringVariableHere
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top