SQL / C# - UPSERT上的主键错误

时间:2011-08-31 21:09:12

标签: c# sql sql-server-2000

更新(简化问题,从问题中删除了C#)

如何在下列情况下编写可以识别两行相同的UPSERT ...

SSMS

看看那里有一个 \ b [退格] 编码(奇怪的小角色)? SQL认为这些是相同的。虽然我的UPSERT将其视为新数据,并尝试INSERT,其中应该有更新。


//UPSERT
    INSERT INTO [table]
    SELECT [col1] = @col1, [col2] = @col2, [col3] = @col3, [col4] = @col4
    FROM [table]
    WHERE NOT EXISTS
       -- race condition risk here?
       ( SELECT 1 FROM [table] 
       WHERE 
            [col1] = @col1 
        AND [col2] = @col2
        AND [col3] = @col3)

    UPDATE [table]
        SET [col4] = @col4
        WHERE 
        [col1] = @col1 
        AND [col2] = @col2
        AND [col3] = @col3

3 个答案:

答案 0 :(得分:4)

您需要@符号,否则会触发C#字符转义序列。

C#定义了以下字符转义序列:

\' - single quote, needed for character literals 
\" - double quote, needed for string literals 
\\ - backslash 
\0 - Unicode character 0 
\a - Alert (character 7) 
\b - Backspace (character 8) 
\f - Form feed (character 12) 
\n - New line (character 10) 
\r - Carriage return (character 13) 
\t - Horizontal tab (character 9) 
\v - Vertical quote (character 11) 
\uxxxx - Unicode escape sequence for character with hex value xxxx 
\xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx) 
\Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates) 

答案 1 :(得分:2)

经过几个小时的修修补补后,我发现自己一直在疯狂追逐。问题很简单。我从a popular SO post.取出了我的UPSERT。代码不好。选择有时会返回> INSERT上有1行。从而尝试插入一行,然后再次插入同一行

修复方法是删除FROM

    //UPSERT
    INSERT INTO [table]
    SELECT [col1] = @col1, [col2] = @col2, [col3] = @col3, [col4] = @col4
    --FROM [table] (Dont use FROM..not a race condition, just a bad SELECT)
    WHERE NOT EXISTS
       ( SELECT 1 FROM [table] 
       WHERE 
            [col1] = @col1 
        AND [col2] = @col2
        AND [col3] = @col3)

    UPDATE [table]
        SET [col4] = @col4
        WHERE 
        [col1] = @col1 
        AND [col2] = @col2
        AND [col3] = @col3

问题已经消失。

感谢你们所有人。

答案 2 :(得分:1)

您正在使用生成Unicode字符的'\u'

您的列是varchar,不支持Unicode字符。 nvarchar会支持这个角色。