
[英]How to delete a record when a user has two records with the following condition
[英]Comparing articles in two databases and only delete on the following condition
我有一个数据库表,将其称为“ t1”,另一个表将其称为“ t2”
如果不在t2中,我想将某些内容插入t1中。 知道它是否已经在t2中的条件(又称其为DUPLICATE)是t2中一个条目中字段之一的文本是否已经存在(与要插入的文本完全匹配)
如何使用SQL Server制定此条件?
你想要
如果项目在t2中是“已经”,但在t1中不是,那么我想避免执行INSERT语句。
因此插入应在上述声明否定的情况下进行,即
项目不应该在t2中,项目应该在t1中
insert into target_table( column list )
select ( column list)
from source_table
where item not in (select item from t2)
and item in (select item from t1)
我的意思是,如果文章不在t2中,那么我想将其插入t1中。 真的很简单
insert into t1 ( <column list>)
select <column list>
from source_table
where item not in (select item from t2)
您可以使用
IF NOT EXISTS (SELECT * FROM t2 WHERE item like '%'+@itemvalue+'%')
BEGIN
INSERT INTO t1
VALUES (@itemvalue)
END
您可以使用VALUES中的SELECT并与t2联接,例如,一次插入多行(当然,您只能插入一行)
insert into t1 ( id, label)
select id, label
from (VALUES(1, 'item1'),
(3, 'item3'),
(5, 'item5')) as T(id,label)
where not exists(select 1 from t2 where t2.id = t.id)
此FROM VALUES语法在Sql2008中可用,对于以前的版本,您已将VALUES(...)
子句替换为
SELECT 1,'idem1'
UNION ALL SELECT 2, 'item2'
如果您的数据包含在变量中,则只需执行(NO FROM):
insert t1 ( id, label)
select @id, @label
where not exists(select 1 from t2 where t2.id = @id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.