0

我有以下用于将文本数据插入 SQL 2008 DB 的 VB 语句。如何在插入时检查 sValueList 是否已存在于 sFieldNameList 列中?

sInsertStatement = "INSERT " & sTableName 
                   & "(" & sFieldNameList & ") VALUES(" 
                   & Mid(sValueList , 3) & ")"
4

2 回答 2

1

我会这样做:

"IF NOT EXISTS (SELECT * FROM " & sTableName * " 
                WHERE " & sFieldNameList & " = " & sValueList & ") 
 BEGIN
    "INSERT " & sTableName 
              & "(" & sFieldNameList & ") VALUES(" 
              & Mid(sValueList , 3) & ")"  
 END

(不过,这需要适应 VBScript 语法!)

于 2012-09-20T16:58:30.023 回答
0

您需要执行 UPDATE 或 INSERT 吗?您需要的是一个 UPSERT 命令。基本上你需要一个 WHERE 子句,如:

where not exists (select 1 from mytable where col2='myId').

在这里阅读postgres 是如何做到的。

sql2008 没有相同的功能,但请查看此博客(页尾),它们在哪里:

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);
于 2012-09-20T17:07:23.257 回答