以下查询不会失败,但也不会插入唯一值。
我只想插入唯一值
DECLARE @user_id AS varchar(80)
DECLARE @real_name as varchar(250)
- 新的唯一值是“aaa”,它们在目标表中不存在
SET @user_id = 'aaa'
SET @real_name = 'aaa'
INSERT INTO TargetTable
([user_id],real_name)
SELECT @user_id, @real_name
WHERE NOT EXISTS
(SELECT [user_id],real_name FROM TargetTable)
答案 0 :(得分:1)
如果您按照自己的方式遇到插入问题,请尝试不同的方法:
-- if the count of records with that @user_id and @real_name is less or equal to 0,
-- that means it's not in the table
IF (0 >= (SELECT COUNT(*) FROM TargetTable WHERE @user_id = [user_id] AND @real_name = [real_name]))
BEGIN
-- then call a normal insert
INSERT
INTO TargetTable ([user_id], real_name )
VALUES (@user_id , @real_name)
END
答案 1 :(得分:0)
查询插入行的唯一方法是,如果数据库上没有'aaa','aaa'的行。
看,你在做什么
SELECT 'aaa','aaa'
WHERE NOT EXISTS
(SELECT [user_id],real_name FROM TargetTable)
所以,它的'aaa','aaa'
结果集“减去”或“除了”由目标表上的每一行的user_id和real_name组成的结果集。
因此,如果'aaa','aaa'已存在于第二个结果集中,它将从最终结果集中排除,因此不会被插入
答案 2 :(得分:0)
如果有人还在乎,或者稍后再看这个问题......
最初的问题是OP使用WHERE NOT EXISTS
子句来检查目标表中存在的任何行,而不是特定的行。只需检查您要插入的数据:
DECLARE @user_id AS varchar(80)
DECLARE @real_name as varchar(250)
--New Unique values are "aaa" and they do not exist in the target table
SET @user_id = 'aaa'
SET @real_name = 'aaa'
INSERT INTO TargetTable
([user_id],real_name)
SELECT @user_id, @real_name
WHERE NOT EXISTS
( SELECT 42 FROM TargetTable WHERE [user_id] = @user_id AND real_name = @real_name )
(当前)接受的答案鼓励不安全的设计,其中执行两个单独的查询而没有TRANSACTION
的好处。查询之间发生的更改可能会导致令人不快的结果。
答案 3 :(得分:0)
这是为了解决user92546的问题。插入发生在查询TargetTable的同一查询中。唯一的子选择是针对变量,它们显然不会在此插入过程中发生变化,而表格可能会在任何微秒级发生变化。
DECLARE @user_id AS varchar(80)
DECLARE @real_name as varchar(250)
--New Unique values are "aaa" and they do not exist in the target table
SET @user_id = 'aaa'
SET @real_name = 'aaa'
INSERT INTO TargetTable ([user_id],real_name)
SELECT T1.user_id, T1.real_name
FROM (select @user_id [user_id], @real_name [real_name] ) T1
LEFT JOIN TargetTable T2
on T1.user_id = T2.user_id
and t1.real_name = T2.real_name
and T2.user_id = @user_id
and T2.real_name = @real_name
WHERE T2.user_id is null