First of all hello to everyone at this forum. I have worked as a .NET developer for about 3 years now in which time I have worked with SQL Server.I am trying to write a stored procedure that is dynamic, trying to avoid having many select statements surrounded by if clauses etc.Here is a rough draft of SQL of what I am working on:DECLARE @StartDate DATETIME, @EndDate DATETIME, @UseStartDateCriteria BIT, @UseEndDateCriteria BIT, @ErrorTypeCriteria VARCHAR(50), @ErrorID BIT, @ErrorType BIT, @Server BIT, @OrderBy VARCHAR(50), @AscDesc VARCHAR(50)SET DATEFORMAT DMYSET @StartDate = '18/09/2006'SET @EndDate = '18/10/2006'SET @EndDate = DATEADD(HOUR, 23, @EndDate)SET @EndDate = DATEADD(MINUTE, 59, @EndDate)SET @EndDate = DATEADD(MINUTE, 59, @EndDate)SET @ErrorTypeCriteria = 'Errors'SET @ErrorID = 1SET @ErrorType = 0SET @Server = 1SET @OrderBy = 'ErrorDate'SET @AscDesc = 'ASC'SELECT CASE WHEN @ErrorID = 1 THEN ErrorID END, CASE WHEN @ErrorType = 1 THEN ErrorType END, CASE WHEN @Server = 1 THEN Server END, FROM [dbo].[ErrorDetails]WHERE ErrorType = @ErrorTypeCriteria AND ErrorDate >= COALESCE(@StartDate,ErrorDate) AND ErrorDate <= COALESCE(@EndDate,ErrorDate)ORDER BYCASE WHEN @OrderBy = 'ErrorID' THEN ErrorID WHEN @OrderBy = 'ErrorType' THEN ErrorType WHEN @OrderBy = 'Server' THEN Server ELSE ErrorDateEND
The first thing I am trying to do is depending on is only select a column if its corresponding bit value is passed in as 1. Let me give an example. In the code above I pass in a parameter ErrorID as a value of 1. In this case I wish the select statement to include ErrorID in the select statement. In the case of ErrorType passed in as 0 I wish this not to be part of the select statement. Iam trying to make the call to the database less draining. Hope this makes sense. As you can see I have made an unsuccessful attempt of this already.Secondly, I am trying to order by dynamically, partly I have had some luck with this. I have managed to dynamically set the field to order by but in addition to this I wish to set the ascending/descending depending on what parameter @AscDesc passes in. I don't seem to have the right code up to now after trying many things.If you can help, please do, thanks, Dave.

