不要使用字符串连接将数据放入SQL查询!
这会导致Sql注入攻击。现在的问题是什么样的价值观,你所需要的,但猜测该样品是4条用逗号分开,你只需要在每条记录的空间之前的部分完全清楚,像这样做,而不是:
Dim sql As String = _
"SELECT SUM(CAST(LEFT(txttotal, " & _
" CASE WHEN charindex(' ', txttotal) = 0 THEN LEN(txttotal) ELSE charindex(' ', txttotal) - 1 END " & _
") As Integer)) as Total" & _
" FROM table WHERE odate >= @DateFrom AND odate <= @DateTo"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("@DateFrom", SqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("@DateTo", SqlDbType.DateTime).Value = DateTimePicker2.Value
cn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
'Do something with the reader here
End Using
或对于一个DataSet/DataTable的解决方案:
Dim result As New DataTable
Dim sql As String = _
"SELECT SUM(CAST(LEFT(txttotal, " & _
" CASE WHEN charindex(' ', txttotal) = 0 THEN LEN(txttotal) ELSE charindex(' ', txttotal) - 1 END " & _
") As Integer)) as Total" & _
" FROM table WHERE odate >= @DateFrom AND odate <= @DateTo"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("@DateFrom", SqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("@DateTo", SqlDbType.DateTime).Value = DateTimePicker2.Value
cn.Open()
result.Load(cmd.ExecuteReader())
End Using
基于一些评论,它开始听起来像的空间仅仅是一个缺少小数点分隔符。如果是这样的话,SUM()
表达是非常简单的:
SUM(CAST(REPLACE(txttotal, ' ', '.') As numeric(5,2)))
,你可能需要一个,
而不是.
取决于服务器的安装文化。 Sql Server 2012还有一个新的功能,允许您指定文化,消除任何模糊不清的机会,如果升级改变系统本地文化。
你确定它不是文化的东西吗?你尝试过吗?而不是,为您的小数点分隔符? – itsme86
我需要使用(,)字符作为分隔符。 – Mysta
你使用的是c#还是vb.net? –