【问题标题】:SQL - list all data if a column is emptySQL - 如果列为空,则列出所有数据
【发布时间】:2021-12-13 11:57:04
【问题描述】:
我正在尝试编写一个 WHERE 子句,如果该列为空,它将返回所有数据。我有一个 csv 文件(static_table),其中包括:
如果权限为空,则表示用户需要查看所有内容。
因此,如果 hvfg23 用户登录并运行包含国家、地区和品牌的查询,则无论何时执行查询,用户都可以看到每个国家、欧洲地区和所有品牌的数据。
我现在的查询看起来像这样:
select * from t1
where(select restriction, type from t2 where user_id = {{current_userId()}} )
我无法将查询调整为我所需要的,非常感谢您的帮助。
【问题讨论】:
标签:
sql
value-restriction
【解决方案1】:
如果我很了解您的表的结构,那么这将选择当前用户的权限,然后选择其相关信息以防它不为空,否则选择列,这意味着该列上没有条件
declare @country nvarchar(50), @region nvarchar(50), @brand nvarchar(50)
set @country=(Select [t2].[permission]
from [t2] where [t2].[type]='country'
and [t2].[user_id] = {{current_userId()}})
set @brand=(Select [t2].[permission]
from [t2] where [t2].[type]='brand'
and [t2].[user_id] = {{current_userId()}})
set @region=(Select [t2].[permission]
from [t2] where [t2].[type]='region'
and [t2].[user_id] = {{current_userId()}})
select * from [t1] where
[t1].[country]= case when @country IS NULL
then [t1].[country] else @country end
and [t1].[brand]= case when @brand IS NULL
then [t1].[brand] else @brand end
and [t1].[region]= case when @region IS NULL
then [t1].[region] else @region end