忽略CAST错误

时间:2018-05-14 18:18:43

标签: sql sql-server sql-server-2012

我有两个字段

(CAST((SUBSTRING([CallLength],0,(CHARINDEX(':',[CallLength],0)))*3600)+(LEFT(RIGHT([CallLength],5),2)*60)+RIGHT([CallLength],2) AS int) -
CAST((SUBSTRING([CallLengthActual],0,(CHARINDEX(':',[CallLengthActual],0)))*3600)+(LEFT(RIGHT([CallLengthActual],5),2)*60)+RIGHT([CallLengthActual],2) AS Int)) AS Variance

其中包含格式为hh:mm:ss的值。

我需要在几秒内找到两个字段之间的差异,这在数据格式正确时工作正常。一些数据格式不正确,当我尝试将其转换为整数时,我收到错误消息“将varchar值'x'转换为数据类型int时转换失败。”

有没有办法只是忽略格式不正确的数据?我正在使用SQL Server 2012,文档说支持TRY_CAST但它似乎不适用于我的版本。

Controller java file (LogControllerLua.java):
-----------
@Api(value = "/")
@Path("/")
public class LogControllerLua

{

    private Logger logger = LoggerFactory.getLogger(LogControllerLua.class);
    private LoggerServiceLua loggerServiceLua = new LoggerServiceLua();

    @GET
    @Path("/getLogServerInfo")
    public String getLogServerInfo(@Context HttpHeaders httpheaders) throws Exception {
//..code }



service class ::(LoggerServiceLua.java) ::
------------------------------
package com.koopid.apex.API.rest.service;

public class LoggerServiceLua {

public String getLogServerInfo() throws Exception { //..code }


web.xml ::
------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

 <!--  <web-app> -->
  <display-name>jerseysample</display-name>
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
            <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>
            com.adaequare.resource.config.JerseyResourceInitializer
        </param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

1 个答案:

答案 0 :(得分:2)

您没有提供样本数据和所需结果,但您的代码看起来比需要的更复杂。

如果我在几秒钟内得到了差异,我会这样做:

   datediff(second,
            try_convert(time, CallLengthActual),
            try_convert(time, CallLength)
           ) as diff_seconds

这可能是你想要的消极。我不确定你从中减去了什么。

如果try_convert()不起作用,那么您的兼容级别设置为旧版本。您可以与isdate()

非常接近
   datediff(second,
            (case when isdate(CallLengthActual) = 1 then convert(time, CallLengthActual end),
            (case when isdate(CallLength) = 1 then convert(time, CallLength) end)
           ) as diff_seconds