简体   繁体   English

sql根据其他表值插入行

[英]sql insert row based on other table value

I have 2 tables called table1 and table2. 我有2个表,分别称为table1和table2。 table1 has key, condition, level and conditionvalue columns and table2 has key and value columns. table1具有键,条件,级别和conditionvalue列,而table2具有键和值列。

table1 rows table1行

key         condition  level     conditionVal
 1              >        error       10
 1              =        info         5    
 2              <        warning      5
 2              >        info         20 

I will get inputs(key and value) from user or other source and that values I need to insert into table2 based on the following condition. 我将从用户或其他来源获取输入(键和值),并且需要根据以下条件将这些值插入到table2中。

if key is 1 and value is > 10 or value is equal to 5 then i need to insert. 如果键是1且值> 10或值等于5则我需要插入。 if key is 2 and value is > 20 or value is less than 5 then i need to insert. 如果键是2且值> 20或值小于5则我需要插入。

How to acheive this using sql insert statement. 如何使用sql insert语句实现此目的。

Try this: 尝试这个:

IF EXISTS(
           SELECT 1
           WHERE (@Key=1 AND (@value>10 @value=5) ) OR (@Key=2 AND (@value>20 OR @value<5))
                                                                                            )

INSERT INTO Table2 (column1) VALUES (@values)

try this : 尝试这个 :

INSERT INTO table2 (KEY, value)
  SELECT KEY , conditionVal 
    FROM table1 
    WHERE KEY IN
      (SELECT KEY
      FROM table1
      WHERE (KEY        =1
      AND (value        >10
      OR value          =5) )
      OR (KEY           =2
      AND (value        >20
      OR value          <5))
      AND 
    conditionVal IN
      (SELECT conditionVal
      FROM table1
      WHERE (KEY        =1
      AND (value        >10
      OR value          =5) )
      OR (KEY           =2
      AND (value        >20
      OR value          <5))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM