0

以下查询不会失败,但也不会插入唯一值。

我只想插入唯一值

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)
4

4 回答 4

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
于 2012-05-11T18:59:54.833 回答
0

查询插入行的唯一方法是,如果数据库中没有包含“aaa”、“aaa”的行。

看,你在做

SELECT 'aaa','aaa'
WHERE NOT EXISTS
(SELECT [user_id],real_name FROM TargetTable)

因此,它的'aaa','aaa'结果集“减去”或“除外”由目标表上每一行的 user_id 和 real_name 列形成的结果集。

所以如果 'aaa','aaa' 已经存在于第二个结果集中,它将被排除在最终结果集中,因此不会被插入

于 2012-05-11T18:50:32.537 回答
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. 查询之间发生的变化可能会导致不愉快的结果。

于 2012-05-11T19:57:18.610 回答
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
于 2012-05-11T21:06:33.887 回答