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

将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 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案