【问题标题】:MS SQL update query on int column with an empty value具有空值的 int 列上的 MS SQL 更新查询
【发布时间】:2012-02-17 00:33:00
【问题描述】:

我的表有两列 - col1 (int, null) 和 col2 (int, null) 我希望能够使用空值或 null 语句进行更新。

我的代码如下:

            $newkeylimit = $allkeylimits[$row['Group_ID']];
            if($newkeylimit == ''){ $newkeylimit = NULL ; }

            $newproflimit = $allproflimits[$row['Group_ID']];                               
            if($newproflimit == ''){ $newproflimit = NULL ; }

            $sql = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '".$newgroupname."', col1 = '".$newkeylimit."', col2 = '".$newproflimit."' WHERE Group_ID = '".$row['Group_ID']."'";
            $result = mssql_query($sql)
                or die( "<strong>ERROR: Group update query failed</strong>" );

代码执行后,我在假设为空值或 NULL 的每一列中得到 0。 col1 和 col2 的默认值设置为 NULL。

知道我做错了什么吗?谢谢

【问题讨论】:

  • 好的,我已将上面的代码更改为:if(empty($newkeylimit) && empty($newproflimit)){ $sqlup = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '"。 $newgroupname."', col1 = null, col2 = null WHERE Group_ID = '".$row['Group_ID']."'"; } else { $sqlup = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '".$newgroupname."', col1 = '".$newkeylimit."', col2 = '".$newproflimit."' WHERE Group_ID = '".$row['Group_ID']."'"; } 并且它以某种方式起作用。

标签: php sql sql-server-2008 tsql


【解决方案1】:

您不能设置为“NULL”。您改为设置为 NULL。 试试这个。

        $newkeylimit = $allkeylimits[$row['Group_ID']];
        if($newkeylimit == "''"){ $newkeylimit = "NULL" ; }

        $newproflimit = $allproflimits[$row['Group_ID']];                               
        if($newproflimit == '""'){ $newproflimit = "NULL" ; }

        $sql = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '".$newgroupname."',                col1 = ".$newkeylimit.", col2 = ".$newproflimit." WHERE Group_ID = '".$row['Group_ID']."'";

【讨论】:

  • 如下所述 - 代码将 NULL 作为字符串而不是 int 传递。 IF 语句也对我无效(搜索双撇号或引号)
【解决方案2】:

您将字符串而不是 NULL 传递给服务器。去掉 col1 和 col2 的撇号 (')。

【讨论】:

  • 我的代码没有 col1 和 col2 的撇号 (')。即使将 if($newkeylimit == '') 切换为 if(empty($newkeylimit)) 也无济于事
  • 知道了!在传递带有开/关撇号的变量时,无论如何我都将 NULL 作为字符串传递。谢谢。
  • 不知道是谁做的,但你的答案比不正确的答案要好,因为他也将 NULL 作为字符串传递。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多