A, B, C, D and E are five column开发者_如何学JAVAs in a table. I need output like:
A
newline
B
newline
C
newline
D
newline
E
But there cannot be two newlines between two columns(if one is null), for eg -
A
newline
D
newline
E
So if there is no data in column B there should be no newline corresponding to B. Right now I am thinking of a scaler function with If else loops. Any better way?
Thanks.
You can use the CASE operator i believe.
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
This is something i just tried with my own database, but I think something like this should do the trick :)
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
精彩评论