SQL Server:有条件地在存储过程中排除Union的一部分

时间:2012-12-15 12:28:10

标签: sql sql-server sql-server-2008

我有一个这样的存储过程(缩短到必要的最小值):

CREATE PROCEDURE [dbo].[proc_Foo]
    -- Add the parameters for the stored procedure here
    @StyleNumber int,
    @App nvarchar(50),
    @User nvarchar(20)
AS
BEGIN
    DECLARE @UserChar varchar(1) = 'U'

    -- User with App
    SELECT [StyleType],
           [Value], 'UA' AS 'DerivedFrom'
    FROM daten.dbo.GridStyleLocal
    WHERE [StyleAssign] = @UserChar
    AND [User] = @User
    AND [StyleNumber] = @StyleNumber
    AND [Application] = @App

    UNION

    -- Global (Basis) with app
    SELECT [StyleType],
           [Value], 'GA' AS 'DerivedFrom'
    FROM basis.dbo.GridStyle
    WHERE [StyleNumber] = @StyleNumber
    AND [Application] = @App
    AND [StyleType] NOT IN (
        SELECT [StyleType]
        FROM daten.dbo.GridStyleLocal
        WHERE [StyleAssign] = @UserChar
        AND [User] = @User
        AND [StyleNumber] = @StyleNumber
        AND [Application] = @App)

    UNION

    -- Scrape missing StyleTypes from Number 0
    SELECT [StyleType],
           [Value], 'G0A' AS 'DerivedFrom'
    FROM basis.dbo.GridStyle
    WHERE [StyleNumber] = 0
    AND [Application] = @App
    AND [StyleType] NOT IN (
        SELECT [StyleType]
        FROM daten.dbo.GridStyleLocal
        WHERE [StyleAssign] = @UserChar
        AND [User] = @User
        AND [StyleNumber] = @StyleNumber
        AND [Application] = @App)
    AND [StyleType] NOT IN (
        SELECT [StyleType]
        FROM basis.dbo.GridStyle
        WHERE [StyleNumber] = @StyleNumber
        AND [Application] = @App)

END

GO

现在StyleNumber 0是我的基本风格。不在另一个StyleType中的所有属性(StyleNumber)都是从StyleNumber 0派生的。但现在,如果我在应用中包含第二个SELECT(全局(基础)) @StyleNumber设置为0,DerivedFrom值为GA而不是G0A。

那么有没有任何条件,如果SELECT为0,可以将@StyleNumber排除在联合之外?

1 个答案:

答案 0 :(得分:1)

不太清楚你需要什么。假设您需要从第二个查询获得G0A @StyleNumber = 0,请使用{更改您的second select query ( - 全球(基础)与应用) {1}}。

CASE

如果SELECT [StyleType], [Value], CASE @StyleNumber WHEN 0 THEN 'G0A' ELSE 'GA' END AS 'DerivedFrom' FROM basis.dbo.GridStyle --Rest fo the query ,请不要从第二个选择查询中选择任何记录,将@StyleNumber = 0添加到CASE;

WHERE clause