使用VBA使用NULL覆盖DB中的值

时间:2013-10-16 15:39:19

标签: sql-server vba

    If cell.Value <> "" Then

        uid = cell
        lname = Left(Replace(Range(cell.Address).Offset(0, 1), "'", ""), 50)
        fname = Replace(Range(cell.Address).Offset(0, 2), "'", "")
        stat = Replace(Range(cell.Address).Offset(0, 3), "'", "")
        role = Left(Replace(Range(cell.Address).Offset(0, 4), "'", ""), 50)
        iqn = Replace(Range(cell.Address).Offset(0, 5), "'", "")
        sdate = Format(Replace(Range(cell.Address).Offset(0, 6), "'", ""), "yyyy-mm-dd")
        bdate = Format(Replace(Range(cell.Address).Offset(0, 7), "'", ""), "yyyy-mm-dd")
        rodate = Format(Replace(Range(cell.Address).Offset(0, 8), "'", ""), "yyyy-mm-dd")
        End If
        hirereason = Replace(Range(cell.Address).Offset(0, 9), "'", "")
        roreason = Replace(Range(cell.Address).Offset(0, 10), "'", "")


        sql = "BEGIN TRAN IF EXISTS (SELECT * FROM " & TableName & " WITH (updlock, serializable)"
        sql = sql & " WHERE UID = '" & uid & "')"
        sql = sql & " BEGIN"
        sql = sql & " UPDATE" & TableName
        sql = sql & " SET LName='" & lname & "', FName='" & fname & "'"
        sql = sql & ", Status='" & stat & "', Role='" & role & "'"
        sql = sql & ", IQNRole='" & iqn & "', StartDate='" & sdate & "'"
        sql = sql & ", BillableDate='" & bdate & "', RollOffDate='" & rodate & "'"
        sql = sql & ", HireReason='" & hirereason & "', RollOffReason='" & roreason & "'"
        sql = sql & " WHERE UID = '" & uid & "'"
        sql = sql & " END"
        sql = sql & " ELSE BEGIN"
        sql = sql & " INSERT " & TableName & " (UID, LName, FName, Status, Role, IQNRole, StartDate"
        sql = sql & ", BillableDate, RollOffDate, HireReason, RollOffReason)"
        sql = sql & " VALUES('" & uid & "', '" & lname & "', '" & fname & "', '" & stat & "'"
        sql = sql & ", '" & role & "', '" & iqn & "', '" & sdate & "', '" & bdate & "', '" & rodate & "'"
        sql = sql & ", '" & hirereason & "', '" & roreason & "')"
        sql = sql & " END COMMIT TRAN"

        Cn.Execute (sql)

    End If

我有一些值,我正在格式化日期值,它是迄今为止的字符串。如果我按原样运行它,它会将“”的默认值放入DB中作为1900-1-1。我希望NULL值实际上保留在DB中而不会被覆盖。此外,我希望他们用NULL更新一个单元格,如果说它不是用,但现在是。

我尝试将我的值rodate包装在IF语句中并尝试对NULL,NOTHING和EMPTY进行验证,以确定它是否是这些UPDATE DB中的一个“NULL”,但它没有这样做。日期仍然出现1900-1-1。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我很困惑,不确定我是否能正确回答这个问题。

我唯一理解的是你在数据库中将日期保存为NULL。 NULL和空字符串不一样 试试看是否有效:

dim vNull as variant 

vNull = Null 

if sDate = "" then 
    //Save vNull instead of Date
end if

我不相信你可以在字符串数据类型中捕获NULL。

修改
也许愚蠢的是我之前没有想过这个,而不是一个空字符串,你不能把字符串“NULL”放在查询字符串中吗?

答案 1 :(得分:0)

Dim roDate
'...
'...
rodate = Trim(cell.Offset(0, 8).Value)
If len(rodate)=0 Then
    rodate = null
else
    rodate = "'" & Format(rodate, "yyyy-mm-dd") & "'"
end if
'....
'....
'note no single quote here around rodate
sql = sql & ", BillableDate='" & bdate & "', RollOffDate=" & rodate
'...
'...