从字符串转换日期 and/or 时间时面临存储过程相关问题,如转换失败

Facing stored procedure related issue like Conversion failed when converting date and/or time from character string

这是我的存储过程,在 Status='2' 中我收到转换错误,在这里我试图找到包括今天在内的上周数据。如果有人能帮助我,我将不胜感激。

这是我得到的错误截图:

Error facing

代码:

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

if @status = 2 条件中,表达式(DATEADD(day,-11117,GETDATE())) returns 是datetime 类型的值。您正在尝试使用 + 运算符将其连接到字符串的末尾。你不能那样做:

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

这将修复您的特定错误,但您的代码在其他方面也有很大的改进空间。如果你有比较SQL经验的同事,看看能不能给你指点。

下面你可以找到正确的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