我正在尝试从php插入我的表在sql server中,但我不明白如何从我的查询中修复它。当我尝试运行查询时,会出现一条错误,通知我无法转换我的数据类型。
像这样:
Conversion failed when converting the varchar value '1 CASE When 1 = 1 Then Default ELSE Piority + CONVERT (Varchar(5),1) END' to data type tinyint.
这是我所有的PHP代码。
<?
include "new.php";
$ID_Person = $_POST['IDPerson'];
$Number_Phone_Person = $_POST['NumberPhonePerson'];
$Piority_Phone_Person = $_POST['PiorityPhonePerson'];
$Default = 'Default';
$Piority = 'Piority';
$response = array();
if (isset($ID_Person) &&
isset($Number_Phone_Person) &&
isset($Piority_Phone_Person)
)
{
$query = "INSERT INTO T_Person_Phone
(
ID_Person,
Number_Phone_Person,
Piority_Phone_Person
)
VALUES
(
'$ID_Person',
'$Number_Phone_Person',
'$Piority_Phone_Person
CASE When $Piority_Phone_Person = 1 Then $Default
ELSE $Piority + CONVERT (Varchar(5),$Piority_Phone_Person) END');";
$hasil = sqlsrv_query($conn,$query,$response);
if($hasil)
{
$response["success"] = 1;
$response["message"] = "User successfully created.";
} else
{
$response["success"] = 0;
$response["message"] = "Eksekusi error.";
die( print_r( sqlsrv_errors(), true));
}
} else
{
$response["success"] = 0;
$response["message"] = "Data gagal disimpan.";
}
// echoing JSON response
echo json_encode($response);
?>
有没有解决这个问题?
答案 0 :(得分:0)
首先,您使用引号封装SQL语句,因此它会逐字地解释整个字符串。也就是说,MySQL并不认为你想要一个case
开关,而是一个包含这些单词的字符串。将字符串插入tinyint列无效,因此错误。
所以改变这个:
'$Number_Phone_Person',
'$Piority_Phone_Person
CASE When $Piority_Phone_Person = 1 Then $Default
ELSE $Piority + CONVERT (Varchar(5),$Piority_Phone_Person) END')
对此:
'$Number_Phone_Person',
CASE WHEN $Piority_Phone_Person = 1 THEN $Default
ELSE $Piority + CONVERT (Varchar(5),$Piority_Phone_Person) END)
注意我并不完全确定整个$Piority + CONVERT (Varchar(5),$Piority_Phone_Person)
会发生什么 - 该声明可能同样无效。