-2

I need a query for order by given parameters My table like this

ID    Name      Type
1    Argentine  Standard
2    Spain      Critical
3    France     Critical
4    Germany    Standard
5    Brazil     Standard
6    Italy      Standard

I am sending the parameter as Germany,Spain,Brazil,Argentine my output should be

ID      Name        Type
4      Germany      Standard
2      Spain        Critical
5      Brazil       Standard
1      Argentine    Standard

At present i used in query and i got the output in order by id that means it shows the result as in database order but i need to order by query parameter order?

can anyone help me for query?

Manoj Kumar
  • 41
  • 1
  • 10
  • 1
    Your question is unclear. Could you show your query? What do you mean by "it shows the result as in database order", data in a database table is unsorted. I think you want to sort by a `case` expression. – HoneyBadger Feb 10 '16 at 08:19
  • select * from Countries where name in ('Germany','Spain','Brazil','Argentine') ORDER BY name – Manoj Kumar Feb 10 '16 at 08:23
  • i need query like it should be ordered by query parameter not by name or id. – Manoj Kumar Feb 10 '16 at 08:23
  • What on earth do you mean by "query parameter"? – HoneyBadger Feb 10 '16 at 08:24
  • using in query i am sending the values that i am mentioning as query parameter "Germany,Spain,Brazil,Argentine" – Manoj Kumar Feb 10 '16 at 08:25
  • 2
    Possible duplicate of [Is it possible to select a specific ORDER BY in SQL Server 2008?](http://stackoverflow.com/questions/10208104/is-it-possible-to-select-a-specific-order-by-in-sql-server-2008) – sagi Feb 10 '16 at 08:26
  • thanks @sagi i've got the query and working fine – Manoj Kumar Feb 10 '16 at 08:29

2 Answers2

1

according to your output I can suggest you this query. You can also alter order by clause as per your requirement:

select id,name,type from stack where name in('Germany','Spain','Brazil','Argentine') order by type,name,id desc
Robert
  • 5,278
  • 43
  • 65
  • 115
0

may be you are sending Comma Separated Input then we can convert them into rows and join with the table Data to get Required Output.

declare @t varchar(50) = ' Germany,Spain,Brazil,Argentine'

Declare @tt table (ID INT IDENTITY(1,1),val varchar(10))
insert into @tt (val)
SELECT 
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Certs
FROM
(
SELECT CAST('<XMLRoot><RowData>' + REPLACE(@t,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x

)t
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)


DECLARE @Table1 TABLE 
    (ID int, Name varchar(9), Type varchar(8))
;

INSERT INTO @Table1
    (ID, Name, Type)
VALUES
    (1, 'Argentine', 'Standard'),
    (2, 'Spain', 'Critical'),
    (3, 'France', 'Critical'),
    (4, 'Germany', 'Standard'),
    (5, 'Brazil', 'Standard'),
    (6, 'Italy', 'Standard')
;

select T.ID,TT.val,T.Type from @Table1 T
INNER JOIN @tt TT
ON T.Name = TT.val
ORDER BY TT.ID
mohan111
  • 8,633
  • 4
  • 28
  • 55