当满足另一个表的条件时如何从表中选择记录

时间:2018-08-01 11:18:09

标签: sql sql-server ssms

我有定期运行的查询。

SELECT REPLICATE('0', 10-LEN(PolicyNumber)) + PolicyNumber AS PolicyNumber,
       REPLICATE('0', 7-LEN(BOCBranch)) + BOCBranch AS BOCBranch,
       CIFNumber+ REPLICATE(' ', 8-LEN(CIFNumber)) AS CIFNumber,
       REPLICATE('0', 7-LEN(EmployeeNumber)) + EmployeeNumber AS EmployeeNumber,
       PremiumSign,
       REPLACE(REPLICATE('0',16-LEN(CAST(Premium AS VARCHAR))) + CAST(Premium AS VARCHAR),'.','') AS Premium, 
       CASE WHEN RegistrationDate IS NULL 
            THEN REPLICATE(' ', 8)
            ELSE REPLACE(CONVERT(VARCHAR(10),RegistrationDate,103),'/','')
       END AS RegistrationDate,
       ActivityCode + REPLICATE(' ', 10-LEN(ActivityCode)) AS ActivityCode,
       ActivityDescription + REPLICATE(' ', 255-LEN(ActivityDescription)) AS ActivityDescription,
       PolicyTypeCode + REPLICATE(' ', 10-LEN(PolicyTypeCode)) AS PolicyTypeCode,
       PolicyTypeDescription + REPLICATE(' ', 255-LEN(PolicyTypeDescription)) AS PolicyTypeDescription,
       ContributionCode + REPLICATE(' ', 10-LEN(ContributionCode)) AS ContributionCode,
       ContributionDescription + REPLICATE(' ', 255-LEN(ContributionDescription)) AS ContributionDescription,
       ActivityMilimetra + REPLICATE(' ', 1-LEN(ActivityMilimetra)) AS ActivityMilimetra,
       REPLICATE('0', 8-LEN(SourceCode)) + CAST(SourceCode AS varCHAR) AS SourceCode
FROM FileExtraction.EXTR_MILIMETRA
ORDER BY PolicyNumber

我已按照管理说明创建了一个名为FIELD_ACTIVATIONS的新表,如下所示:

FieldName                                          CategoryID  IsActive
-------------------------------------------------- ----------- --------
PolicyNumber                                       1           1
BOCBranch                                          1           1
CIFNumber                                          1           1
EmployeeNumber                                     1           0
PremiumSign                                        1           0
RegistrationDate                                   1           0
ActivityCode                                       1           0
ActivityDescription                                1           0
PolicyTypeCode                                     1           0
PolicyTypeDescription                              1           0
ContributionCode                                   1           0
ContributionDescription                            1           0
ActivityMilimetra                                  1           0
SourceCode                                         1           0
Premium                                            1           0
PolicyNumber                                       2           0
BOCBranch                                          2           0
CIFNumber                                          2           0
EmployeeNumber                                     2           1
PremiumSign                                        2           1
RegistrationDate                                   2           1
ActivityCode                                       2           0
ActivityDescription                                2           0
PolicyTypeCode                                     2           0
PolicyTypeDescription                              2           0
ContributionCode                                   2           0
ContributionDescription                            2           0
ActivityMilimetra                                  2           0
SourceCode                                         2           0
Premium                                            2           0
PolicyNumber                                       3           0
BOCBranch                                          3           0
CIFNumber                                          3           0
EmployeeNumber                                     3           0
PremiumSign                                        3           0
RegistrationDate                                   3           0
ActivityCode                                       3           1
ActivityDescription                                3           1
PolicyTypeCode                                     3           1
PolicyTypeDescription                              3           0
ContributionCode                                   3           0
ContributionDescription                            3           0
ActivityMilimetra                                  3           0
SourceCode                                         3           0
Premium                                            3           0
PolicyNumber                                       4           0
BOCBranch                                          4           0
CIFNumber                                          4           0
EmployeeNumber                                     4           0
PremiumSign                                        4           0
RegistrationDate                                   4           0
ActivityCode                                       4           0
ActivityDescription                                4           0
PolicyTypeCode                                     4           0
PolicyTypeDescription                              4           1
ContributionCode                                   4           1
ContributionDescription                            4           1
ActivityMilimetra                                  4           1
SourceCode                                         4           1
Premium                                            4           1

您可能会注意到,SELECT语句中的每一列都是表中的FieldName。

我需要做的是仅对FieldName中出现的状态为IsActive = 1的列运行该SELECT语句。对于SELECT查询中的列,状态为IsActive = 0,我仍想选择该列,但将其显示为空列。

这一切都没有永久删除或更改任何表中的任何内容。

我已经尝试过使用案例,子查询,IF,并且如果FIELD_ACTIVATIONS表中的任何详细信息发生更改,我似乎都无法提出不需要将来更改的解决方案。

我也查看了此链接Select records in on table based on conditions from another table?,但是此链接假定两个表中都有一个公共字段。

SELECT查询中显示的名为“ EXTR_MILIMETRA”的主表与FIELD_ACTIVATION没有什么共同之处,除了列名和字段名。

以下是“ EXTR_MILIMETRA”中各列的示例。 (由于屏幕空间有限,因此未显示所有列。)下面显示的每一列是上面的表格的FieldName。

ColumnNames

问这个问题,我有可能由于先前的连续投票而被封锁。如果需要任何其他信息,请先告诉我,而不要投票。如果可以的话。我真的尽力描述了我的问题。

很高兴做出澄清。

2 个答案:

答案 0 :(得分:0)

@NikosV您需要的是动态查询。我称它为@DynamicQuery,并且一种分配要隐藏的列的方法将为它们添加NULL,从而使其输出为空白。看看这个模型,只需将TABLENAME更改为您要从中提取数据的表的实际名称,然后使用您说过创建的实际FIELD_ACTIVATIONS表即可。

@JsonPOJOBuilder(withPrefix = "")
public static class UserBuilder {

    @JsonProperty("user_name")
    @NonNull
    private String userName;
}

输出查询将像这样运行:

DECLARE @FIELD_ACTIVATIONS TABLE (FieldName  varchar(200), CategoryID  int, IsActive bit)

INSERT INTO @FIELD_ACTIVATIONS

SELECT 'PolicyNumber',  1,  1 UNION ALL
SELECT 'BOCBranch', 1,  1 UNION ALL
SELECT 'CIFNumber', 1,  1 UNION ALL
SELECT 'EmployeeNumber',    1,  0 UNION ALL
SELECT 'PremiumSign',   1,  0 UNION ALL
SELECT 'RegistrationDate',  1,  0 UNION ALL
SELECT 'ActivityCode',  1,  0 UNION ALL
SELECT 'ActivityDescription',   1,  0 UNION ALL
SELECT 'PolicyTypeCode',    1,  0 UNION ALL
SELECT 'PolicyTypeDescription', 1,  0 UNION ALL
SELECT 'ContributionCode',  1,  0



DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += FieldName+','
    FROM (SELECT p.FieldName+''+CASE WHEN IsActive=0 THEN '=NULL' ELSE '' END FieldName
    FROM @FIELD_ACTIVATIONS p 

    ) AS x;




DECLARE @Querycolumns VARCHAR(MAX)=(select  left (@columns, Len ( @columns) - 1 ))

DECLARE @Dynamicquery NVARCHAR(MAX) = '

      SELECT '+ @Querycolumns +'
      FROM 
      TABLENAME   
      '

答案 1 :(得分:0)

如何编写取决于您是否需要性能。如果您没有太多的行,则可以这样做:

WITH active AS
(
   SELECT FieldName 
   FROM Field_Activations 
   WHERE CategoryId=1 AND IsActive=1
)
SELECT 
    CASE WHEN EXISTS (SELECT * FROM active WHERE FieldName='PolicyNumber')
    THEN REPLICATE('0', 10-LEN(PolicyNumber)) + PolicyNumber 
    ELSE '' END AS PolicyNumber,
    CASE WHEN EXISTS (SELECT * FROM active WHERE FieldName='BOCBranch')
    then REPLICATE('0', 7-LEN(BOCBranch)) + BOCBranch
    ELSE '' end AS BOCBranch,
    --...
    FROM FileExtraction.EXTR_MILIMETRA
    ORDER BY PolicyNumber;

如果需要一些性能,则可以将上面的查询编写为带有一系列if和execute的动态查询:

DECLARE @SQLString nvarchar(4000);  
declare @active table (FieldName varchar(100));

insert into @active (FieldName)
   SELECT FieldName 
   FROM Field_Activations 
   WHERE CategoryId=1 AND IsActive=1;


SET @SQLString = N'
SELECT ' +
        CASE when EXISTS 
          (SELECT * FROM @active WHERE FieldName = 'PolicyNumber')
        THEN 'REPLICATE(''0'', 10-LEN(PolicyNumber)) + PolicyNumber'
        ELSE '''''' END + ' AS PolicyNumber,' +
        CASE WHEN EXISTS 
          (SELECT * FROM @active WHERE FieldName = 'BOCBranch')
        THEN 'REPLICATE(''0'', 7-LEN(BOCBranch)) + BOCBranch'
        ELSE '''''' end + ' AS BOCBranch,' +
        --... +
        ' FROM FileExtraction.EXTR_MILIMETRA
          ORDER BY PolicyNumber;'
print @SQLString
EXECUTE sp_executesql @SQLString;