简体   繁体   中英

Define a Select via a control table, SQL Server 2008

This is a bit of a weird question, but that's what the customer wants :)

They want to control what is selected via a control table. Reason for that is, that they don't know how the columns will be called in the end.

So when someone wants to run the code, they check how the columns are named and write it down in this control table. There can be up to 4 columns.

So the control table looks like this

Level1      Level2      Level3 Level4
--------------------------------------
columnname1 columnname2 Null   Null 

So the code should select this

SELECT 
     columnname1
     ,columnname2
FROM table

The null values in the control table should be ignored.

I've already tried to do define dynamic parameters and write the select with that, but this of course only works when all 4 columns are filled.

Any ideas?

Thanks

Here is one solution. Select the values into a in-memory table and then select the columns. This isn't that flexible as it requires some manual rework as you progress.

DECLARE @TempTable TABLE
(
    Column1 varchar(50),
    Column2 varchar(50),
    Column3 varchar(50),
    Column4 varchar(50)
)

INSERT INTO @TempTable
    SELECT Level1, Level2, Level3, Level4
    FROM Table

IF EXISTS (SELECT Column1 FROM @TempTable WHERE Column4 = NULL)
BEGIN
    IF EXISTS (SELECT Column1 FROM @TempTable WHERE Column3 = NULL)
    BEGIN
        IF EXISTS (SELECT Column1 FROM @TempTable WHERE Column2 = NULL)
        BEGIN
            SELECT Column1 FROM @TempTable
        END
        ELSE
        BEGIN
            SELECT Column1, Column2 FROM @TempTable
        END
    END
    ELSE 
    BEGIN
        SELECT Column1, Column2, Column3 FROM @TempTable
    END
END
ELSE
BEGIN
    SELECT Column1, Column2, Column3, Column4 FROM @TempTable
END     

SQL FIDDLE

SELECT Level1, Level2, Level3 , Level4 
from table
WHERE Level1 IS NOT NULL AND Level2 IS NOT NULL AND Level3 IS NOT NULL AND Level4 IS NOT NULL

You can write a dynamic query as:

DECLARE @SQLString nvarchar(500);

select @SQLString = 'Select '+ CASE WHEN Level1 IS NULL THEN '' ELSE Level1 END +
                     + CASE WHEN Level2 IS NULL THEN '' ELSE + ' , ' + Level2  END +
                     + CASE WHEN Level3 IS NULL THEN '' ELSE + ' , '+ Level3  END +
                     + CASE WHEN Level4 IS NULL THEN '' ELSE + ' , ' +Level4  END 
                     + ' FROM controltbl '
FROM controltbl

--SELECT @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