0

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?

7
  • 1
    you need to remove the commas from the $amount Commented May 28, 2014 at 3:58
  • there is no comma, u mean single quotes? i did but no change.Still error :CONVERT(FLOAT,$amount) -->[Microsoft][SQL Server Native Client 10.0][SQL Server]Incorrect syntax near ','.. Commented May 28, 2014 at 4:01
  • "echo ($amount); // prints 1,000,000.00" i see 2 commas Commented May 28, 2014 at 4:01
  • oh i understand now what u mean Commented May 28, 2014 at 4:03
  • 2
    i have the magic power of reading ;-) Commented May 28, 2014 at 4:05

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

10 Comments

its of type float in db
I think my answer works for FLOAT. You could check the demo link above.
i am not sure where r u asking me to declare @amount varchar(25)? in the php code?
No, simply change CONVERT(FLOAT,'$amount') to cast(@amount as money). The link I post above is for testing purpose to demo why my suggestion works.
[Microsoft][SQL Server Native Client 10.0][SQL Server]Must declare the scalar variable "@amount".. INSERT INTO dbo.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.