[英]Convert Varchar to Float from a variable string and insert into SQL Server?
I am new to SQL Server. 我是SQL Server的新手。 I have created a script where I import data and insert into SQL Server. 我创建了一个脚本,在其中导入数据并将其插入SQL Server。 The update query works fine but the insert query does not . 更新查询可以正常工作,但插入查询不能。 I get a error 我得到一个错误
Error converting data type varchar to float.. INSERT INTO dbo. 将数据类型varchar转换为float时出错。INSERT INTO dbo。
This is the code 这是代码
$amount = trim(str_replace('$','',$data[2]));
// echo ($amount); // prints 1,000,000.00
// INSERT QUERY
//Try 1 : Fails
$Query = "INSERT INTO dbo.testtable (id, name, amount)
values ( 11, 'John' , $amount )";
//Try 2 : Fails
$Query = "INSERT INTO dbo.testtable (id, name, amount)
values ( 11, 'John' , CONVERT(FLOAT,'$amount') )";
How in the world can I insert a proper float value from the variable ( $amount
) into SQL Server? 在世界上如何从变量( $amount
)插入合适的浮点值到SQL Server?
use this: 用这个:
cast('$amount' as money)
Updates: It actually depends on what's the type of your column amount
. 更新:实际上取决于列amount
的类型。 If it's varchar, it should not throw an error for 1st line. 如果是varchar,则不应在第一行中引发错误。 So, I guess it's something like decimal(18, 2)
. 所以,我想这有点像decimal(18, 2)
。 Refer to the demo here 在这里参考演示
declare @amount varchar(25)
SET @amount = '1,000.00'
create table #tmp_money (amount FLOAT)
insert into #tmp_money
SELECT cast(@amount as money)
select * from #tmp_money
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.