选择直到找到空值

时间:2019-08-29 09:34:06

标签: sql sql-server ssis etl

我遇到一个问题,我尝试从一列中进行选择,直到它标识空值为止。我无法使用行数,因为我担心添加的新项目会改变行数。因此,数据计数不是固定的,而是3行为空的数据是固定的。

这是源示例

This is the source example

加载到SSIS后

After load to SSIS

SELECT  [F1] FROM TEST_TBL WHERE F1 BETWEEN 'MTH' AND NULL 

我的计划是从值MTH中选择,直到找到为空的列并将其保存到新表中。另一个也一样,从值YTD中选择直到找到空列。

到目前为止,我仍然无法解决它,而我在SQL中仍然是新手。谢谢

1 个答案:

答案 0 :(得分:1)

如果您在SSIS流程上添加原始的excel行号并将其存储在SQL上,则由于您现在拥有一组有序的行,因此可以轻松选择所需的行。

设置:

IF OBJECT_ID('tempdb..#Excel') IS NOT NULL
    DROP TABLE #Excel

CREATE TABLE #Excel (
    ID INT IDENTITY, 
    CellContent VARCHAR(100))

INSERT INTO #Excel (
    CellContent)
VALUES
    ('MTH'),
    ('BANK FINANCING'),
    ('CLR A/C - ERROR'),
    ('COMPANY/CORPORATE'),
    ('NULL'),
    ('NULL'),
    ('NULL'),
    ('YTD'),
    ('Account Type'),
    ('BANK FINANCING'),
    ('CLR A/C - ERROR')

解决方案

DECLARE @v_StartingCellContent VARCHAR(100) = 'MTH' -- Change here the first value you want to be displayed from

DECLARE @v_LowerLimit INT = (SELECT MIN(E.ID) FROM #Excel AS E WHERE E.CellContent = @v_StartingCellContent)
DECLARE @v_HigherLimit INT = (SELECT MIN(E.ID) FROM #Excel AS E WHERE E.ID > @v_LowerLimit AND E.CellContent = 'NULL')

SELECT
    *
FROM
    #Excel AS T
WHERE
    T.ID >= @v_LowerLimit AND 
    (@v_HigherLimit IS NULL OR T.ID < @v_HigherLimit)
ORDER BY
    T.ID

结果

ID  CellContent
1   MTH
2   BANK FINANCING
3   CLR A/C - ERROR
4   COMPANY/CORPORATE