我正在尝试通过web接口将一行插入到Microsoft dynamics数据库中。我可以从(命令行?)运行插入。它工作得很好,但是当我尝试使用sqlsrv从PHP脚本运行它时,它会转储一个515错误,说明它不能向ID列中插入一个空值。
我觉得这个错误是sqlsrv与数据库而不是数据库本身对话的结果,因为我可以直接运行同一行并创建新的行。
前几次我试过这种方法,但为了解决问题,我把它拿出来了。这两种方法都有相同的错误。
错误信息:
( =>数组( => 23000 SQLSTATE => 23000 1 => 515代码=> 515 2 => MicrosoftSQL ServerCannot )将该值插入“ID”列,表'OMGHQ.dbo.Customer';列不允许空值。插入失败。message => MicrosoftSQL ServerCannot将值NULL插入列'ID',表'OMGHQ.dbo.Customer';列不允许空值。插入失败。)1 =>数组( => 01000 SQLSTATE => 01000 1 => 3621代码=> 3621 2 => MicrosoftSQL ServerThe语句已终止。消息=> MicrosoftSQL ServerThe语句已终止。))
$conn = sqlConnection();
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$itlquery = "DECLARE @itemID INT
DECLARE @newQuantity INT
SET @itemID = $itemID
SET @newQuantity = $newQuantity
INSERT INTO inventorytransferlog (itemID, quantity, cashierID, type, cost) VALUES (@itemID, @newQuantity - (SELECT TOP 1 quantity FROM item WHERE id = @itemID), 6, 5, (SELECT TOP 1 cost FROM item WHERE id = @itemID));";
echo $itlquery;
$itlstatement = sqlsrv_query($conn,$itlquery);
if($itlstatement === false)
{
die(print_r(sqlsrv_errors(),true));
}发布于 2015-12-17 18:02:55
在不知道php变量是什么($itemID和$newQuantity)的情况下,使用参数要安全得多,如下所示。这是一条预先准备好的语句,并具有额外的优点,可以防止某些SQL注入。
$itlquery = "INSERT INTO inventorytransferlog (itemID, quantity, cashierID, type, cost) VALUES (?, ? - (SELECT TOP 1 quantity FROM item WHERE id = ?), 6, 5, (SELECT TOP 1 cost FROM item WHERE id = ?));";
echo $itlquery;
$itlstatement = sqlsrv_query($conn,$itlquery,array($itemId,$newQuantity,$itemId,$itemId));编辑:虽然上面的内容是正确的,但它不是你问题的答案。您的ID表中必须有一个不能为空的Customer列。也许它是主键,而不是自动增量。因此,您必须在insert中指定它,或者更改架构以使其为空或自动递增(如果不是主键)。
https://stackoverflow.com/questions/34341232
复制相似问题