簡體   English   中英

SQL插入-僅在這種情況下插入

[英]SQL Insert - Only insert on this condition

我有Table 1

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

Table 2

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

我正在向表1中執行插入操作,但我想創建一個條件,使其僅在表2中已有用戶時才插入(如果表2中已有用戶,則僅在表1中插入行)

我目前正在做兩個單獨的SQL檢查(一個如果用戶存在,然后插入),但是我敢肯定有更好的方法

實現此目的的最佳方法是在表上定義一個FOREIGN KEY 這是最簡單,最隱式的方法,有關某些參考可以在MSDN上找到。 這意味着您將永遠無法:a)如果不存在相應的FK,則在此表中插入一個條目; b)如果此處具有外鍵的條目在基表中刪除(在您的情況下,則刪除該用戶)設置)。 它看起來像:

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

在mysql上試試這個:

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

或在SQL Server上

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

將{{var}}更改為您的實際值

您可能要使用insert ... select ...來實現這一點,假設您的ID列為自動遞增:

insert into
    table1 (
        UserString,
        Date
    )
select
    table2.UserString,
    @yourDateVariableHere
from
    table2
where
    table2.UserString = @yourUserStringVariableHere

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM