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  
)   

 

上一篇:数据仓库之抽取数据:通过bcp命令行导入数据


下一篇:c#.net+SQL2005 实现简单搜索