从Classic ASP将NULL值插入SQL Server

时间:2016-04-18 17:57:57

标签: sql-server asp-classic

我试图将一个简单的插入或更新到SQL Server中作为NULL,而不是空白。我在网上看到很多引用只是设置Field = NULL而没有引号,但它仍然是空的,而不是NULL。令人难以置信的令人沮丧。

这是经典的asp。

If Request.Form("Field") = "" or IsNull(Request.Form("Field")) then
    Field = NULL
Else
    Field = Request.Form("Field")
End If

sSql="UPDATE [table] SET timestamp = {fn NOW()}," &_ 
    "Field = '" & Field & "'," &_
    "WHERE [System] = '" & System & "' and Active = '1'"

如果我这样做,它证明它正在检查,因为它放入1。

If Request.Form("Field") = "" or IsNull(Request.Form("Field")) then
    Field = 1
Else
    Field = Request.Form("Field")
End If

sSql="UPDATE [table] SET timestamp = {fn NOW()}," &_ 
"Field = '" & Field & "'," &_
"WHERE [System] = '" & System & "' and Active = '1'"

我尝试了这个,但得到错误500:

    sSql="UPDATE [Table] SET timestamp = {fn NOW()}, Field = "
If IsNull(Field) Then
    sSQL = sSQL & "NULL"
Else
    sSQL = sSQL & "'" & Field & "'" &_
End If
"NTLogon = '" & UCase(NTLogon) & "'" &_
"WHERE [System] = '" & System & "' and Active = '1'"

当我尝试使用此代替原始代码时: 现场分配:

Field = "NULL" and Field = "'" & Request.Form("Field") & "'"

sSQL:

"Field = " & Field & "," &_

我得到“处理URL时服务器上发生错误。”

2 个答案:

答案 0 :(得分:1)

所以,是的,在这里插入关于使用参数化查询的咆哮,等等等等......现在,在所有人的系统中,我们可以查看实际的问题吗?

问题在于:

"Field = '" & Field & "'"

这些&符号正在将您精心填充的vbScript NULL值转换回字符串。如果您不希望这种情况发生,您需要明确处理IsNull案例。

sSQL = "UPDATE [table] SET timestamp = {fn NOW()}, Field = "
If IsNull(Field) Then
    sSQL = sSQL & "NULL"
Else
    sSQL = sSQL & "'" & Field & "'"
End If
sSQL = sSQL & " WHERE [System] = '" & System & "' AND Active = '1'"

请注意,即使您通过参数化查询执行此操作,也需要确保不要将vbScript NULL值附加到字符串上,因为"" & NULL = ""

答案 1 :(得分:0)

@pinchetpooche 你好。我遇到了同样的问题并尝试了给定的答案,但也收到了 500 错误页面。我发现@Martha 忘记包含正在更新的必要 SQL 字段(即“字段”)。所以我整理了一些测试代码,使用她的解决方案(即使用字符串连接和条件逻辑),并针对实际数据库执行,这个解决方案非常有效:

sSQLNullTest = "UPDATE CustomersToCCData SET " 
sSQLNullTest = sSQLNullTest & "CustomerID = " & iCustomerID & ", "
                    
   If IsNull(x_license_number_state) Or x_license_number_state = "" Then

     sSQLNullTest = sSQLNullTest & "CCLicenseState = NULL"

   Else
   
     sSQLNullTest = sSQLNullTest & "CCLicenseState = '" & x_license_number_state & "' "
   
   End If
                    
sSQLNullTest = sSQLNullTest & " WHERE CCID = '" & iCCInfoCCID & "'