where语句带有条件子查询

时间:2013-09-24 08:24:41

标签: sql-server tsql

我想使用以下Statement

DECLARE @MatnrFilter TABLE ( ListValue VARCHAR(50) )

INSERT  INTO @MatnrFilter
    ( ListValue )
VALUES  ( '167436' )
INSERT  INTO @MatnrFilter
        ( ListValue )
VALUES  ( '167447' )

SELECT  *
FROM    ios.BaseData_2013
WHERE   Materialnummer IN ( CASE WHEN ( ( SELECT TOP 1
                                                ListValue
                                      FROM      @MatnrFilter
                                    ) IS NULL ) THEN Materialnummer
                             ELSE ( SELECT  *
                                    FROM    @MatnrFilter
                                  )
                        END ) 

我希望在@MtnrFilter中存在值时进行过滤。这里我收到错误消息

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

还有其他办法吗?

坦克 岸堤

2 个答案:

答案 0 :(得分:1)

WHERE Materialnummer IN (SELECT ListValue FROM @MatnrFilter)
OR NOT EXISTS (SELECT * FROM @MatnrFilter)

似乎会掩盖它。 CASE表达式必须返回单个标量值(每行)。

答案 1 :(得分:0)

将WHERE语句更改为以下内容:

WHERE   NOT EXISTS(SELECT ListValue FROM @MatnrFilter)
        OR Materialnummer IN ( SELECT  ListValue FROM    @MatnrFilter)