SQL IF NOT EXISTS INSERT Else Update,基于列ID

时间:2016-03-07 16:55:12

标签: sql sql-server sql-server-2014

我的目标是让SQL检查行是否存在,是否确实更新,如果不存在则插入。

FTP_num是第一列的名称。 SQL语句是

using (SqlCommand cmd = new SqlCommand("IF NOT EXISTS(SELECT ftp_num from Distributor WHERE fpt_num = FTP_num)" 
" insert FTP_Info set IP=@IP, Port=@Port, UN=@UN, PW=@PW, Folder=@Folder where FTP_num = @ftp_num" +
" else" +
" update FTP_Info set IP=@IP, Port=@Port, UN=@UN, PW=@PW, Folder=@Folder where FTP_num = @ftp_num", con))

我没有太多的SQL经验,感谢任何帮助。

Line 120:
Line 121:                con.Open();
Line 122:                cmd.ExecuteNonQuery();
Line 123:                con.Close();
Line 124:            }

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

正如已经建议的那样,MERGE语句在这里非常合适,因为它可能在原子指令中执行INSERTUPDATEDELETE

using (SqlCommand cmd = new SqlCommand(@"
    MERGE Distributor AS T
    USING ( VALUES(@IP, @Port, @UN, @PW, @Folder, @FTP_Num) AS S
        (IP, Port, UN, PW, Folder, FTP_num)
    ON S.FTP_num = T.FTP_num
    WHEN NOT MATCHED THEN
        INSERT VALUES (S.IP, S.Port, S.UN, S.PW, S.Folder, S.FTP_num);
    WHEN MATCHED THEN UPDATE
    SET IP=@IP, Port=@Port, UN=@UN, PW=@PW, Folder=@Folder",
con);

我的建议是直接在SSMS和端口代码.NET中使用MERGE语句,因为发现错误会更有效率(它复杂而且非常难看,但是强有力的声明)。

在您的情况下,源是来自上下文的纯数据,这就是源(S)由VALUES而不是table或{{1}组成的原因}。

有关MERGE语句的更多有用提示可以找到here

答案 2 :(得分:1)

您的插入语法错误。 它应该是这样的:

using (SqlCommand cmd = new SqlCommand("IF NOT EXISTS(SELECT 1from Distributor WHERE fpt_num = @FTP_num)" +
                        " insert into FTP_Info (IP, Port, UN, PW, Folder, FTP_num) VALUES(@IP, @Port, @UN, @PW, @Folder @ftp_num)" +
                        " else" +
                        " update FTP_Info set IP=@IP, Port=@Port, UN=@UN, PW=@PW, Folder=@Folder where FTP_num = @ftp_num", con))