How to change SQL Order By clause based on a variable expression

by Andrew Jackson 5. July 2009 12:20
DECLARE @SearchType int
DECLARE @SearchText varchar(50)

SET @SearchType = 1
SET @SearchText = 'A'


SELECT
*
FROM
[TableNameGoesHere]
WHERE
(@SearchType=1 AND [Field1] LIKE @SearchText + '%')
OR
(@SearchType=2 AND [Field2] LIKE @SearchText + '%')
ORDER BY
CASE @SearchType
WHEN 1 THEN [Field1]
WHEN 2 THEN [Field2]
END

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Development | SQL

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen