how to produce multiple rows into 1 column value or sql statement with comma seperated in T-sql
ColumnName IsOrdered Seq_ID
ABC 2 2
DEF 1 1
GHI 0 NULL
JKL 1 4
MNO 1 3
PQR 0 5
I have a table (table1) in the database with above values stored in it.
Not开发者_运维问答e: -
I. Is_Ordered column: 2 --> Desc; 1 --> Asc; 0 --> Default.
II. Seq_ID column: Column names 'order by' sequence
These values are stored in the above table by user.(i.e. on User interface). I want to produce a 'order by' clause from the multiple rows to a single statement with comma ',' seperated (one single column).
eg: select * from Table1 order by DEF asc, ABC desc, MNO asc, JKL asc
Here I want to write a sql statement to produce just the order by statement as above shown i.e. (order by DEF asc, ABC desc, MNO asc, JKL asc)
Here you will notice that GHI column and PQR columns are not included since these two are not selected in the order by selections in the user interface.
I thank you in advance who tried to understand my question and given an appropriate solution for this.
Here you go (may need to add a CAST)
SELECT
'ORDER BY ' +
SUBSTRING(
(
SELECT
',' + ColumnName +
CASE IsOrdered
WHEN 1 THEN 'ASC'
WHEN 2 THEN 'DESC'
END
FROM
MyTable
WHERE
IsOrdered > 0 -- why have "IsIncluded" column ?
ORDER BY
Seq_ID
FOR XML PATH ('')
)
, 2, 7999)
Hope this helps
DECLARE @OrderBySetting VARCHAR(max) = ''
DECLARE @OrderByString VARCHAR(max) = ''
DECLARE MY_CURSOR CURSOR
FOR SELECT ColumnName + ' ' +
case IsOrdered
WHEN 1 THEN 'ASC'
WHEN 2 THEN 'DESC'
END
+ ','
FROM Table1
WHERE (IsOrdered <> 0)
ORDER BY Seq_ID DESC
OPEN My_Cursor
Fetch NEXT FROM MY_Cursor INTO @OrderBySetting
WHILE @@FETCH_STATUS = 0
BEGIN
SET @OrderByString = @OrderBySetting + @OrderByString
FETCH NEXT FROM MY_Cursor INTO @OrderBySetting
END
CLOSE MY_Cursor
DEALLOCATE MY_Cursor
SET @OrderByString = 'SELECT * FROM TABLE1 ORDER BY ' + SUBSTRING(@OrderByString, 1, LEN(@OrderByString)-1)
精彩评论