Let us assume we have created a
table and inserted some data into using following sql query:
CREATE TABLE tblSource(
ID INT IDENTITY PRIMARY KEY,
vcData VARCHAR(500)
)
INSERT INTO tblSource VALUES('PC'),('Laptop'),('Mobile')
Variable
in ORDER BY clause in sql server
DECLARE @Col_Name VARCHAR(128) = 'ID'
SELECT *
FROM
tblSource
ORDER BY CONVERT(SYSNAME,@Col_Name) DESC
Output:
ID
|
vcData
|
1
|
PC
|
2
|
Laptop
|
3
|
Mobile
|
Note: There is
limitation of using varaible in ORDER BY clause. We cannot use column position
in order by cluase. For example:
DECLARE @Position INT = 1
SELECT * FROM tblSource ORDER BY @Position DESC
We will get
error message :
No comments:
Post a Comment