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  
)   

 

posted @ 2019-03-06 11:40  ChuckLu  阅读(10703)  评论(0编辑  收藏  举报