如何在选定值的基础上写出条件

时间:2015-09-13 11:41:04

标签: sql-server

我有一个包含20个值的多选下拉列表。 用户可以选择全部或少数。

我想写一个查询

  1. 如果用户选择了所有值,则我不想传递所有选定的值。 (我将传递0以确定所有值都已选中)

  2. 如果使用选择了少数(或不是全部),那么我只想传递那些选定的值。 (我将通过逗号分隔值ex 101,102,103,104)

  3. 根据我想要的值编写连接表或在where条件

    中使用它

    我做了类似下面的事情,但似乎没有用。

    WHERE:抛出错误(Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

    DECLARE @EntitiyIds  AS varchar(2500) = '0'
    SELECT * 
    FROM Tb_CompanyType 
    WHERE Id  IN (
                CASE WHEN @EntitiyIds <> '0' THEN (SELECT Item FROM dbo.Split(@EntitiyIds, ','))
                     WHEN @EntitiyIds =  '0' THEN (SELECT Id FROM Tb_CompanyType) END 
              )
    

    INNER JOIN :(以下没有给出正确的输出)

    DECLARE @EntitiyIds  AS VARCHAR(2500) = '101'
    
    SELECT * FROM Tb_CompanyType CT
    INNER JOIN Tb_Company TC ON 
                            CASE  WHEN @EntitiyIds = '0' AND TC.CompanyId = CT.Id THEN 1
                                  WHEN @EntitiyIds <> '0' AND TC.CompanyId = (SELECT Item FROM dbo.Split(@EntitiyIds, ',')) THEN 1 END = 1
    

    dbo.Split返回包含逗号分隔值的表

    请帮助

2 个答案:

答案 0 :(得分:0)

也许这样的事情。

{{1}}

答案 1 :(得分:0)

从您提供的错误消息中,您的子查询似乎返回了多行。您最后一个查询细分的最后一行似乎有问题:

DECLARE @EntitiyIds  AS VARCHAR(2500) = '101'

SELECT * FROM Tb_CompanyType CT
INNER JOIN Tb_Company TC ON 
                        CASE  WHEN @EntitiyIds = '0' AND TC.CompanyId = CT.Id THEN 1
                              WHEN @EntitiyIds <> '0' AND TC.CompanyId = (SELECT Item FROM dbo.Split(@EntitiyIds, ',')) THEN 1 END = 1

更改最后一个

SELECT Item FROM dbo.Split(@EntitiyIds, ',') 

SELECT top 1 Item FROM dbo.Split(@EntitiyIds, ',')