T-SQL查看子查询的子句

时间:2013-07-12 14:24:39

标签: sql-server-2008 tsql views subquery

我想看看这是否可行。我正在构建一个需要子查询的视图。但是,子查询需要与主SQL语句具有相同的where子句。

我需要在视图中使用它,因为我必须从另一个表执行JOIN,并且存储过程和表UDF将在我的情况下工作。

我构建了以下示例来展示我正在尝试做的事情:

IF OBJECT_ID('tempdb..#TableA') IS NOT NULL BEGIN DROP TABLE #TableA END
IF OBJECT_ID('tempdb..#TableB') IS NOT NULL BEGIN DROP TABLE #TableB END

Create Table #TableA
(
    Id INT IDENTITY(1, 1)
    , ValueA VARCHAR(10)
)

Create Table #TableB
(
    Id INT IDENTITY(1, 1)
    , TableAID INT
    , ValueB VARCHAR(10)
)

INSERT INTO #TableA VALUES ('Company A'), ('Company B')

INSERT INTO #TableB VALUES (1, '05001'), (1, '05002')
INSERT INTO #TableB VALUES (2, '04001'), (2, '04003')

SELECT
    DISTINCT
    A.ValueA
    , STUFF((SELECT 
                ', ' + B.ValueB
            FROM 
                #TableB B 
            INNER JOIN #TableA A on A.Id = B.TableAID
            WHERE 
                B.ValueB IN ('05001', '05002') --This needs to be part of the main where clause
            FOR XML PATH ('')), 1, 1, '') as TBValue

FROM
    #TableA A
INNER JOIN #TableB B on B.TableAID = A.Id
WHERE
    B.ValueB IN ('05001', '05002') --This will be passed in as the where clause for the View

IF OBJECT_ID('tempdb..#TableA') IS NOT NULL BEGIN DROP TABLE #TableA END
IF OBJECT_ID('tempdb..#TableB') IS NOT NULL BEGIN DROP TABLE #TableB END

上面例子的输出给我们这个:

ValueA     TBValue 
Company A  05001, 05002 

我需要能够使子查询使用与main where子句相同的值,或者重构查询以使用primary where子句以某种方式为子数据。

1 个答案:

答案 0 :(得分:2)

您无法将参数传递到视图中。它们不是为了接受它们而设计的。我相信在这种情况下你需要使用Table-Value(内联表)函数。这将允许您传入所需的值并返回“表格”。

您应该能够使用您已经为视图编写的相同代码,并对函数进行微小更改。您必须声明传入的变量和传出的表值。

CREATE FUNCTION tvf_SomeFunction 
(   
    -- Add the parameters for the function here
    @Value1 varchar(10), 
    @Value2 varchar(10)
)
RETURNS TABLE 
AS
RETURN 

        DECLARE @TableA TABLE
    (
        Id INT IDENTITY(1, 1)
        , ValueA VARCHAR(10)
    )

    DECLARE @TableB TABLE
    (
        Id INT IDENTITY(1, 1)
        , TableAID INT
        , ValueB VARCHAR(10)
    )

    INSERT INTO @TableA VALUES ('Company A'), ('Company B')

    --INSERT INTO @TableB VALUES (1, '05001'), (1, '05002')
    --INSERT INTO @TableB VALUES (2, '04001'), (2, '04003')

    SELECT
        DISTINCT
        A.ValueA
        , STUFF((SELECT 
                    ', ' + B.ValueB
                FROM 
                    @TableB B 
                INNER JOIN @TableA A on A.Id = B.TableAID
                WHERE 
                    B.ValueB IN (@Value1, @Value2) --This needs to be part of the main where clause
                FOR XML PATH ('')), 1, 1, '') as TBValue

    FROM
        @TableA A
    INNER JOIN @TableB B on B.TableAID = A.Id
    WHERE
        B.ValueB IN (@Value1, @Value2) --This will be passed in as the where clause
    )
    GO

您的最终SQL将如下所示:

SELECT *
FROM tvf_SomeFunction('05001', '05002')