2010-11-21 139 views
0

A,B,C,D和E是表中的五列。我需要一個像輸出:SQL插入換行符和格式化數據

A 
newline 
B 
newline 
C 
newline 
D 
newline 
E 

但不能有兩個新行兩列之間(如果爲空),用於如 -

A 
newline 
D 
newline 
E 

所以,如果有B列中沒有數據應該有沒有對應於B的換行符。 現在我正在考慮使用If else循環的縮放函數。有更好的方法嗎?

謝謝。

回答

1

您可以使用我相信的CASE操作符。
http://www.tizag.com/sqlTutorial/sqlcase.php

SELECT CASE WHEN Video_Title IS NOT NULL THEN 
     Video_Title + '\n' 
     ELSE 
     ''  
     END + 

     CASE WHEN Author IS NOT NULL THEN 
     Author + '\n' 
     ELSE 
     '' 
     END + 


     CASE WHEN URL IS NOT NULL THEN 
     URL + '\n' 
     ELSE 
     '' 
     END 
FROM Videos 

這東西我只是想用我自己的數據庫,但我覺得這樣的事情應該做的伎倆:)

1
DECLARE @CRLF CHAR(2) 

SET @CRLF = CHAR(10)+ CHAR(13); 

WITH t AS 
(
SELECT 'A' AS A,'B' AS B, 'C' AS C, 'D' AS D, 'E' AS E UNION ALL 
SELECT 'A' AS A,NULL AS B, NULL AS C, NULL AS D, 'E' AS E UNION ALL 
SELECT NULL AS A,NULL AS B, NULL AS C, NULL AS D, NULL AS E 
) 
SELECT 
ISNULL(STUFF(ISNULL(@CRLF + A,'') + ISNULL(@CRLF + B,'') + ISNULL(@CRLF + C,'') + ISNULL(@CRLF + D,'') +ISNULL(@CRLF + E,'') , 1, 2, ''),'') 
FROM t