您可以使用這將unpivot的的數據可以再使用串聯的FOR XML PATH
值:
;with cte as
(
select id, col, data
from
(
select t.id,
c.col,
case c.col
when 'Price_1' then Price_1
when 'Price_2' then Price_2
when 'Price_3' then Price_3
end as data
from yourtable t
cross join
(
select 'Price_1' as col
union all select 'Price_2'
union all select 'Price_3'
) c
) src
where isnumeric(data) = 0
)
select distinct c1.id,
stuff((select ', ' + col
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_columns,
stuff((select ', ' + data
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_Values
from cte c1
見SQL Fiddle with Demo。
這也可以使用unpivot
功能寫着:
;with cte as
(
select id, col, data
from yourtable
unpivot
(
data
for col in ([Price_1], [Price_2], [Price_3])
) unpiv
where isnumeric(data) = 0
)
select distinct c1.id,
stuff((select ', ' + col
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_columns,
stuff((select ', ' + data
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_Values
from cte c1
見SQL Fiddle with Demo。其結果是:
| ID | BAD_COLUMNS | BAD_VALUES |
---------------------------------------
| P3 | Price_1, Price_3 | aa, bb |
| P4 | Price_2 | cc |
好吧,如果你想要某種類型的列值不好的審計表,那麼我強烈建議你不要**連接這些值,在數據庫上這樣做沒有意義。您可以爲每個列的每個不合格值使用同一個表。 – Lamak 2013-03-04 15:57:26
@Lamak感謝您的建議。我只需要生成一個彙總表 – 2013-03-04 16:00:31