insert into 和 where not exists

Posted chucklu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了insert into 和 where not exists相关的知识,希望对你有一定的参考价值。

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/3569bd60-1299-4fe4-bfa1-d77ffa3e579f/insert-into-with-not-exists?forum=transactsql

错误的语法

INSERT INTO [dbo].[geo_asso_type]

([geo_asso_type_id]

,[bound_asso_type]

,[updated_date])

VALUES

(11

,Province to City

,GETDATE()

WHERE NOT EXISTS

(SELECT 1 FROM [dbo].[geo_asso_type] WHERE [geo_asso_type_id] = 11)

 

方案1,前置not exists

IF NOT EXISTS (SELECT 1 FROM [dbo].[geo_asso_type] WHERE [geo_asso_type_id] = 11)  
BEGIN 
    INSERT INTO [dbo].[geo_asso_type]   
        ([geo_asso_type_id]  
        ,[bound_asso_type]  
        ,[updated_date])  
    VALUES 
        (11  
        ,Province to City 
        ,GETDATE())  
 
END 

 

方案2,通过select的方式插入数据

INSERT INTO [dbo].[geo_asso_type]         
(     
[geo_asso_type_id],        
[bound_asso_type],     
[updated_date]     
)        
SELECT    
     11,     
     Province to City,     
     GETDATE()     
WHERE NOT EXISTS(     
    SELECT 1   
    FROM [dbo].[geo_asso_type]   
    WHERE [geo_asso_type_id] = 11  
)   

 

以上是关于insert into 和 where not exists的主要内容,如果未能解决你的问题,请参考以下文章

INSERT INTO WITH SELECT 和 WHERE(问题)

MS-Access:SQL JOIN 和 INSERT INTO 与 WHERE 慢

LINQ to Entities does not recognize the method , and this method cannot be translated into a store e

带有 INSERT 和 WHERE NOT EXISTS 的奇怪 SQL 行为

insert into 插入数据问题

MySQL INSERT INTO ... 值和选择