Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ORER BY in an IF ? 1

Status
Not open for further replies.

irate

Programmer
Jan 29, 2001
92
GB
The following code in the query analyzer gives me an error:
Code:
Server: Msg 156, Level 15, State 1, Procedure searchDynamicContent, Line 18
Incorrect syntax near the keyword 'ORDER'.
Can someone tell me what I am doing wrong please?
Code:
CREATE PROCEDURE searchDynamicContent

		@dynamicArea VARCHAR(25),
		@dynamicTitle VARCHAR(50),
		@dynamicOrder int
AS

SELECT *

FROM		dynamicContent

WHERE		dynamicContentArea = @dynamicArea
	AND	dynamicContentTitle LIKE '%' + @dynamicTitle + '%'
	AND	dynamicContentStatus != 'DELETED'

if (@dynamicOrder = 1)
	begin
   		ORDER BY dynamicContentTitle ASC
	end

GO
 
Code:
CREATE PROCEDURE searchDynamicContent

        @dynamicArea VARCHAR(25),
        @dynamicTitle VARCHAR(50),
        @dynamicOrder int
AS
if (@dynamicOrder = 1)
SELECT *
FROM        dynamicContent
WHERE        dynamicContentArea = @dynamicArea
    AND    dynamicContentTitle LIKE '%' + @dynamicTitle + '%'
    AND    dynamicContentStatus != 'DELETED'
           ORDER BY dynamicContentTitle ASC
else
SELECT *
FROM        dynamicContent
WHERE        dynamicContentArea = @dynamicArea
    AND    dynamicContentTitle LIKE '%' + @dynamicTitle + '%'
    AND    dynamicContentStatus != 'DELETED'
 
irate, you can't use an If statement from within a select statement. SwampBoogie's code should work however.
 
Also can be done with

SELECT *
FROM dynamicContent
WHERE dynamicContentArea = @dynamicArea
AND dynamicContentTitle LIKE '%' + @dynamicTitle + '%'
AND dynamicContentStatus != 'DELETED'
ORDER BY CASE WHEN @dynamicOrder = 1 THEN dynamicContentTitle ELSE 'blahblah' END ASC

Zhavic

---------------------------------------------------------------
In the 1960s you needed the power of two Comodore64s to get a rocket to the moon. Now you need a machine which is a vast number of times more powerful just to run the most popular GUI.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top