2011-10-17 127 views
2

时转换失败我不知道如何将nvarchar值转换为int,但这是它需要设置的方式。我发现了其他职位,但我不知道如何在INSERT语句中使用CAST。我能找到的所有帖子都是关于在SELECT语句中转换为int的。我需要此语句将字段@Duration更改为数据库中的int。 @Duration是一段时间。 (01:00,02:00 ...)它们都会四舍五入到下一个int值。所以如果用户输入0:45,它应该被转换为1.有人能帮我弄清楚如何让这个INSERT工作吗?将nvarchar值'01:00'转换为数据类型int

'SQL Insert: Product table 
     Dim sqlInsertProduct As String = "INSERT INTO Product (ProductName, Status, 
             CreateDate, ModifyDate, CreateUser, 
             ModifyUser, Price, LaunchDate, Duration, 
             IsPublic, Presenter, Host, Broker) 

             VALUES (@ProductName, '1',getdate(), 
             getdate(), @CreateUser, @ModifyUser, 
             '0', @LaunchDate, @Duration, '1', 
             @Presenter, @Host, @Broker); 
             SELECT SCOPE_IDENTITY();" 
     Using cmd As New SqlCommand(sqlInsertProduct, cn) 
      Dim ProductID As String 
      cmd.Parameters.Add(New SqlParameter("@ProductName", 
      txtNewWebinarName.Text)) 
      cmd.Parameters.Add(New SqlParameter("@CreateUser", 
      System.Web.HttpContext.Current.User.Identity.Name)) 
      cmd.Parameters.Add(New SqlParameter("@ModifyUser", 
      System.Web.HttpContext.Current.User.Identity.Name)) 
      cmd.Parameters.Add(New SqlParameter("@LaunchDate", txtDateTime.Text)) 
      cmd.Parameters.Add(New SqlParameter("@Duration", txtDuration.Text)) 
      cmd.Parameters.Add(New SqlParameter("@Presenter", txtPresenter.Text)) 
      cmd.Parameters.Add(New SqlParameter("@Host", txtHost.Text)) 
      cmd.Parameters.Add(New SqlParameter("@Broker", txtBroker.Text)) 
      cn.Open() 
      ProductID = cmd.ExecuteScalar() 
      Session("ProductID") = ProductID 
      Dim Product As String = Session("ProductID") 
     End Using 
     cn.Close() 
+0

并且希望该值什么转换为int? 1? 100?因为这不是一个整数! – gbianchi

+0

假设'txtDuration.Text'是一个TimeSpan,你想将它存储为小时,分钟,秒,毫秒或什么? –

+0

对不起,@Duration是一段时间,比如01:00,需要转换为1. 02:00转换为2,依此类推。 – jlg

回答

0

假设你想要一个TimeSpan转换成int型,也假设你希望它是TotalHours属性:

Dim ts As TimeSpan = TimeSpan.Parse(txtDuration.Text) 
cmd.Parameters.Add(New SqlParameter("@Duration", ts.TotalHours)) 

编辑:如果这其实是一个时间跨度,您的转换将是错误因为字符串“0:45”表示0,75小时的时间跨度(45分钟是3/4小时)。

这应该做正确的舍入:

Dim hours As Integer = _ 
     CInt(Math.Round(ts.TotalHours, MidpointRounding.AwayFromZero)) 

http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

+0

这是完美的,非常感谢您的帮助! – jlg

+0

@jlg:很高兴我能帮忙。编辑我的答案,并添加了'MidpointRounding.AwayFromZero',否则0:30将是0而不是1. –

+0

一个注意:你认为它是用户友好的,让用户进入'0:31',你只存储1(小时)?!这是一种不切实际的信息丢失,你可以很容易地在前端进行整理,但保留精度并在需要时显示。 –

相关问题