I am new to SQL Server. I have created a script where I import data and insert into 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.
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?
use this:
cast('$amount' as money)
Updates: It actually depends on what's the type of your column amount
. If it's varchar, it should not throw an error for 1st line. So, I guess it's something like 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