简体   繁体   中英

How to select records from a table when a condition of another table is satisfied

I have this query that runs regularly.

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

I have created a new table called FIELD_ACTIVATIONS as per managerial instructions like so:

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

As you may notice, each column in the SELECT statement, is a FieldName in the table.

What I need to do is to run that SELECT statement only for the columns that appear in FieldName that have a status of IsActive = 1. For the columns in the SELECT query that have a status of IsActive = 0, I would still like to select the column, but display it as an empty column.

This is all without permanently deleting or altering anything from any tables.

I've tried using Cases, Subqueries, IFs and I cannot seem to come up with a solution that will not require future alteration if any details in the FIELD_ACTIVATIONS table change.

I've also looked at this link Select records in on table based on conditions from another table? but this link presumes that there is a common field in both tables.

The main table named as "EXTR_MILIMETRA" displayed in the SELECT query has nothing in common with FIELD_ACTIVATION apart from the column name and the field name.

Here is a sample of the columns in "EXTR_MILIMETRA". (Not all columns are being shown because of limited screen space.) Each column show below is a FieldName is the table above.

COLUMNNAMES

By asking this I'm risking being blocked due to consecutive previous downvotes. If any extra information is needed please let me know first instead of downvoting. If that's ok. I've really tried to describe my problem well enough.

Happy to make any clarifications.

@NikosV you need is a dynamic query. I have called it @DynamicQuery and a method to assign those columns that you are intersted in hiding will have NULL added to them, rendering their output to be blanks. Have a look at this mock up, just change the TABLENAME to the actual name of the table you want to pull the data from and use the actual FIELD_ACTIVATIONS table you said you creatd.

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   
      '

The output query will be run like this :

SELECT PolicyNumber,BOCBranch,CIFNumber,EmployeeNumber=NULL,PremiumSign=NULL,RegistrationDate=NULL,ActivityCode=NULL,ActivityDescription=NULL,PolicyTypeCode=NULL,PolicyTypeDescription=NULL,ContributionCode=NULL
      FROM 
      TABLENAME  

How you would write that depends on if you need performance or not. If you don't have too many rows then you can do it like:

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 you need some performance then you can write the above query as a dynamic query with a series of if and 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM