前段時間通過mybatis寫sql,想實現EXISTS語法,一直報錯,記錄一下,以防以后范同樣的錯誤,
錯誤語法類似如下:
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)
正確語法記錄一下
第一種:前置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
第二種:通過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 )