我意识到这已被问了一百万次,但我找不到有效的答案。新的sql server和vs vb(抱怨老板,不是我),做练习跑。在以下内容中继续将varchar转换为数字异常:
Dim height, width As Decimal
height = InputBox("Enter height:")
width = InputBox("Enter width:")
'PRODUCING VARCHAR TO NUMERIC EXCEPTION
command = New SqlCommand("DECLARE @height as decimal(10,2), " & _
"@width as decimal(10,2), " & _
"@area as decimal(10,2); " & _
"SET @height = ' " & height & " '; " & _
"SET @width = ' " & width & " '; " & _
"SET @area = @height * @width; " & _
"IF @height IS NULL OR @width IS NULL " & _
" SELECT 'Either the height or width field was blank.' " & _
"ELSE IF @height <= 0 OR @width <= 0 " & _
" SELECT 'That''s some fancy negative space.' " & _
"ELSE " & _
" SELECT 'The area is: ' +@area;" _
, connect)
connect.Open()
rdr = command.ExecuteReader()
我已经通过vartype()验证了传递的数据确实是十进制的(我是唯一一个测试,因此不担心错误控制atm)。我尝试使用带有和不带有单引号的变量。 Cast()和Convert()不起作用(除非我做错了吗?)。不确定问题出在哪里?
答案 0 :(得分:2)
Dim height, width As Decimal
height = InputBox("Enter height:")
width = InputBox("Enter width:")
'PRODUCING VARCHAR TO NUMERIC EXCEPTION
command = New SqlCommand("IF @height IS NULL OR @width IS NULL " & _
" SELECT 'Either the height or width field was blank.' " & _
"ELSE IF @height <= 0 OR @width <= 0 " & _
" SELECT 'That''s some fancy negative space.' " & _
"ELSE " & _
" SELECT 'The area is: ' + cast(@width * @height as varchar(20))" _
, connect)
command.Parameters.Add("@height", SqlDbType.Decimal).Value = height
command.Parameters.Add("@width", SqlDbType.Decimal).Value = width
connect.Open()
rdr = command.ExecuteReader()
另外,在SQL中编写IF / ELSE语句以在各种选择中进行选择非常奇怪。对于SQL,您希望考虑编写描述一组数据的单个语句。