我有以下VB语句用于将文本数据插入SQL 2008 DB。如何在执行插入时检查sFieldNameList列中是否已存在sValueList?
sInsertStatement = "INSERT " & sTableName
& "(" & sFieldNameList & ") VALUES("
& Mid(sValueList , 3) & ")"
答案 0 :(得分:1)
我会这样做:
"IF NOT EXISTS (SELECT * FROM " & sTableName * "
WHERE " & sFieldNameList & " = " & sValueList & ")
BEGIN
"INSERT " & sTableName
& "(" & sFieldNameList & ") VALUES("
& Mid(sValueList , 3) & ")"
END
(这需要适应VBScript语法!)
答案 1 :(得分:0)
你需要做UPDATE还是INSERT?你需要的是UPSERT命令。基本上你需要一个WHERE子句,如:
where not exists (select 1 from mytable where col2='myId').
阅读here postgres是如何做到的。
sql2008没有相同的功能,只有check this blog(页面末尾)所在的位置:
USE [MyDatabase]
GO
merge into mytable as Target
using mytable2 as Source
on Target.id=Source.id
when matched then
update set Target.name=Source.name,
Target.Salary = Source.Salary
when not matched then
insert (id,name,salary) values (Source.id,Source.name,Source.Salary);