3

我一直在处理 SSRS 报告,对于我的一个存储过程,它使用动态 SQL,因此我收到此错误:

An item with the same key has already been added.

所以我用谷歌搜索了这个错误,但对我来说仍然很模糊..

我的存储过程接受了一些切换类型的参数,如下所示:

@CompleteType INT = NULL,
/*
 * 0 - Routed
 * 1 - Targeted
 * 2 - Offerwall
 */

@SourceType BIT = NULL,
/*
 * Works if @AccountID is not null
 * (should only be used if @AccountID has a single value)
 *
 * 0 - Owned by @AccountID
 * 1 - External (not owned by @AccountID)
 */

@SurveyStatus INT = NULL,
/*
 * NULL - All Surveys
 * 0 - Completes Approved Surveys
 * 1 - Invoiced Surveys
 */

@IsSupplierUser BIT = 0
/*
 * used to decide whether to display FEDSurveyName or SupplierSurveyName

问题出现在这两个代码块中(它们不连续):

-- Initial Survey Name
    IF @IsSupplierUser = 0
        SET @SQL += CHAR(13) + CHAR(9) + N' ,ts.FEDSurveyName as ''Initial Survey Name'''

    ELSE
        SET @SQL += CHAR(13) + CHAR(9) + N' ,ts.SupplierSurveyName as ''Initial Survey Name'''

然后这个:

-- Complete Survey Name
IF @IsSupplierUser = 0
    SET @SQL += CHAR(13) + CHAR(9) + N' ,cs.FEDSurveyName as ''Complete Survey Name'''
ELSE
    SET @SQL += CHAR(13) + CHAR(9) + N' ,cs.SupplierSurveyName as ''Complete Survey Name'''

我们有 a ts.FEDSurveyName和 a cs.FEDSurveyName,并且SupplierSurveyName 分别相同。我很感激任何提示!谢谢

4

2 回答 2

4
DECLARE
@IsSupplierUser BIT = 0,
@SQL NVARCHAR(MAX) ='init'
-- Initial Survey Name
SELECT @SQL += CASE @IsSupplierUser
    WHEN 0 THEN CHAR(13) + CHAR(9) + N' ,ts.FEDSurveyName'
    ELSE CHAR(13) + CHAR(9) + N' ,ts.SupplierSurveyName'
END + N' as ''Initial Survey Name'''
SELECT @SQL 

http://www.sqlfiddle.com/#!3/d41d8/10397

于 2013-03-05T02:25:57.800 回答
1

我假设这些片段用于生成您的选择列表。要将其转换为非动态 SQL:

SELECT
  CASE 
    When @IsSupplierUser = 0 Then ts.FEDSurveyName 
    Else ts.SupplierSurveyName 
  END as 'Initial Survey Name',
  ts.SomeOtherColumn,
  etc.
  ...
FROM ...

当然是“等等”。只是表示您继续使用其他列,您可以为您显示的其他条件列设置另一个 case 语句。

于 2013-03-05T02:20:07.683 回答