从字符串转换日期和/或时间时转换失败

时间:2013-05-20 11:25:18

标签: sql-server sorting datetime

我正在做的是使用自己的函数,它返回字符串,现在我想要这个列进行排序,并且在使用它进行排序时它没有正确排序,因为它是一个字符串,当我尝试转换为datetime时它会导致错误。

任何帮助?

非常感谢。

SELECT 
    b.CallId,
    CONVERT(VARCHAR(25), b.ETADate, 103) as'ETADate',
    dbo.getCallEntrySerialNoLastTranDateTime(b.CallEntrySerialNumbersId) AS 'closingDateTime' 
FROM 
    CallEntry AS a, CallEntrySerialNumbers AS b     
WHERE 
    a.ASPId = 2 
    AND a.CompanyId = 3 
    AND a.CallId= b.CallId 
    AND a.ProdCompanyId = 1 
    AND b.CallCaseId IS NOT NULL 
    AND b.CallCaseId NOT LIKE 'NA' 
    AND ProdCategoryid = 1 
    AND a.CallDateTime > dateadd(day, -30, getdate()) 
    AND b.StatusId = 2 
ORDER BY 
    dbo.getCallEntrySerialNoLastTranDateTime(b.CallEntrySerialNumbersId) ASC

// what I tried and causes above error is 
ORDER BY 
    CONVERT(DATE, dbo.getCallEntrySerialNoLastTranDateTime(b.CallEntrySerialNumbersId)) asc

编辑添加功能

ALTER FUNCTION [dbo].[ASP_getCallEntrySerialNoLastTranDateTime]
(
    @CallEntrySerialNumbersId   bigint

)
RETURNS varchar(500)
AS
BEGIN

    DECLARE @ReturnVal  NVARCHAR(500);
    begin

    select @ReturnVal = ( select Top 1  CONCAT(CONVERT(VARCHAR(10),CallTranEndDateTime,103),' ',CONVERT(VARCHAR(10),CallTranEndDateTime,108))  from  calltransactions  
    where CallEntrySerialNumbersId = @CallEntrySerialNumbersId AND CallTranTypeId = 3 
        order by   CallTranId desc)

    end;    

    RETURN @ReturnVal;
END

1 个答案:

答案 0 :(得分:0)

试试这个 -

SET DATEFORMAT dmy

SELECT *
FROM (
    SELECT 
          b.CallId
        , ETADate = CONVERT(VARCHAR(25), b.ETADate, 103)
        , closingDateTime = dbo.getCallEntrySerialNoLastTranDateTime(b.CallEntrySerialNumbersId)
    FROM dbo.CallEntry a 
    JOIN dbo.CallEntrySerialNumbers b ON a.CallId = b.CallId   
    WHERE a.ASPId = 2 
        AND a.CompanyId = 3 
        AND a.ProdCompanyId = 1 
        AND ISNULL(b.CallCaseId, '') NOT LIKE 'NA' 
        AND ProdCategoryid = 1 
        AND a.CallDateTime > DATEADD(day, -30, GETDATE()) 
        AND b.StatusId = 2 
) d
ORDER BY CAST(d.closingDateTime AS DATE)

ALTER FUNCTION [dbo].[ASP_getCallEntrySerialNoLastTranDateTime]
(
    @CallEntrySerialNumbersId BIGINT
)
RETURNS VARCHAR(30)
AS BEGIN

    DECLARE @ReturnVal VARCHAR(30)

    SELECT @ReturnVal = ( 
        SELECT TOP 1 CONVERT(VARCHAR(10), CallTranEndDateTime, 103) + ' ' + CONVERT(VARCHAR(10), CallTranEndDateTime, 108)
        FROM dbo.CallTransactions  
        WHERE CallEntrySerialNumbersId = @CallEntrySerialNumbersId 
            AND CallTranTypeId = 3 
        ORDER BY CallTranId DESC
    )

    RETURN @ReturnVal

END