Avatar of Westside2004
Westside2004Flag for United States of America asked on

Dynamic Stored Procedure Help

Hi,

I am trying to setup a stored procedure that can accept 2 OPTIONAL params.  How can I rewrite this so it does that?  I get a syntax error apparently in my ORDER BY clause.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[p_getList]
(
@sortColumn nvarchar,
@sortDir nvarchar
)
AS
BEGIN
 
SET NOCOUNT ON;
 
SELECT j.code, j.date_created, j.short_desc
FROM JTable j
ORDER BY @sortColumn @sortDir
   
END


Thanks,

-ws
Microsoft SQL Server 2005

Avatar of undefined
Last Comment
dqmq

8/22/2022 - Mon
chapmandew

ALTER PROCEDURE [dbo].[p_getList]
(
@sortColumn nvarchar,
@sortDir nvarchar
)
AS
BEGIN
 
SET NOCOUNT ON;
declare @sql nvarchar(1000)
 
set @sql  = 'SELECT j.code, j.date_created, j.short_desc
FROM JTable j
ORDER BY ' + @sortColumn @sortDir
   
exec @sql
END
ASKER
Westside2004

That gives an error.

Error:  Incorrect syntax near '@sortDir'.

Any idea?

Thanks as always!

-ws
ASKER
Westside2004

ahh.. I just did + @sortDir fixed it I believe
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
Westside2004

Well, I spoke to soon the problem still persists.

Can you try your code again?

Thx
-ws
ASKER CERTIFIED SOLUTION
dqmq

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question