面向sql的存储过程相关问题,如从字符串转换日期和/或时间时转换失败

4sup72z8  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(335)

这是我的存储过程,在status='2'中,我得到了一个转换错误,我试图在这里找到上周的数据,包括今天的数据。如果有人能帮我,我将不胜感激。
下面是我得到的错误截图:
面向错误
代码:

ALTER PROCEDURE [dbo].[USP_GetRequest_DataListForViewPrint]
    @RequestNo VARCHAR(50),
    @FromDate varchar(50),
    @ToDate varchar(50),
    @Status varchar(20)
AS
BEGIN

DECLARE @SQLStr varchar(8000)

DECLARE @CurrentDate  Varchar(100) =GETDATE()

IF (@RequestNo IS NOT NULL)
BEGIN
    BEGIN     
        SET @SQLStr = 'SELECT Id,RequestStatus, RequestNo,RequestDate From CYGNUX_Request_Header WHERE RequestNo='+''''+@RequestNo+'''';
    END
END
ELSE      
IF @Status = '1'
BEGIN
    SET @SQLStr = 'select Id,RequestStatus,RequestDate,RequestNo from CYGNUX_Request_Header where RequestDate between '+CHAR(39)+  convert(varchar(50) , @FromDate)  +CHAR(39)+ ' AND '+CHAR(39)+ convert(varchar(50), @ToDate) +CHAR(39);
END
IF @Status ='2'
BEGIN
        SET @SQLStr = 'select Id,RequestStatus, RequestNo, RequestDate from CYGNUX_Request_Header where RequestDate>='+(DATEADD(day,-11117,GETDATE()));
END
IF @Status ='3'
BEGIN
            SET @SQLStr = 'select Id,RequestStatus,RequestNo, RequestDate As Today from CYGNUX_Request_Header Where RequestDate='+CHAR(39)+  convert(varchar(50) , @CurrentDate)  +CHAR(39) ;
END
IF @Status ='4'
BEGIN
                SET @SQLStr = 'select Id,RequestStatus, RequestNo,RequestDate  from CYGNUX_Request_Header WHERE RequestDate<=' +CHAR(39)+  convert(varchar(50) , @CurrentDate)  +CHAR(39);
END 

PRINT @SQLStr;

EXEC(@SQLStr);

END
mnowg1ta

mnowg1ta1#

下面您可以找到正确的t-sql

IF @Status ='2'
BEGIN
     SET @SQLStr = '
             SELECT Id,RequestStatus, RequestNo, RequestDate 
             FROM CYGNUX_Request_Header 
             WHERE RequestDate>='+CAST(DATEADD(day,-11117,GETDATE()) AS varchar(50))
END
jucafojl

jucafojl2#

if @status = 2 条件,表达式 (DATEADD(day,-11117,GETDATE())) 返回类型为的值 datetime . 您正在尝试使用 + 接线员。你不能这么做:

select 'my character value' + getdate() -- << fails
select 'my character value' + convert(varchar, getdate(), 121) -- OK

这将修复您的特定错误,但您的代码在其他方面也有很大的改进空间。如果你有一个有更多sql经验的同事,看看他们能否给你一些建议。

相关问题