sql - 如何在 MS SQL 中的 CASE 条件中编写选择查询

标签 sql sql-server

我有一个 SQL 查询。它没有任何编译错误,但在运行时显示
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

 SELECT a.UserID FROM USERGROUPS a WHERE a.GroupID IN 
                      (CASE WHEN @group_id IS NULL THEN (select groupid from usergroups) ELSE 
                       CASE WHEN @group_id=0 THEN (select groupid from usergroups  where userid = @userid)ELSE
                      @group_id END END )

提前致谢。

最佳答案

试试这个:

SELECT a.UserID 
  FROM USERGROUPS a 
  WHERE 
    (@groupid is NUll and a.GroupID IN   (select groupid from usergroups)) 
     or (@groupid = 0 and a.GroupID IN  (select groupid from usergroups  where (userid = @userid)))
      or a.GroupID IN  (@groupid)

关于sql - 如何在 MS SQL 中的 CASE 条件中编写选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7105530/

相关文章:

sql - Postgres pg_try_advisory_lock 阻塞所有记录

sql - Redshift - 除以零误差

c# - 如何使用 ASP.net 在 SQL 中获取最后插入记录的 ID

sql-server - 使用 SQL Server 作为源时的 AWS DMS 限制 - 复制信息超过 8000 字节的行

sql - 从表中选择前 N 个随机行,然后按列排序

mysql - 差异获取值不在内部连接中

android - “Table” : syntax error附近的E/SQLiteLog:(1)

mysql - 在 Go 中访问 MySQL 查询结果的第二行

sql - 选择返回动态列

mysql - CakePHP - 生成的查询无法与 SQL Server 一起正常工作