2011-06-14 2 views
0

필드가SQL 서버 - 필드가 비어있는 목록 열 이름은 다음 예제 COLUMN_NAME에서

select 
    id, 
    name, 
    address, 
    shoe_size, 
    column_name 
from 
    table 
where 
    name = '' OR shoe_size = '' OR address = '' 

이 달성의 올바른 방법은 무엇입니까 비어 실제 컬럼의 이름이 필요? 하나의 컬럼이 수행 (SQL 서버)

+0

어쨌든 밖으로 모든 열을 선택하는 경우, 그 컬럼의 간단한 육안 검사가 적절하게 질문에 대답해야한다. –

+0

죄송합니다.로드가 많습니다. 예를 들어 3을 선택했습니다. –

답변

0

은 간단합니다 :

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 
: 당신은 당신이 모든 가능한 조합을 고려할 필요가 있기 때문에 두 개 이상의 열이 비어있을 것으로 예상 할 때 그것은 추한 도착

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 = '' 

+0

빈 칸을 모두 조합하지 않아도됩니다! 그것을 쉽게하는 방법에 대한 내 대답을 참조하십시오. –

+0

@KM : 감사합니다.'STUFF' 방법에 대해 몰랐습니다. 아주 깔끔한. –

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 = '' 
+0

case 문을 중첩하면이 작업이 복잡해지고 한 행에 여러 개의 빈 열이 지원되지 않습니다. –

0

쉽게 사람을 포함하도록 확장 할 수있는 간단한 방법입니다 Y 열 :

--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)