在以下示例中,column_name必须是字段为空的实际列的名称
select
id,
name,
address,
shoe_size,
column_name
from
table
where
name = '' OR shoe_size = '' OR address = ''
实现这一目标的正确方法是什么? (SQL Server)
答案 0 :(得分:0)
为单列执行此操作非常简单:
select
id,
name,
address,
shoe_size,
case
when name = '' then 'name'
when show_size = '' then 'shoe_size'
when address = '' then 'address'
else 'multiple fields are empty'
end
from
table
where
name = '' OR shoe_size = '' OR address = ''
当您希望多个列为空时会变得很难看,因为您需要考虑所有可能的组合:
case
when name = '' then 'name'
when shoe_size = '' then 'shoe_size'
when address = '' then 'address'
when name = '' and shoe_size = '' then 'name, shoe_size'
when name = '' and address = '' then 'name, address'
when name = '' and shoe_size = '' and address = '' then 'name, address, shoe_size'
... (you get the picture) ...
end
答案 1 :(得分:0)
例如:
select
id,
name,
address,
shoe_size,
(CASE name
WHEN '' THEN 'name'
ELSE
CASE shoe_size
WHEN '' then 'shoe_size'
else
CASE address
WHEN '' then 'address'
ELSE
'n/a'
END
END
END) as column_name
from
table
where
name = '' OR shoe_size = '' OR address = ''
答案 2 :(得分:0)
这是一种简单的方法,可以轻松扩展以涵盖许多列:
--create a sample table to work with
DECLARE @YourTable table (id int,name varchar(10)
,address varchar(10), shoe_size varchar(10))
--populate that table
INSERT @YourTable VALUES (1,'aa','bb','cc')
INSERT @YourTable VALUES (2,'','bb','cc')
INSERT @YourTable VALUES (3,'aa','','cc')
INSERT @YourTable VALUES (4,'aa','bb','')
INSERT @YourTable VALUES (5,'','','cc')
INSERT @YourTable VALUES (6,'aa','','')
INSERT @YourTable VALUES (7,'','bb','')
INSERT @YourTable VALUES (8,'','','')
SELECT
id
,name
,address
,shoe_size
,STUFF(
CASE WHEN name ='' THEN ', name' ELSE '' END
+CASE WHEN address ='' THEN ', address' ELSE '' END
+CASE WHEN shoe_size ='' THEN ', shoe_size' ELSE '' END
,1,2, ''
) AS column_name
FROM @YourTable
WHERE Name='' OR shoe_size='' OR address=''
输出:
id name address shoe_size column_name
----------- ---------- ---------- ---------- -------------------------
2 bb cc name
3 aa cc address
4 aa bb shoe_size
5 cc name, address
6 aa address, shoe_size
7 bb name, shoe_size
8 name, address, shoe_size
(7 row(s) affected)