我有一个sql表,它有两列id和name。我有20个名字的列表,我需要编写一个查询,检查名称是否存在插入之前。
有没有更好的方法来做到这一点,而不是只有下面的查询20次,但有不同的名称(我需要在t-sql中这样做):
IF NOT EXISTS(SELECT*
FROM mytable
WHERE name = 'Dan')
BEGIN
INSERT INTO mytable
(name)
VALUES ('dan')
END
答案 0 :(得分:5)
我认为你可以使用合并声明:
MERGE INTO myTable AS Target
USING (VALUES ('name1'),('name2'),('...')) AS source (NAME)
ON Target.NAME = Source.NAME
WHEN NOT MATCHED BY TARGET THEN
INSERT (NAME) VALUES (name)
答案 1 :(得分:5)
INSERT INTO MyTable (Name)
SELECT NewNames.Name
FROM ( VALUES ('Name1'), ('Name2'), ('Name3') ) AS NewNames (Name)
WHERE NOT EXISTS ( SELECT 1
FROM MyTable AS MT
WHERE MT.Name = NewNames.Name );
答案 2 :(得分:3)
您可以使用NOT EXISTS
INSERT INTO myTable (
Name
)
SELECT DISTINCT
Name
FROM (
VALUES ('Name 1'),
('Name 2')
) AS NewNames(Name)
WHERE
NOT EXISTS (SELECT 1 FROM TargetTable WHERE myTable.Name = NewNames.Name)
如果您的新名称在另一个表中,您可以更改上面的选择查询。
请注意,必须使用DISTINCT
关键字来过滤掉源数据中的重复项。
答案 3 :(得分:2)
我会使用insert
执行此操作:
with names as (
select 'Dan' as name union all
select 'name2' union all
. . .
)
insert into myTable(name)
select distinct name
from myTable
where not exists (select 1 from mytable t2 where t2.name = t.name);
注意:您可能希望在mytable(name)
上创建唯一索引,以便数据库检查重复项。
答案 4 :(得分:1)
INSERT IGNORE INTO myTable (column1, column2) VALUES (val1, val2),(val3,val4),(val5,val6);
INSERT IGNORE将允许跳过重复值
答案 5 :(得分:0)
未经测试,因此可能会出现一些小错误:
merge into mytable x
using (
values ('name1')
, ('name2')
, ...
, ('namen')
) as y (name)
on x.name = y.name
when not matched then
insert (name)
values (y.name)
答案 6 :(得分:0)
INSERT INTO MyTable (Name)
SELECT Name FROM
(
VALUES ('Name 1'),
('Name 2')
) AS Names(Name)
WHERE Name NOT IN
(
SELECT Name FROM MyTable
)