duan1396 2014-05-28 03:56
浏览 612
已采纳

将Varchar从变量字符串转换为Float并插入SQL Server?

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?

  • 写回答

1条回答 默认 最新

  • dongshang6062 2014-05-28 04:09
    关注

    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 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog