INSERT INTO与UPDATE中的CASE行为,位字段比较为更新nchar字段

时间:2014-06-12 14:21:10

标签: sql sql-server sql-update case sql-insert

我将记录从实时表更新为永久表并需要计算一些值。这是一般结构(遗漏了一些不相关的部分)

`UPDATE tbl_static_grades
    SET
        @Grade = 
           CASE
               WHEN tbl_live_grades.Incomplete = 1 THEN 'I'
               WHEN tbl_live_grades.Incomplete =0 THEN tbl_live_grades.Grade
               END
FROM tables
WHERE conditions

IF @@ROWCOUNT=0 
INSERT INTO tbl_static_grades (field-list) (VALUES <values-list>)
SELECT field1,
    field2,
    CASE Grade 
        WHEN Incomplete THEN 'I'
        WHEN Incomplete ^ 1 THEN Grade
        ELSE Grade
        END
FROM tables
WHERE conditions`

Grade是nchar(12),Incomplete是位域。

更新案例适用于不完整。

无论是使用= 0 / = 1技术还是使用Incomplete / Incomplete ^ 1技术,INSERT INTO CASE都会失败 &#34;转换nvarchar值时转换失败&#34; A&#34;到数据类型位&#34;

1 个答案:

答案 0 :(得分:0)

你可以将整个操作包装在一个这样的IF / Else块中......

IF EXISTS(SELECT 1 FROM FROM tables WHERE conditions)
 BEGIN

    UPDATE tbl_static_grades
        SET
            @Grade =    --<-- Also why this '@' before column name
               CASE
                   WHEN tbl_live_grades.Incomplete = 1 
                                    THEN 'I'
                   WHEN tbl_live_grades.Incomplete =0 
                                    THEN tbl_live_grades.Grade
                   END
    FROM tables
    WHERE conditions

 END
ELSE
 BEGIN

    INSERT INTO tbl_static_grades (field-list) VALUES (<values-list>)
    SELECT field1,
        field2,
        CASE Grade 
            WHEN Incomplete THEN 'I'
            WHEN Incomplete ^ 1 THEN Grade  --<-- Suspicious Code what is ^
            ELSE Grade
            END
    FROM tables
    WHERE conditions

 END