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

时间:2015-07-21 20:47:32

标签: sql-server reporting-services ssrs-2008

enter image description here

SELECT [PROC_ID]
    ,[CONTACT_DATE_new]
    ,[CPT_CODE_new]
    ,[CHARGEABLE_YN_new]
    ,cat.CDM_Category
    ,DateUpdated
FROM
    [dbo].CDM_Audit_EAP_OT]
WHERE 
    @ColDate BETWEEN @Start_Date AND @End_Date

添加新参数@ColDate后,我开始收到上述错误。

@ColDate有“CONTACT_DATE_new”或“DateUpdated”。用户将根据他们正在寻找的内容选择一个。

如果我只是直接指定列,报告将正常工作。

 WHERE CONTACT_DATE_new BETWEEN @Start_Date AND @End_Date
 WHERE DateUpdated BETWEEN @Start_Date AND @End_Date

2 个答案:

答案 0 :(得分:1)

请使用where子句中的以下声明。我没有测试下面的脚本。

SELECT [PROC_ID]
        ,[CONTACT_DATE_new]
        ,[CPT_CODE_new]
        ,[CHARGEABLE_YN_new]
        ,cat.CDM_Category
        ,DateUpdated
    FROM
        [dbo].[CDM_Audit_EAP_OT]
where
   (@locationType = 'DateUpdated' AND (DateUpdated BETWEEN @Start_Date AND @End_Date)

CASE

SELECT [PROC_ID]
        ,[CONTACT_DATE_new]
        ,[CPT_CODE_new]
        ,[CHARGEABLE_YN_new]
        ,cat.CDM_Category
        ,DateUpdated
    FROM
        [dbo].[CDM_Audit_EAP_OT]
    where    
    CASE 
    when @locationType =  'DateUpdated' and (DateUpdated BETWEEN @Start_Date AND @End_Date) then 1
    Else 0
    End = 1 

答案 1 :(得分:1)

查询中的@ColDate不会被视为列名,而是字符串类型变量。当您尝试将其值与@startdate@enddate进行比较时,它会失败。因此错误。您可以按照以下方式创建存储过程以满足您的需要: -

Create PROCEDURE [SSRSReport]

@Start_Date date,
@End_Date date,
@ColDate nvarchar(25)

AS

BEGIN
SET NOCOUNT ON

declare @sql1 nvarchar(max)

if @ColDate = 'CONTACT_DATE_new'

begin
set @sql1 = 
'SELECT [PROC_ID]
    ,[CONTACT_DATE_new]
    ,[CPT_CODE_new]
    ,[CHARGEABLE_YN_new]
    ,cat.CDM_Category
    ,DateUpdated
FROM
    [dbo].CDM_Audit_EAP_OT]
WHERE 
    CONTACT_DATE_new BETWEEN ''' + cast(Convert(nvarchar(10),@Start_Date ,120) as Nvarchar(max)) +''' 
    AND ''' + cast(Convert(nvarchar(10),@End_Date ,120) as Nvarchar(max)) + ''''
    end

    else if @ColDate = 'DateUpdated'

    begin
set @sql1 = 
'SELECT [PROC_ID]
    ,[CONTACT_DATE_new]
    ,[CPT_CODE_new]
    ,[CHARGEABLE_YN_new]
    ,cat.CDM_Category
    ,DateUpdated
FROM
    [dbo].CDM_Audit_EAP_OT]
WHERE 
    DateUpdated BETWEEN ''' + cast(Convert(nvarchar(10),@Start_Date ,120) as Nvarchar(max)) +''' 
    AND ''' + cast(Convert(nvarchar(10),@End_Date ,120) as Nvarchar(max)) + ''''
    end

    print @sql1
    exec sp_executesql @sql1

end