从表中选择要插入另一个,获取类型错误

时间:2016-06-27 10:05:04

标签: sql sql-server tsql

我有以下查询,在从另一个表中选择数据后将数据插入到一个表中。

问题是数据类型与其中一列不匹配。我简化了下面的查询。

INSERT INTO tbl.LogTable (
    [SelPartNo], -- This does not match, see below
    )
SELECT TOP 1 
    IF([SelPartNo] = 'False', NULL, [SelPartNo],
FROM tbl.MyTable
WHERE ID = '20358'
ORDER BY CreateDate DESC

第一个SelPartNo是一个int,第二个是VarChar。在大多数情况下,第二个SelPartNotbl.MyTable)的NULLNULL或整数,我认为这不会导致问题。但在某些情况下,值为&#34; False&#34;,需要返回 <option value='0' if ($result[$row]['discount'] == '0') echo 'selected = "selected"'; ?> >0</option> <?php $result = array ( array ( 'item' => 'Dextrose', 'price' => '10.00', 'quantity' => '10', 'discount' => '5.00', 'total' => '95.00' ), array ( 'item' => 'Nescaine', 'price' => '20.00', 'quantity' => '30', 'discount' => '10.00', 'total' => '540.00' ), array ( 'item' => 'Anticavity', 'price' => '30.00', 'quantity' => '10', 'discount' => '25.00', 'total' => '225.00' ) ); for ($row = 0; $row < sizeof($result); $row++) { echo "<tr>"; echo "<td><input type='text' name='item[]' value=".$result[$row]['item']." required></td>"; echo "<td><input type='text' name='price[]' value=".$result[$row]['price']." required></td>"; echo "<td><input type='text' name='qty[]' value=".$result[$row]['quantity']." required></td>"; echo "<td><select name='discount[]' > <option value='0'".if($result[$row]['discount'] == '0') echo 'selected = "selected"'.">0</option> <option value='5'".if($result[$row]['discount'] == '5') echo 'selected = "selected"'.">5</option> <option value='10'".if($result[$row]['discount'] == '10') echo 'selected = "selected"'.">10</option> <option value='25'".if($result[$row]['discount'] == '25') echo 'selected = "selected"'.">25</option></td>"; echo "<td><input name='total[]' value=".$result[$row]['total']." ></td>"; echo "</tr>"; echo "<br>"; }

我已尝试过IF语句,但我做错了,因为它出现语法错误,我不确定这是否是正确的方法。

2 个答案:

答案 0 :(得分:2)

您的代码在语法上是合并的......

尝试

NULLIF([SelPartNo],'False')

如果两个表达式相等,则此函数返回NULL

详细信息:https://msdn.microsoft.com/en-us/library/ms177562.aspx

答案 1 :(得分:1)

我不认为IF是一个函数,至少不能在SELECT语句中使用它。但CASE WHEN ... END是你的朋友:

INSERT INTO tbl.LogTable (
    [SelPartNo]
    )
SELECT TOP 1 
    CASE WHEN [SelPartNo] = 'False' THEN NULL ELSE [SelPartNo] END
FROM tbl.MyTable
WHERE ID = '20358'
ORDER BY CreateDate DESC