简体   繁体   English

C#-将数据加载到SQL Server中并合并(如果已存在)

[英]C# - Load data into SQL Server and merge if already present

Suppose I have the following table in SQL Server: 假设我在SQL Server中具有下表:

MyTable:
IDCol:     Val1:    Val2:
1          a        b
2          c        d
...

And, I am only able to access / modify it via direct SQL statements (meaning I can't put a file in a location and tell it to upload that file, for example) 而且,我只能通过直接的SQL语句访问/修改它(例如,我不能将文件放在某个位置并告诉它上传该文件)

So, currently, in my C# code, if I want to insert values into this table, I'm actually writing SQL such as: 因此,当前,在我的C#代码中,如果要在表中插入值,则实际上是在编写SQL,例如:

INSERT INTO MyTable (IDCol, Col1, Col2) Values (.....)

But now I have to take into account the possibility of a value already existing in the table and, if it does, to update that row. 但是现在我必须考虑表中已经存在值的可能性,如果存在,则要更新该行。

I know I can do this via a Merge , but how could I do it via direct SQL statements? 我知道我可以通过Merge来做到这一点,但是如何通过直接SQL语句来做到这一点呢?

  1. Do I create a temporary table, do the merge, then delete it? 我是否创建一个临时表,进行合并,然后将其删除?
  2. Do I query the rows that already match, update them, then do an insert on the remaining? 我要查询已经匹配的行,更新它们,然后对其余的行进行插入吗?
  3. Is there some kind of other SQL syntax for doing such a thing otherwise? 否则,是否存在某种其他SQL语法来执行此操作?

And, if #1 is the correct way to go, how can I do this such that, if I have 2 instances of my program running, I'm not double-creating a temporary table by the same name? 而且,如果#1是正确的方法,那么如果我有两个正在运行的程序实例,那么我该如何做到这一点呢?

You can use the merge command as you proposed or use an if exists like this: 您可以按照建议的方式使用merge命令,也可以使用if存在,如下所示:

IF EXISTS(SELECT * FROM myTable WHERE Id = @id)
UPDATE myTable SET x = @x WHERE Id = @id
ELSE
INSERT INTO myTable (Id, x) VALUES (@id, @x)

Assuming you are doing merge based on ID column, and assuming you are firing insert row by row, so you have three variables @idcol, @col1, @col2 , then use the below query 假设您正在基于ID列进行合并,并假设逐行触发插入,因此您拥有三个变量@idcol, @col1, @col2 ,然后使用以下查询

--DECLARE @IDCol int
--DECLARE @Col1 varchar(10), @Col2 varchar(10)
--SET @IDcol=2
--SET @Col1='A'
--SET @col2='C'

IF NOT EXISTS( SELECT 1 FROM MyTable WHERE IDCol=@IDCol)
BEGIN
INSERT INTO MyTable (IDCol, Col1, Col2) Values (@IDcol,@col1,@col2)
END
ELSE
BEGIN
UPDATE MyTable
SET Col1= @Col1, Col2=@Col2
WHERE IDCol=@IDCol
END

--SELECT * from MyTable

SQl demo link SQl演示链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM